0

I want know if I can change the menu item icon after the menu it's initialized, this is my code:

   public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {


        super.onCreateOptionsMenu(menu, inflater);
        menu.clear();
        inflater.inflate(R.menu.right_menu, menu);
        this.menu = menu;

        updateMenuButton();
    }

public void updateMenuButton() {

    if (menu != null) {
        if (verificato) {
            this.menu.getItem(R.id.action_home).setIcon(R.drawable.ic_clear_white_24dp);
        } else {
            this.menu.getItem(R.id.action_home).setIcon(R.drawable.ic_done_white_24dp);
        }
    }

}

I call updateMenuButton at the end of onCreateOptionsMenu, but when try to access to this:

this.menu.getItem(R.id.action_home).setIcon(R.drawable.ic_clear_white_24dp);

I get this error:

java.lang.IndexOutOfBoundsException: Invalid index 2131624115, size is 1

so I think that the item menu is not added yet? if i remove the updateMenuButton() call at the end of onCreateOptionsMenu I can see the Menu Item.

How can I do?

Thanks

Piero
  • 9,173
  • 18
  • 90
  • 160
  • you can do something like this http://stackoverflow.com/questions/7765184/how-can-i-refresh-the-actionbar-when-onprepareoptionsmenu-switched-menu-entries – android_eng Sep 16 '16 at 10:06

1 Answers1

0

That because "getItem(int index)" gets the menu item at the given index. I think you have to write menu.getItem(0);

JoWeber
  • 68
  • 4