Whats the proper way to handle the selected state of the navigation drawer after back press?
I have a navigation drawer with n entries (in a listview) like the SDK sampl
This is late but for those who are using navigation menu instead of list, here is how i did it
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int position=0;
Fragment fragment;
int id = item.getItemId();
if (id == R.id.nav_home) {
fragment=new HomeFragment();
position=0;
} else if (id == R.id.nav_profile) {
fragment=new ProfileFragment();
position=1;
} else if (id == R.id.nav_settings) {
fragment=new SettingsFragment();
position=2;
}
getSupportFragmentManager()
.beginTransaction()
.add(R.id.relative_container, fragment)
.addToBackStack(""+position)
.commit();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
and add listner for backstack
getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
FragmentManager fm = getSupportFragmentManager();
String name = fm.getBackStackEntryAt(fm.getBackStackEntryCount()-1).getName();
if(!TextUtils.isEmpty(name))
selectNavigationDrawerItem(Integer.parseInt(name));
}
});
selectNavigationDrawerItem method
private void selectNavigationDrawerItem(int position){
if(position==0){
navigationView.setCheckedItem(R.id.nav_home);
}
else if(position==1){
navigationView.setCheckedItem(R.id.nav_profile);
}
else if(position==2){
navigationView.setCheckedItem(R.id.nav_settings);
}
}