Difference between add(), replace(), and addToBackStack()
1)
fragmentTransaction.addToBackStack(str);
Description - Add this transaction to the back stack. This means that the transaction will be remembered after it is committed, and will reverse its operation when later popped off the stack.
2)
fragmentTransaction.replace(int containerViewId, Fragment fragment, String tag)
Description - Replace an existing fragment that was added to a container. This is essentially the same as calling remove(Fragment) for all currently added fragments that were added with the same containerViewId and then add(int, Fragment, String) with the same arguments given here.
3)
fragmentTransaction.add(int containerViewId, Fragment fragment, String tag)
Description - Add a fragment to the activity state. This fragment may optionally also have its view (if Fragment.onCreateView returns non-null) into a container view of the activity.
What does it mean to replace an already existing fragment, and adding a fragment to the activity state and adding an activity to the back stack ?
There is a stack in which all the activities in the running state are kept. Fragments belong to the activity. So you can add them to embed them in a activity.
You can combine multiple fragments in a single activity to build a multi-pane UI and reuse a fragment in multiple activities. This is essentially useful when you have defined your fragment container at different layouts. You just need to replace with any other fragment in any layout.
When you navigate to the current layout, you have the id of that container to replace it with the fragment you want.
You can also go back to the previous fragment in the backStack with the
popBackStack()
method. For that you need to add that fragment in the stack using addToBackStack()
and then commit()
to reflect. This is in reverse order with the current on top.findFragmentByTag does this search for tag added by the add/replace method or the addToBackStack method ?
If depends upon how you added the tag. It then just finds a fragment by its tag that you defined before either when inflated from XML or as supplied when added in a transaction.
No comments: