After reading this and searching in Android documentation, I gave up and decided to ask here.
I'm trying to set a back button in my Navigation Drawer
so that the app will close only from the Home
fragment, and any other fragment will take us back to Home
. For example, if we begin at Home
fragment and navigate to other fragments in the navigation drawer, when we hit the back button we will get to Home
fragment, and if we hit back from Home fragment, we will exit the app.
I have tried to implement it like this:
public void onNavigationDrawerItemSelected(int position) {
...
// If the next fragment is Home, clear the backstack.
if (frag instanceof Home) {
getSupportFragmentManager().popBackStack();
fragmentManager.beginTransaction().replace(R.id.container, frag)
.commit();
}
// If the backstack already contains a transaction, replace the current fragment
else if (getSupportFragmentManager().getBackStackEntryCount() > 0) {
fragmentManager.beginTransaction().replace(R.id.container, frag)
.commit();
}
// If the backstack is empty, insert the Home -> Fragment transaction
else {
fragmentManager.beginTransaction().replace(R.id.container, frag)
.addToBackStack("").commit();
}
...
}
...
@Override
public void onBackPressed() {
if (drawerLayout.isDrawerOpen(Gravity.START)) {
drawerLayout.closeDrawer(Gravity.LEFT);
} else {
super.onBackPressed();
// If returning back to Home fragment, restore action bar title.
if (getSupportFragmentManager().getBackStackEntryCount() > 0)
onSectionAttached(0);
}
}
The link I have attached is not working properly, and the way I implemented is not working consistently. For example, if I navigate from Home to other fragments and back to home (without pressing the back button), my fragments get overlay one another.