Reputation: 4485
When I try to update my MenuItem in menu I recieve IndexOutOfBoundsException.
I've added menu_item in xml and I can see it when enable() == false.
My code:
public boolean onPrepareOptionsMenu(Menu menu) {
if ( enable() ) {
MenuItem menuItem= menu.getItem(R.id.menu_item);
menuItem.setEnabled(true);
}
return super.onPrepareOptionsMenu(menu);
}
How to deal with the problem?
Cheers.
Upvotes: 10
Views: 2277
Reputation: 5375
Just had the same problem. Happens if you accidentally use the getItem()
instead of findItem()
.
MenuItem menuItem = menu.findItem(R.id.menu_item);
Upvotes: 56
Reputation: 3063
Probably you need to Clean your project to update the values of R. If you prefer another way, you can do
for(int i = 0; i<menu.size();++i)
{
if(menu.getItem(i).getItemId() == R.id.menu_item)
MenuItem menuItem = menu.getItem(i);
}
or opt for a more beautiful
menu.findItem(R.id.menu_item);
Upvotes: 1