changing menu item programmatically is not working in android

后端 未结 2 1227
面向向阳花
面向向阳花 2021-01-24 15:55

I have a menu item and I want to change its visibility programmatically. The menu is this




        
2条回答
  •  逝去的感伤
    2021-01-24 16:03

    Since you did not provide any other code, I can't say much about it.

    However, whenever you want to change the menu, you should call invalidateOptionsMenu(). What that does is it invalidates the menu, which in turn forces it to be recreated. During its recreation, one of the callbacks is onPrepareOptionsMenu(Menu menu). This is where you can make the change to your menu.

    Example:

    // This is where I want to change the menu. Can be anywhere in your activity.
    invalidateOptionsMenu();
    

    Then override this method

    // Override this method to do what you want when the menu is recreated
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.pencil).setVisible(false);
        return super.onPrepareOptionsMenu(menu);
    }
    

提交回复
热议问题