FragmentManager popBackStack doesn't remove fragment

I found that the problem was not in the logic of adding and removing fragment of the stack.

The problem was that some of the fragment loaded another fragments inside of it (it had ViewPager component). Then I thought that when the fragment was removed then these fragments were removed too.

This is true ONLY if you use getChildFragmentManager() method. This method MUST be used when loading fragments inside other fragmets. If not, then the fragments are asociated with the fragments activity.


I found this question, because after calling

fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

this code fragmentManager.getFragments().size() returns me the maximum number of fragments, which were in the stack. I checked every fragment on null. And I found that some fragment is null in my case. Maybe it will help someone)


popBackStack will just revert your last FragmentTransaction.

If you use FragmentTransaction.add, popBackStack will just call FragmentTransacetion.remove.

But if you call FragmentTransaction.replace, popBackStack will call FragmentTransaction.remove and FragmentTransaction.add

For your "NOTE 1" : FragmentTransaction.replace will not change your fragment state.