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

前端 未结 8 2386
深忆病人
深忆病人 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:54

    Use below solution and you do not need to worry about which fragment managers you are dealing with,

    Assuming that you must have used a BaseFragment.

    First create an interface:

    public interface OnRequestUpdateListener {
    void onRequestUpdate(final int requestCode, final Intent data);
    
    void setRequestFragment(final BaseFragment requestFragment, int requestCode);
    
    BaseFragment getRequestFragment();
    
    int getRequestCode();
    

    }

    Implement that interface in your BaseFragment

    public class BaseFragment extends Fragment implements OnRequestUpdateListener {
    private BaseFragment requestFragment;
    
    private int requestCode;
    
    @Override
    public void onRequestUpdate(int requestCode, Intent data) {
     // you can implement your logic the same way you do in onActivityResult
    }
    
    @Override
    public void setRequestFragment(BaseFragment requestFragment, int requestCode) {
        this.requestFragment = requestFragment;
        this.requestCode = requestCode;
    }
    
    @Override
    public BaseFragment getRequestFragment() {
        return requestFragment;
    }
    
    @Override
    public int getRequestCode() {
        return requestCode;
    }
    

    }

    Then, replace the setTargetFragment with setRequestFragment and replace getTargetFragment with getRequestFragment.

    Here, you could also user onRequestUpdate in place of onActivityResult.

    This is a custom solution without bothering about the which fragment manager you are using.

    Using getFragmentManager() instead of getChildFragmentManager() would also work but it affects getParentFragment(). If you do not use a getChildFragmentManager() for nested fragment then you will not be able the get the parent fragment by using getParentFragment() in child/nested fragment.

    0 讨论(0)
  • 2020-12-08 10:57

    I had the same problem, definitely an android bug. It happens when you are showing a fragment from another fragment using it as target. As workaround you can use:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        getActivity().getFragmentManager().beginTransaction().add(dialogFrag, "dialog").commit();
    else
        getChildFragmentManager().beginTransaction().add(dialogFrag,"dialog").commit();
    
    0 讨论(0)
提交回复
热议问题