简体   繁体   中英

IllegalStateException: Fragment already added

I got this error:

java.lang.IllegalStateException: Fragment already added: MenuBottomSheetFragment{d476429 #0}
    at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1891)
    at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:760)

My code when open clicked MenuBottomSheetFragment :

private void openBottomSheet() {
        if (mMenuBottomSheetFragment == null)
            mMenuBottomSheetFragment = new MenuBottomSheetFragment();
        if (!mMenuBottomSheetFragment.isShowing())
            mMenuBottomSheetFragment.show(getSupportFragmentManager(), mMenuBottomSheetFragment.getTag());
    }

And my MenuBottomSheetFragment have nothing special.

I really have no idea why. Most of the time, MenuBottomSheetFragment works fine. But some time, it throws this Exception then I do nothing.

So what is the problem in my case? And how can I fix it?

Replace the isShowing with this:

 if(!mMenuBottomSheetFragment.isAdded()) {
      mMenuBottomSheetFragment.show(getSupportFragmentManager(), mMenuBottomSheetFragment.getTag());
 }

The fragment has already been added. There is no need to show it again. Just check it after the null -check and return if it's added:

if(mMenuBottomSheetFragment.isAdded()) {
    return;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM