Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic difference between add() and replace() method of Fragment [duplicate]

How do Fragment's replace and add methods work differently, and is there any real life scenario where we would need these methods for specific purposes.

like image 810
Tejinder Singh Avatar asked Jun 28 '14 11:06

Tejinder Singh


People also ask

Which method is called when fragment is replaced?

Use replace() to replace an existing fragment in a container with an instance of a new fragment class that you provide. Calling replace() is equivalent to calling remove() with a fragment in a container and adding a new fragment to that same container. transaction. commit();

What is the purpose of addToBackStack () while commiting fragment transaction?

addToBackStack. 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 Answers

The important difference is:

replace removes the existing fragment and adds a new fragment..

but add retains the existing fragments and adds a new fragment that means existing fragment will be active and they wont be in 'paused' state hence when a back button is pressed onCreateView() is not called for the existing fragment(the fragment which was there before new fragment was added).

For more information just visit this conversation.

like image 188
Ranjit Avatar answered Sep 21 '22 11:09

Ranjit


fragmentTransaction.replace(int containerViewId, Fragment fragment, String tag)

Description - It 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.

fragmentTransaction.add(int containerViewId, Fragment fragment, String tag)

Description - It 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.

Please visit below official android developer link for more details about fragments... http://developer.android.com/guide/components/fragments.html

like image 23
Priyank Patel Avatar answered Sep 25 '22 11:09

Priyank Patel