0

I've a 4 tab bottom navigation used with the navigation component for setup. The problem is, after navigating through the tab of the bottom nav for a while, pressing the back button takes me through every fragment/tab I've visited before getting back to the first tab and exit the app.

What can I do to modify this behavior, I think normally the first back button should take the user back to the first tab then the second closes the app. How can I achieve this behavior ?

Kareem Waleed
  • 93
  • 1
  • 10

1 Answers1

0

Set up a global variable called backCount in your MainActivity class, and as you navigate around, keep setting the backCount = 0. Then in all of your other Activities, override the onBackPressed() method:

@Override
public void onBackPressed()
{
     backCount += 1;
     if (backCount >= 2) {
        finish();
        System.exit(0);
     }

     super.onBackPressed();  // optional depending on your needs
}
Michael Dougan
  • 1,698
  • 1
  • 9
  • 13