4

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.

SIr Codealot
  • 5,331
  • 9
  • 33
  • 45

3 Answers3

1

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

Community
  • 1
  • 1
Javi Mollá
  • 786
  • 7
  • 18
  • in regard to fragments: why does the back button not pop the top of the stack immediately? – SIr Codealot Feb 17 '15 at 15:29
  • 2
    It's because onBackPressed is called on an activity level. It acts over activities, not over fragments. Fragments are app's responsibility. Here you have another way to handle it: http://stackoverflow.com/a/22552865/4576054 – Javi Mollá Feb 17 '15 at 15:38
0

Simply call

 findNavController().popBackStack()
Amal
  • 261
  • 4
  • 9
  • 2
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Jul 26 '22 at 14:19
-1

add below line:

addToBackStack("Some String").commit();

You can find solution Here.

Community
  • 1
  • 1
sandeepmaaram
  • 4,191
  • 2
  • 37
  • 42