I'm trying to make the back or back button of android keep the sequence of fragments that I'm rendering according to the option chosen in my navigation menu (Navigation Drawer), however I can not, it always closes the app when I click on it back and does not return the previous pro fragment where it was. I'm doing the following:
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
switch (id) {
case R.id.nav_home:
myFragment = new SliderFragment();
break;
case R.id.nav_program:
myFragment = new ProgramFragment();
break;
case R.id.nav_ticket:
myFragment = new TicketFragment();
break;
case R.id.nav_togo:
myFragment = new HowtogoFragment();
break;
case R.id.nav_map:
myFragment = new MapFragment();
break;
case R.id.nav_social:
myFragment = new SocialFragment();
break;
case R.id.nav_festival:
myFragment = new FestivalFragment();
break;
case R.id.nav_contact:
myFragment = new ContactFragment();
break;
}
setTitle(item.getTitle(););
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.content_frame, myFragment)
.addToBackStack(null)
.commit();
return true;
}
And I'm not getting the click of the button back like this:
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
How could I keep the button back normally? Returning always to the previous fragment, with action bar title and corresponding selected menu item?