Get Current Selected Item of Navigation Drawer in Android

12,252

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:
12,252
akkk
Author by

akkk

Updated on June 19, 2022

Comments

  • akkk
    akkk almost 2 years

    How can i get Current selected item of navigation drawer? My menu is stored in drawer_menu.xml

    navigationView = (NavigationView) findViewById(R.id.navigation_view);
        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.change_sec:
                        Intent intent_sec = new Intent(MainActivity.this, ClassDataProvider.class);
                        startActivityForResult(intent_sec, 9);
                        drawerLayout.closeDrawers();
                        break;
                    case R.id.holiday_list:
                        Intent intent = new Intent(MainActivity.this, HolidayList.class);
                        startActivity(intent);
                        drawerLayout.closeDrawers();
                        break;
                }
                return true;
            }
        });