In FragmentTransaction item on Android docs, it is described that the method replace()
is the same as calling the method remove()
for all fragments added in the currently view and then called the method add()
. In this case, to recover the previous fragment, we could use addBackToStack()
, it means that transaction state is still being managed by the fragment manager and will reverse its operation when we popped off the stack.
In the other hand, when we implement the transaction using add()
, beyond the use of add().addBackToStack()
, we can use the detach()
method and recovering the fragment using attach()
, which have the same behavior that addBackToStack()
.
So what is the difference behind the scenes between these scenarios?
I researched more and apparently, the difference between detach()
and addToBackStack ()
is in the life cycle of Fragment. When we add the Fragment in the back stack, is called in sequence the methods onPause()
, onStop()
and after the onDestroyView()
. In this state, the fragment clean up the resources associated with its view and "stay" there waiting to be called again. Returning to the layout from the back stack is called the method onCreateView()
just for the fragment to draw its user interface. Actually, the fragment isn't destroyed.
In the other side, when we use detach()
to remove or replace the fragment, is called in sequence all same methods cited first (onPause()
, onStop()
, onDestroyView()
) adding this two methods: onDestroy()
, to do final cleanup of the fragment's state and onDetach()
, to detach the fragment to being no longer associated with its activity.
Basically, behind the scenes, they don't have the same behavior: using the addToBackStack()
the fragments remain instantiated and detach()
, don't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With