If you use menu_drawer.xml you just need to add id to elements like this:
<item android:id="@+id/nav_top_stories" android:title="@string/txt.menu.item1" />
With this, you just need to check on menuItm.getId() :
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){ @Override public boolean onNavigationItemSelected(final MenuItem menuItem) { // update highlighted item in the navigation menu menuItem.setChecked(true); switch(menuItem.getId()){ case R.id.txt_menu_item1 : //do what you want to do; break; case R.id.txt_menu_item2 : // etc, } return true; } });
If you use a dynamic menu, simply use this method to add an item to the navigation box:
NavigationView.getMenu().add(int groupId, int itemId, int order, CharSequence title)
And then check the order:
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener(){ @Override public boolean onNavigationItemSelected(final MenuItem menuItem) { // update highlighted item in the navigation menu menuItem.setChecked(true); switch(menuItem.getOrder()){ case 0 : //do what you want to do; break; case 1 : // etc, default : //do whatever you want ; } return true; } });
source share