Reputation: 1467
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;
}
});
Upvotes: 9
Views: 14333
Reputation: 477
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).
Upvotes: 1
Reputation: 2618
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;
}
Upvotes: 12
Reputation: 2704
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);
.
Upvotes: 1
Reputation: 109
You can find out if an item is current selected with this:
if(navigationView.getMenu().findItem(R.id.nav_item).isChecked())
//do some stuff
Upvotes: 4