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

后端 未结 5 1247
攒了一身酷
攒了一身酷 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:37

    If you are using menu_drawer.xml, you just have to add an id in the items like this:

    
    

    With this you just have to test 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 are using dynamic menu, just use this method to add an item to you navigation drawer:

    NavigationView.getMenu().add(int groupId, int itemId, int order, CharSequence title)
    

    And then test by 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;
        }
    });
    

提交回复
热议问题