I am using bottom navigation bar. When I click on each items in bottom navigation, Fragment will replace with another one. when I want to press back I want to exit from application. I think this is easy.
But the problem is here: In every Fragment I have button. if we click on button it will replace with another fragment. if I press back button, I want to go to previous fragment that it was in bottom navigation bar. after this if user pressed back again, the app should exit. what should I do?
Should I use onBackPressed()
?
I used this code BUT not working
boolean pressBackForExit = false;
@Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0){
pressBackForExit = true;
}
if (pressBackForExit){
finish();
}
if (getSupportFragmentManager().getBackStackEntryCount() > 0){
getSupportFragmentManager().popBackStack();
if (getSupportFragmentManager().getBackStackEntryCount() == 0){
pressBackForExit = true;
}
}
}
If yes, tell me How?