Question

Basically the situation is like this: I have an Activity, which displays a three Fragments within a FragmentPagerAdapter, and within one of these Fragment, I nest another Fragment. I added the fragments like this:

fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.add(rootView.getId(), new MainPageFragment(), "lpt2");
fragmentTransaction.commit();

When I try to call getParentFragment() inside of MainPageFragment(), it returns null. How can that be? I checked multiple posts here on stackoverflow as well as on other blogs, and they all came to the conclusion that if you nest one fragment within another one, calling getParentFragment should return its parent fragment. Returning null means, that the parent is an activity as stated here. Which is not the case. Please tell me I'm making some kind of silly mistakes :\

This is the Fragment that is a child to the main Activity

public class MainPage extends Fragment {

private FragmentTransaction fragmentTransaction;
private View rootView;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
           Bundle savedInstanceState) {
        global_var = new Global();
        rootView = inflater.inflate(R.layout.main_page, container, false);
        return rootView;
}
@Override
public void onViewCreated (View view, Bundle savedInstanceState) {      
    fragmentTransaction = getFragmentManager().beginTransaction();
    fragmentTransaction.add(rootView.getId(), new MainPageFragment(), "lpt2");
    fragmentTransaction.commit();
}
}

This is the Fragment which is a child to the Main Page Fragment

public class MainPageFragment extends Fragment{
private View rootView;
private Fragment parentFragment;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.main_page_list, container, false);
    if (getParentFragment() == null) Log.i("damn", "it");
    return rootView;
   }

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onViewCreated(view, savedInstanceState);
}
}

Please tell me if I need to provide more code, I extracted things like ListView and so on because I thought it would be irrelevant.

Edit: I'm using android.support.v4.app

Was it helpful?

Solution

Check that you have pass FragmentManager reference to all of your Fragments from your FragmentPagerAdapter and then use getParentFragment(). May be this will help you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top