I am building an android app that uses a drawer navigation and it looks and works well except i cant add the current view (fragment) to the back stack to get allow the user navigate the app more easily. at the moment the back button just exits the app when pressed. i have looked at various questions on here and none have worked.
Here is my current attempt and dont understand why it dosent work.
if (id == R.id.nav_gallery) {
// fragmentManager.beginTransaction().replace(R.id.content_frame, new GalleryFragment()).commit();
// fragmentManager.beginTransaction().addToBackStack(null);
FragmentTransaction ft = fragmentManager.beginTransaction();
ft.replace(R.id.content_frame, new GalleryFragment());
ft.addToBackStack(null);
ft.commit();
}
edit
onbackPressed
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
FragmentManager fragmentManager = getFragmentManager();
int backCount = fragmentManager.getBackStackEntryCount();
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
if you want to control your transaction when back button pressed of android then use below code
@Override
public void onBackPressed() {
// initialize variables
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
// check to see if stack is empty
if (fm.getBackStackEntryCount() > 0) {
fm.popBackStack();
ft.commit();
}
else {
if (this.lastBackPressTime < System.currentTimeMillis() - 4000) {
Toast.makeText(this, "Nochmal drücken zum Beenden!", 4000).show();
this.lastBackPressTime = System.currentTimeMillis();
} else{
super.onBackPressed();
}
}
}