Difference Between Fragmenttransaction.add And Fragmenttransaction.replace
Solution 1:
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.
Solution 2:
Two choices
Let's say you have a fragment container. And, your task is to add a fragment into the container.
You can do this by calling any of the following methods
1) add(containerId,fragment)
2) replace(containerId,fragment)
But both methods differ in behavior !!!
Although both methods will add your fragment into the fragment container, their innards(internal working) differ based on the two possible states of the fragment container. When fragment container 1) does not have any fragment in it. 2) already have one or multiple fragments attached to it.
Let's see what happens when we call add()
and replace()
method.
Case 1: When there is no fragment attached in a container
In this case, both methods will add the fragment to the container. So they will produce same effect.
Case 2: When the fragmentContainer already has fragment/fragments
add()
: adds the new fragment on the top another fragment
replace()
: removes everything then adds the new fragment
Example
So suppose the Fragment container has fragments[A->B->C]
.
Now you want to add a new fragment D
.
add()
method result will be [A->B->C->D]
replace()
method result will be [D]
Relevant Link:
Check this Demo project for better understanding.
Post a Comment for "Difference Between Fragmenttransaction.add And Fragmenttransaction.replace"