Skip to content Skip to sidebar Skip to footer

Back Button Not Working When Adding Fragment To Backstack

I've been trying to figure this one out. I'll start by saying that there are many StackOverflow solutions but most say to hookup the onBackPressed() myself, which does work, but I

Solution 1:

Override onBackPressed() into your activity and call this in order to remove current fragment from backstack, since you add it.

if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
    getSupportFragmentManager().popBackStackImmediate()
} else {
    finish();
}

This will work only when you add fragment to backstack using addToBackStack() method.

When you add a fragment to backstack to keep tracking your back flow and all the previous changes, that instance will be keeped into FragmentManager. When you want to go back to previous fragment, just pop the latest fragment from backstack. If you don't add it to stack, you will not be able to roll back the taken path and all the previous oprations.

Solution 2:

It looks like you know how to get around the issue you're running into, and your post seems to be asking one specific question, so I'll answer that:

I don't understand why I don't get that behavior for free with the .addToBackStack

It does! But only to a point. The back button will automatically navigate back through the back stack, but it will not close the last fragment, if there is nothing to navigate back to. So, if you were to add another fragment to the back stack (and not override the back button), it would automatically navigate the user back to your first fragment, but then do nothing after that.

Post a Comment for "Back Button Not Working When Adding Fragment To Backstack"