Get Current Selected Item of Navigation Drawer in Android

akkk picture akkk · Jul 12, 2016 · Viewed 11k times · Source

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;
        }
    });

Answer

Michael Spitsin picture Michael Spitsin · Jul 12, 2016

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;
}