1

I have one Activity, and four types of fragment A,B,C,D

  1. first I'll show an instance of fragA in HomeActivity - (FRAGMENT 1)

  2. from FRAGMENT1 I'll load an instance of fragB(FRAGMENT 2)(_this transaction added to backstack)

  3. from FRAGMENT 2 I'll load new instance of fragA(FRAGMENT 3)(not old one), (this transaction is NOT added to backstack) (So FRAGMENT 2 should be destroyed)

  4. Now I'll press backButton, and this will go to FRAGMENT 1(So FRAGMENT 3 will be destroyed as i think)

    and fragment1 from backstack is loaded. At this point, We can assume now there are no fragments in backstack.(which means if i click back it would close app)

  5. now from this FRAGMENT 1, I will go to FRAGMENT 4(instance of fragC) , (this transaction i will add to backstack).

  6. Now I'll press BackButton,

  7. Now theoretically, it should load FRAGMENT 1(instance of fragA). but FRAGMENT 3(instance of fragA) is getting loaded.

(I am wondering how come FRAGMENT3 came into picture, it was removed and not added to backstack).

and other similar issues comes to picture, if i go further

and this is my code in onbackpressed

  @Override
     public void onBackPressed() {

    if(getSupportFragmentManager().getBackStackEntryCount() > 1){

        getSupportFragmentManager().popBackStackImmediate();
    }else {
        super.onBackPressed();

    }
}
Community
  • 1
  • 1

1 Answers1

0

I think you don't need to call popBackStackImmediately() in your implementation of onBackPressed. It always worked for me without manually popping the BackStack. (One thing I do in onBackPressed() for example is making sure that the NavigationDrawer is closed).

So probably you pop the backstack twice: One time it is done automatically and one time you trigger it by calling popBackStackImmediately(). This could lead to some problems and unexpected behaviour when switching the fragments.

l7r7
  • 1,134
  • 1
  • 7
  • 23