androidandroid-fragmentsandroid-fragmentactivity

Need for popBackStack in onBackPressed


Please help me understand how back stack works natively when "onBackPressed" is called. I noticed that even though visually it went back to the previous fragment, the fragment that was supposedly popped (that I exited from) is still in the back stack. Why is that? I will then have to resort to

    @Override
    public void onBackPressed() {
        if(getFragmentManager().getBackStackEntryCount() > 0)
             getFragmentManager().popBackStack();
    }

which seems counter-intuitive. Is it true then to be on a fragment that isn't at the top of the back stack? Not much of a stack then...

Edit: to clarify, my question is why is onBackPressed not popping the back stack already and that an extra call is required to pop it as a workaround? I'm fine if that's just the way it is but I'd like confirmation.


Solution

  • Android apps have one stack of activities. When onBackPressed is called on an activity it pops back the previous activity and finishes current

    If you have an activity with fragments you'll have another stack, activity's fragments stack, that you control if you override onBackPressed the way that solution proposes so your activity does not finish until all their fragments have been popped back