I have a side navigation system, by loading fragments using the property addToBackStack
so that when the back button is pressed, the last fragment on the fragment control stack is retrieved with the getSupportFragmentManager().popBackStack()
.
The problem is that when there are no fragments left in the stack it does not exit the application and the application is displayed as if a blank fragment was loaded, it takes another backstroke to exit the application.
How can I prevent loading the blank fragment and exiting the application if there are no more fragments left on the stack?
The control code onBackPressed
in MainActivity.java:
@Override
public void onBackPressed() {
Log.d(TAG, "onBackPressed()");
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
Log.d(TAG, "close Drawer");
} else {
if (getSupportFragmentManager().getBackStackEntryCount() > 1 ){
getSupportFragmentManager().popBackStack();
Log.d(TAG, "fragment Manager popBackStack()");
} else {
super.onBackPressed();
}
}
}
~~Fixed, replace
super.onBackPressed();
withfinish()
y so the app is forced to close.~~Edit
The load of the first fragment is done with
add
and the others withreplace
.Regarding your question:
finish()
, it's exclusive to closing the Activity and it works, but you're only closing the Activity.the real solution would be not to add the first fragment to the stack, with this you really solve the problem.