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