Delete a fragment that doesn't fit on the stack in my case

Suppose I have two fragments: firstFragment


I know that I can replace the snippet with:

fragmentTransaction.replace(, firstFragment);


As in the above code, I have not added the above firstFragment

to the back stack .

Then I replace with secondFragment

, but this time I add secondFragment

to the back stack :

fragmentTransaction.replace(, secondFragment);
fragmentTransaction.addToBackStack(null); //add to back stack


Is now displayed on my mobile screen secondFragment


My question is, how can I remove firstFragment

that is not added to the back stack ?


source to share

2 answers

After detaching the fragment, the fragment will be destroyed. To ensure that your snippet is still in the layout, you can use the Hierarchical View perspective. To use the Hierarchy Viewer, you must be using an emulator or embedded device. (Http://

However, if you are using android-support-v4.jar support for 1.6 and above support, make sure you are not defining fragments in the xml layout. Fragments in XML layout cannot be removed when using android-v4.jar support. Just do this if you are using fragments that will be displayed all the time (e.g. navigation)

Edit: Replace should remove the first snippet as well. Replace will replace all children inside the container with the given chunk.



you can detach the first snippet from the ui. see the doc for more help

or you can try remove

EDIT: stand in the document:

If you don't call addToBackStack () when executing a transaction that deletes a chunk, then that chunk is destroyed when the transaction commits and the user cannot return to it.

So what you need, I think, is to call remove.



All Articles