How to replace fragment C with fragment A when back button is pressed?

Harshal Kshatriya picture Harshal Kshatriya · Dec 21, 2012 · Viewed 40.2k times · Source

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?

Answer

user697495 picture user697495 · Feb 5, 2013

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();
  }
}