Search code examples
androidnavigationview

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


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!


Solution

  • UPDATE

    You can get position using this trick

    final List<MenuItem> items = new ArrayList<>();
    Menu menu;
    
    NavigationView navigationView = (NavigationView) findViewById(R.id.navigation);.
    menu = navigationView.getMenu();
    
    for(int i = 0; i < menu.size(); i++){
        items.add(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.indexOf(menuItem);
    
            return true;
        }
    });