Change the icon to Toolbar Android

459 Views Asked by At

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.

1

There are 1 best solutions below

0
On

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);