0

I have a HomeFragment1, ClassFragment2, QuestionFragment3, LastFragment4. The user will navigate in the order mentioned. I want to return to HomeFragment1 from anywhere the user presses back button.

I tried removing addToBackStack in all fragments except HomeFragment1 but when pressing back button the fragments overlap.

I wrote in the onBackPressed() of the MainActivity as below:

if(getFragmentManager().getBackStackEntryCount() > 0 ) {
    fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
    super.onBackPressed();
}

But it returns from 4 to 3 to 2 to 1 in this order for each back press. I would like to go directly to 1 from any fragment.

itabdullah
  • 605
  • 1
  • 8
  • 22
  • Duplicate https://stackoverflow.com/questions/28360913/popbackstack-but-keep-the-first-fragment-in-android – Ankit Aman Oct 24 '19 at 16:46
  • fragmentManager.popBackStack ("fragmentATagName", FragmentManager.POP_BACK_STACK_INCLUSIVE); – Ankit Aman Oct 24 '19 at 16:48
  • 1
    This link https://stackoverflow.com/questions/7992216/android-fragment-handle-back-button-press the same like your question issues you can try it. – Htut Nov 05 '19 at 10:50
  • 1
    This link https://stackoverflow.com/questions/7992216/android-fragment-handle-back-button-press the same like your question. – Htut Nov 05 '19 at 10:51

1 Answers1

1

What worked for me is:

1) It is necessary to add all fragments to backstack using addToBackStack("text"). Because not adding any fragment to backstack will make it overlap with previous fragment when back pressed.

2) Then we need to clear the backstack using following lines of code which should be added to onBackPressed() overridden method.

if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
                getSupportFragmentManager().popBackStack(getSupportFragmentManager()
    .getBackStackEntryAt(0).getId(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
} else {
    super.onBackPressed();
}

or simply

getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);

There are a lot of answers found for this question as mentioned below but the one worked for me is above.

Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

Clear back stack using fragments

PopBackStack but keep the first fragment in android

How to clear Fragment backstack in android

Thanks to @Ankit Aman for the link.

itabdullah
  • 605
  • 1
  • 8
  • 22