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

bgolson picture bgolson · Nov 7, 2013 · Viewed 21.6k times · Source

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.

Answer

Jason Hu picture Jason Hu · Nov 8, 2013

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.