Android fragment nested in another fragment: getParentFragment() returns 0

主宰稳场 提交于 2020-01-02 10:17:23

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/22500973/android-fragment-nested-in-another-fragment-getparentfragment-returns-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!