How to get MenuItem position in the listener using the new NavigationView

Fhl picture Fhl · Aug 7, 2015 · Viewed 8.5k times · Source

The topic says it all. How should I go about retrieving the item position on the onClick listener using NavigationView? Also, why is there no getHeader method? Lastly I am doing everything programmatically, but the header is still clickable. Any thoughts?

Thanks!

Answer

Rami picture Rami · Feb 23, 2016

I found a simple solution. You can assign an order using Menu's add(...) method. Then you can retrieve the order using MenuItems's getOrder(...) method. If you are using xml, you can use android:orderInCategory="...".

NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);.
Menu menu = navigationView.getMenu();

for(int i=0; i < menu.size(); i++){
    items.add(Menu.NONE, Menu.NONE, i, menu.getItem(i));
}

navigationView.setNavigationItemSelectedListener(new  NavigationView.OnNavigationItemSelectedListener(){
    @Override
    public boolean onNavigationItemSelected(final MenuItem menuItem) {
        // update highlighted item in the navigation menu
        menuItem.setChecked(true);
        int position=items.getOrder();
        return true;
    }
});