I need to change my menu icon based on a condition, however when I use Menu.getItem(index).setIcon() it doesn't change my icon at all. I need help how to do that please

Menu.getItem(index).setIcon()

if (menu != null) {
   if (observedCount != 0)

     menu.getItem(2).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_delete_copy));
  else

     menu.getItem(2).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_cart));

1 Answers

0
Julio E. Rodríguez Cabañas On

Your code looks correct, but maybe you are using it just once inside onCreateOptionsMenu() and missing the calls that are necessary to update the icon as observedCount updates.

Approach 1

You can try doing the following in your activity:

First, override onPrepareOptionsMenu() and apply the changes there:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    if (observedCount != 0)
        menu.getItem(2).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_delete_copy));
    else
        menu.getItem(2).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_cart));

    return super.onPrepareOptionsMenu(menu);
}

Then, whenever you want the icon to be updated (i.e., whenever observedCount changes), just invoke:

invalidateOptionsMenu(); // From a fragment, call activity.invalidateOptionsMenu();

Approach 2

Another option is to save a reference to the menu inside onCreateOptionsMenu():

private Menu mMenu;

...

@Override
public void onCreateOptionsMenu(Menu menu)
{
    getMenuInflater().inflate(R.menu.your_menu, menu);
    mMenu = menu;
}

Then, you can use that reference to set the icon:

if (observedCount != 0)
    mMenu.getItem(2).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_delete_copy));
else
    mMenu.getItem(2).setIcon(ContextCompat.getDrawable(MainActivity.this, R.drawable.ic_cart));

That should hopefully do it!

P.S. Make sure you are getting the correct item when doing menu.getItem(2) (the item number 2 is actually the third one because the count starts at 0). To avoid getting the wrong item, it would be a good idea to set the item you want to change with an ID and then replace menu.getItem(2) with menu.findItem(R.id.your_item_id).