Why is Android O failing with “does not belong to this FragmentManager!”

前端 未结 8 2392
深忆病人
深忆病人 2020-12-08 10:23

I have migrated my application to Android O in Android Studio 3

Running on an Android O emulator all my dialogFragments now fail with :-

java.lang.I         


        
8条回答
  •  既然无缘
    2020-12-08 10:34

    For me this was not only an issue on Android O but also on older versions. The oldest version I tested was API Level 16.

    I was instantiating my fragments using this code:

    MyFragment myFragment = MyFragment.newInstance();
    myFragment.setTargetFragment(ParentFragment.this, 0);
    myFragment.show(getActivity().getSupportFragmentManager(), null);
    

    Where ParentFragment.this is a custom class extending android.support.v4.app.Fragment, MyFragment also extends this class and is a child fragment of the ParentFragment fragment (hence it's name).

    I thought that I had to use a SupportFragmentManager (the getSupportFragmentManager() method) because I am using a fragment of the support package so I tried to call getActivity().getSupportFragmentManager() to get an activity reference that supported this method.

    This does not seem to be the correct way though. I changed those calls to:

    MyFragment myFragment = MyFragment.newInstance();
    myFragment.setTargetFragment(ParentFragment.this, 0);
    myFragment.show(getFragmentManager(), null);
    

    so the fragment decides on it's own which FragmentManager to use and the error is gone now.

    Hope this helps someone.

提交回复
热议问题