How to change MenuItem icon in ActionBar programmatically

后端 未结 9 1634
小鲜肉
小鲜肉 2020-11-30 23:37

How to change MenuItem icon in ActionBar programmatically? I tried to use

MenuItem menuItem = (MenuItem)findViewById(R.id.action_settings);
menuItem.setIcon(         


        
9条回答
  •  死守一世寂寞
    2020-11-30 23:41

    You can't use findViewById() on menu items in onCreate() because the menu layout isn't inflated yet. You could create a global Menu variable and initialize it in the onCreateOptionsMenu() and then use it in your onClick().

    private Menu menu;
    

    In your onCreateOptionsMenu()

    this.menu = menu;
    

    In your button's onClick() method

    menu.getItem(0).setIcon(ContextCompat.getDrawable(this, R.drawable.ic_launcher));
    

提交回复
热议问题