1

How can I get an icon from the toolbar to be changed to a new one that I get with a method that is seen in a bbdd. The problem is that I can not access the event that updates the activity to be able to change the icon. I tried with the onPrepareOptionsMenu method, but I can not make it work. I have not been able to do this by putting the code in onStart because it tells me that the menu object is empty or invalid.

public boolean onPrepareOptionsMenu(Menu menu) {
    menu.clear();
    Drawable iconoMenu = obtenerIconoMenuCarro();
    getMenuInflater().inflate(R.menu.menu_categorias, menu);
    menu.getItem(0).setIcon(iconoMenu);
    return super.onPrepareOptionsMenu(menu);

}

    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_categorias, menu);
    Drawable iconoMenu = obtenerIconoMenuCarro();
    menu.getItem(0).setIcon(iconoMenu);
    return true;
}

My activities are extended by AppCompactActivity and loaded through an AdapterView. And I have the problem when I go back to the fragmentDialog or since the next activity.

Thanks.

ferdiado
  • 369
  • 3
  • 8
  • 1
    [This post](http://stackoverflow.com/questions/19882443/how-to-change-menuitem-icon-in-actionbar-programatically) has many options to do what you want. You could set a global boolean, and when you want to update the menu item, by calling `invalidateOptionsMenu()`, change the boolean to true. Then in `onPrepareOptionsMenu`, if the boolean is true, change the icon without need to clear the menu. – Blo Dec 27 '16 at 00:35
  • Thanks, I solicionate the problem. – ferdiado Dec 27 '16 at 19:13
  • 1
    @ferdiado Uh, what's `solicionate`? – Gurupad Mamadapur Dec 28 '16 at 12:50
  • @GurupadMamadapur It is spanish means "apply" – Rod_Algonquin Oct 26 '18 at 14:19

1 Answers1

0

For me the simplest way was to keep a reference to the MenuItem for later use.

Obtain when the menu item is inflated.

    MenuItem menuItem; 

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);

        //find the menu item from the id
        menuItem = menu.findItem(R.id.myMenuItem);
        return true;
    }

Then change the image where you need to with mipmap resource or @drawable.

    menuItem.setIcon(R.mipmap.ic_other_icon);