I'm new to Android development and developing an application using Android's default Navigation drawer layout.
I'm using fragment in the application.
I want to get back to previous fragment when back button is pressed on next fragment. The onBackPress must implement following functions
This is what my code is in MainActivity while creating new fragment
// replacing the fragment
if (fragment != null) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
}
onBackPress
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getFragmentManager().getBackStackEntryCount() > 0) {
FragmentManager fm = getSupportFragmentManager();
fm.popBackStack();
} else {
super.onBackPressed();
}
}
But this is not working and on pressing back exits the application except when Navigation drawer is open it is closed.
You are not adding the fragment to the backstack. You just have to do
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
.replace(R.id.content_frame, fragment);
.addToBackStack(null);
.commit();
And since the Backstack is actually handled by the back button, you do not need to handle this scenario in onBackPressed()
, so you can change it to just:
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}