Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it OK to addToBackStack and replace in a fragment transaction?

Any thoughts on the following code? In my testing I've found the replaced fragment isn't destroyed and the instance is still around when popping the back stack. Just looking to verify that this is a valid way to use fragment transactions.

getSupportFragmentManager().beginTransaction().addToBackStack(null).replace(frame, fragmentB).commit();

My reason for using replace is that it causes the replaced fragment to run it's exit animation.

like image 843
bgolson Avatar asked Nov 07 '13 20:11

bgolson


People also ask

When to use add and replace in fragment?

One more important difference between add and replace is this: replace removes the existing fragment and adds a new fragment. This means when you press back button the fragment that got replaced will be created with its onCreateView being invoked.

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.

What happens when fragment is replaced?

The removed fragment is moved to the DESTROYED state. 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.

When replacing a fragment with another one how do you know that the user can get back to the last fragment when they press the back button?

The title of the toolbar should change between the two fragments (from "First Fragment" to "Second Fragment"). The second fragment should have a "back button" (arrow left icon) in the toolbar that, on click, lets the user go back to the first fragment.


1 Answers

You can refer to the android designer guide for fragment transaction: http://developer.android.com/guide/components/fragments.html

Specificly the snippet below:

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

So yes, what you are doing is the correct approach in replacing fragments.

like image 128
Jason Hu Avatar answered Oct 17 '22 05:10

Jason Hu