Get Current Selected Item of Navigation Drawer in Android

Solution 1

For example, you can use:

private int getCheckedItem(NavigationView navigationView) {
    Menu menu = navigationView.getMenu();
    for (int i = 0; i < menu.size(); i++) {
        MenuItem item = menu.getItem(i);
        if (item.isChecked()) {
            return i;
        }
    } 

    return -1;
}

Solution 2

You can find out if an item is current selected with this:

if(navigationView.getMenu().findItem(R.id.nav_item).isChecked())
//do some stuff

Solution 3

You've got OnNavigationItemSelectedListener, with method onNavigationItemSelected(MenuItem item), which is called every time new item is selected. This item has methods getItemId() which will return id, and get getOrder(), which will return position.

Create int var in your class, save this id.

For example you can save it to bundle later on onSaveInstanceState, then get it back on onRestorInstanceState. And apply it using navigationView.setCheckedItem(savedItemId);.

Solution 4

In my case I always mantain a global reference to the nav controller like this on my MainActivity:

navController = findNavController(R.id.nav_host_fragment)

If I need to know on which menu item my user is currently I just get the current destination's id like this:

val menuId = (activity as MainActivity).navController.currentDestination?.id

You can compare the menuId with the defined ids at your navigation graph (which are the same ids you should have for your menu items).

Share:
Admin
Author by

Admin

Updated on June 19, 2022

Comments

  • Admin
    Admin about 2 months

Related