difference between fragmentTransaction.add and fragmentTransaction.replace

Wood picture Wood · Dec 19, 2013 · Viewed 25.4k times · Source

What I already known is:

after fragmentTransaction.replace(), current fragment's onStop() function will be called while fragmentTransaction.add() won't.

and after calling fragMgr.popBackStack();, we will return to previous fragment no matter fragmentTransaction.replace or fragmentTransaction.add() is used

So what does fragmentTransaction.replace do?

I can understand we can "add" a fragment opon a previous fragment and later return to previous fragment by popBackStack(), BUT:

if previous fragment is "replaced" by current fragment, I guess previous fragment is removed and current fragment is added in, how can it return to previous fragment when popBackStack() called?

Answer

Kuffs picture Kuffs · Dec 19, 2013

You can add multiple fragments to a container and they will be layered one on top of the other. If your fragments have transparent backgrounds you will see this effect and will be able to interact with the multiple fragments at the same time.

This is what will happen if you use FragmentTransaction.add on a container. Your added fragment will be placed on top of your existing fragment.

If you use FragmentTransaction.replace(R.id.container,fragment) it will remove any fragments that are already in the container and add your new one to the same container.

You can also use the add method without a container id and your fragment will simply be added to the list of fragments in the FragmentManager and you can recall these at any time by their Tag value.

You can still return to a previous configuration IF you added the transaction to back stack. You can do this even if a previous operation removed a fragment. The removed fragment is remembered in the transaction and popping the back stack brings it back.