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

后端 未结 5 1246
攒了一身酷
攒了一身酷 2020-12-19 02:44

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 d

5条回答
  •  生来不讨喜
    2020-12-19 03:15

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

提交回复
热议问题