0

I have a bug where a fragment just refuses to be removed. I have been through a dozen other posts here with near identical titles, but none of the solutions apply to my problem.

The fragment is added like this:

CustomFragment fragment = new CustomFragment();

fragmentManager.beginTransaction().replace(R.id.fragment_container, fragment, "fragment_tag").commit();

It is not added to backstack.

Then it is removed like this:

Fragment fragmentToRemove = fragmentManager.findFragmentByTag("fragment_tag");
if (fragmentToRemove != null) {
    fragmentManager.beginTransaction().remove(fragmentToRemove).commit();
}

To make sure I check:

fragmentManager.getFragments() -> empty
fragmentManager.getBackStackEntryCount() -> 0

Seems fine and dandy, right? But when I then call:

fragmentManager.findFragmentByTag("fragment_tag");

I still find the same fragment, with the same id, that I just removed. What gives? I have lost track of all the things I have tried, suffice to say that obvious things like popBackStackImmediate() and commitNow() did not work. Hoping someone else has run into this one before and can tell me what I am missing.

Breiby
  • 554
  • 5
  • 14
  • Is it possible that your fragment is retained (`Fragment.setRetainInstance(true)`) ? – bwt Mar 07 '19 at 18:01
  • @bwt `fragmentToRemove.getRetainInstance()` is false. – Breiby Mar 08 '19 at 09:37
  • Maybe [enableDebugLogging()](https://developer.android.com/reference/android/app/FragmentManager#enableDebugLogging(boolean)) and [dump()](https://developer.android.com/reference/android/app/FragmentManager.html#dump(java.lang.String,%20java.io.FileDescriptor,%20java.io.PrintWriter,%20java.lang.String%5B%5D)) could help understand what is happening – bwt Mar 08 '19 at 11:48
  • @bwt Already looked into it quite a lot through the debugger. `mRemoving` is true, `mAdded`, `mRetainInstance` and `mRetaining` are false. `mBackStackNesting` is 0, meaning it is not in backstack. The fragment is not in the fragment manager's `mAdded` list, but it is in `mActive`. – Breiby Mar 08 '19 at 12:18
  • I think this could be a bug caused by a fragment being removed while still in `Fragment.INITIALIZING` state, which results in `makeInactive()` never being called in `FragmentManagerImpl.moveToState()`. – Breiby Mar 08 '19 at 14:26

0 Answers0