I have a method where the custom Toolbar is initialized to which I attached the Menu. I need to change icons for menu items from another method. How to access them?

public void initToolbar() { toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.refresh: return true; case R.id.back: return true; } return false; } }); toolbar.inflateMenu(R.menu.menu_toolbar); } 

    3 answers 3

    To access the menu that is in the ToolBar , you need to use the getMenu() method of the ToolBar , and then search for the menu item by ID.

     toolbar.getMenu().findItem(R.id.refresh).setIcon(R.mipmap.ic_back); 
      1. We drive in Google line:

      android change menu icon programmatically

      1. We go on the first link

      2. We get the answer :

      Create a variable in the activation class

       private Menu menu; 

      In the onCreateOptionsMenu () activation method, we initialize it

       this.menu = menu; 

      Then in the right place we find the desired item and change the icon:

       menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.ic_launcher)); 

        I do this: get a local variable private Menu menu . Then do the following:

         @Override public boolean onCreateOptionsMenu(Menu menu) { this.menu = menu; getMenuInflater().inflate(R.menu.menu_news, menu); return true; } 

        After that, this method can change the icons:

         private void updateMenuIcons() { MenuItem menuItem = menu.findItem(R.id.icon); menuItem.setIcon(getResources().getDrawable(R.drawable.ic_launcher)); } 

        I don’t know how correct it is, but it works for me.

        • I have already tried this in the menu line MenuItem menuItem = menu.findItem (R.id.icon); throws out cash pointer - Camel
        • under debug see what happens first: initialize the toolbar or onCreateOptionsMenu? - Android Android
        • Already figured out, I do not have the menu as such, I only have the ToolBar in which I put the menu items. It was necessary to get the Menu and MenuItem from the ToolBar. - Camel