hotspring hotspring - 4 months ago 33
Android Question

Get selected menu item's index value in the navigation drawer

I have implemented navigation drawer, it is working fine. The only problem that I have to make selected item to deselect when the navigationdrawer closes. I wonder how could I able to get the index value of selected menu item.

navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
menuItem.setChecked(false);
}
)}

N J N J
Answer

One way to do is store menu item ID in variable e.g checkedItemID

navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
  @Override
  public boolean onNavigationItemSelected(MenuItem menuItem) {
      menuItemID=menuItem.getItemId();
   }
)}

Then on implement

mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {

        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            // Do whatever you want here

         navigationView.getMenu().findItem(menuItemID).setChecked(false);
        }

        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            // Do whatever you want here
        }
    };
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);