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?
Theory
Use the
addToBackStack(tag:String):FragmentTransaction
method from within theFragmentTransaction
in order to mark a point where you want to return to. This method returns theFragmentTransaction
instance for chain-ability only.Then Return with the
popBackStackImmediate(tag:String,flag:int):void
method from theFragmentManager
. The tag is what you specified before. The flag is either the constantPOP_BACK_STACK_INCLUSIVE
to include the transaction marked or0
.Example
What follows is an example with the following layout having a
FrameLayout
with idcontent_frame
where the fragments are loaded into.The code below marks a fragment by it's fragment class name when replacing the content of the layout element with id
content_frame
.And to complete this example a method that allows you to get back to that exact same fragment using the tag when you loaded it.
When implementing this for real you might want to add a null check on the fragment parameter ;-).
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
Transition from B->C will use a similar transaction with "FragmentC" as its tag.
Then in your containing Activity override onBackPressed():