2

I use BackStack to store fragments and it works fine. However when I want to remove a fragment from BackStack, nothing happens. I checked some questions like this and saw that they do remove an item from BackStack by using popBackStack, like me, but it does not work for me.

This is my code:

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    int count = getSupportFragmentManager().getBackStackEntryCount();

    String currentTag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
    Fragment currentInstance = getSupportFragmentManager().findFragmentByTag(currentTag);
    fragmentTransaction.remove(currentInstance);
    fragmentTransaction.commit();
    fragmentManager.popBackStack(getSupportFragmentManager().getBackStackEntryCount() - 1, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    int count1 = getSupportFragmentManager().getBackStackEntryCount();

currentInstance shows the topmost fragment correctly. Interestingly count and count1 are equals and the topmost item in stack remains after using popBackStack command. So I cant remove the topmost fragment from stack.

If use this code:

        String previousTag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
        Fragment previousInstance = getSupportFragmentManager().findFragmentByTag(previousTag);

        fragmentTransaction.replace(R.id.container_body, previousInstance,previousTag);
        fragmentTransaction.commit();

I could replace fragment with previous one, but it's not correct way to do that, because I can't back for more than one fragment.

Community
  • 1
  • 1
Taher
  • 1,185
  • 3
  • 18
  • 36

1 Answers1

4

I found it out: popBackStack method does not pop immediately after call. So in I have to use popBackStackImmediate method instead of popBackStack. This is my final corrected code:

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (getSupportFragmentManager().getBackStackEntryCount()> 0) {
   fragmentManager.popBackStackImmediate(getSupportFragmentManager().getBackStackEntryCount() - 1, FragmentManager.POP_BACK_STACK_INCLUSIVE);

   String previousTag = getSupportFragmentManager().getBackStackEntryAt(getSupportFragmentManager().getBackStackEntryCount() - 1).getName();
   Fragment previousInstance = getSupportFragmentManager().findFragmentByTag(previousTag);

  fragmentTransaction.replace(R.id.container_body, previousInstance, previousTag);
  fragmentTransaction.commit();
}
Taher
  • 1,185
  • 3
  • 18
  • 36