How to get an MenuItem by id

前端 未结 3 1046
-上瘾入骨i
-上瘾入骨i 2021-01-01 18:08

I have my menuItem on my res/menu/student_marks.xml file:



        
相关标签:
3条回答
  • 2021-01-01 18:55
    Menu optionsMenu;
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
           getMenuInflater().inflate(R.menu.main, menu);
           //  store the menu to var when creating options menu
           optionsMenu = menu;
        }
    

    example: change icon on first menuItem (optionsMenu should be != null)

    optionsMenu.getItem(0).setIcon(getResources()
        .getDrawable(R.drawable.ic_action_green));
    
    0 讨论(0)
  • 2021-01-01 19:01

    If your menu inside NavigationView example:

    <com.google.android.material.navigation.NavigationView 
        android:id="@+id/navigationView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/menu_layout" />
    

    then you can find your menu item by id like this

    NavigationView navigationView = findViewById(R.id.navigationView);
    Menu menu = navigationView.getMenu();
    MenuItem menuItem = menu.findItem(R.id.your_menu_item_id);
    
    0 讨论(0)
  • 2021-01-01 19:06
    Menu optionsMenu;
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
       getMenuInflater().inflate(R.menu.main, menu);
       //  store the menu to var when creating options menu
       optionsMenu = menu;
    }
    

    And to get a menu item:

    MenuItem item = optionsMenu.findItem(R.id. action_selected_year);
    
    0 讨论(0)
提交回复
热议问题