Failure saving state - target not in fragment manager (setTargetFragment)

后端 未结 8 1417
北荒
北荒 2020-12-23 14:06

I\'ve got a monkey crash whereby

java.lang.IllegalStateException: Failure saving state: FragmentB has target not in fragment manager: FragmentA
at android.s         


        
8条回答
  •  萌比男神i
    2020-12-23 14:37

    I just faced this problem and this is what I think is happening and how I fixed it:

    Your FragmentA instance is being destroyed and another one is being created when there is a device rotation, for example. When this happens, your FragmentB keeps holding a reference to a FragmentA which doesn't exist anymore.

    In this case, you have to reset FragmentB's target to be the new FragmentA instance.

    I did that with the following code in FragmentA:

    @Override
        public void onAttach(Context context) {
    
            super.onAttach(context);
    
            FragmentB fragment = (FragmentB) getFragmentManager().findFragmentByTag(FragmentBtag);
    
            if (fragment != null) {
                fragment.setTargetFragment(this, 0);
            }
    
    
        }
    

    This way, whenever the FragmentA is attached to the Context, ie: a device rotation happens, FragmentB's target is reset, if FragmentB was created at first hand (if so, it would be on FragmentManager).

    I hope it helps.

提交回复
热议问题