Reputation: 42602
Suppose I have two fragments: firstFragment
, and secondFragment
I know I can replace a fragment by:
fragmentTransaction.replace(R.id.fragment_placeholder, firstFragment);
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.commit();
Like the above code shows, I did not add the above firstFragment
to back stack.
Then, I replace with the secondFragment
, But this time, I add the secondFragment
to back stack:
fragmentTransaction.replace(R.id.fragment_placeholder, secondFragment);
fragmentTransaction.addToBackStack(null); //add to back stack
fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
fragmentTransaction.commit();
On my mobile screen, it is now showing the secondFragment
.
My question is, how can I remove the firstFragment
which is not added to back stack ?
Upvotes: 3
Views: 3252
Reputation: 822
After detaching the fragment the fragment will be destroyed. To make sure wether your fragment is still in the layout you can use the "Hierarchy Viewer" perspective. To use the hierarchy viewer you have to use an emulator or a rooted device though. (http://developer.android.com/guide/topics/fundamentals/fragments.html#Creating)
However if you use the android-support-v4.jar to support 1.6 and higher make sure you don't define any fragments in a xml-layout. The fragments in the xml-layout can't be removed when you use android-support-v4.jar. Just do it, if you use fragments which will be displayed all the time (e.g. navigation)
Edit: Replace should remove the firstfragment as well. Replace will replace all children inside the container with the given fragment.
Upvotes: 2
Reputation: 157447
you can detach the first fragment from the ui. see the doc for more reference
or you can try remove
EDIT: standing at the doc:
If you do not call addToBackStack() when you perform a transaction that removes a fragment, then that fragment is destroyed when the transaction is committed and the user cannot navigate back to it.
So what you need, I think, is to call remove.
Upvotes: 1