My scenario : Activity 1 consists of Fragments A-> B-> C. All the fragments are added using this code :
FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.replace(R.id.content, fragment, TAG); ft.addToBackStack(TAG); ft.commit();
Now, from fragment C, I want to directly return to Fragment A. Therefore, I've commented ft.addToBackStack(TAG)
while adding Fragment C. So when I press back button from C I directly get Fragment A on the screen.
However, Fragment C is not replaced by A. In fact, both the fragments are visible. How do I solve this issue?
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();
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.
But you can create your own interface called Replaceable with a method onReplace() that you have your fragment implement, and call it directly when you call FragmentTransaction. replace() .
You need to do 2 things - name the FragmentTransaction from A->B and then override onBackPressed() in your containing activity to call FragmentManager#popBackStack (String name, int flags) when you are on Fragment C. Example:
Transition from A->B
getSupportFragmentManager() .beginTransaction() .replace(R.id.container, new FragmentB(), "FragmentB") .addToBackStack("A_B_TAG") .commit();
Transition from B->C will use a similar transaction with "FragmentC" as its tag.
Then in your containing Activity override onBackPressed():
@Override public void onBackPressed() { if (getSupportFragmentManager().findFragmentByTag("FragmentC") != null) { // I'm viewing Fragment C getSupportFragmentManager().popBackStack("A_B_TAG", FragmentManager.POP_BACK_STACK_INCLUSIVE); } else { super.onBackPressed(); } }
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