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.
Just had the same problem. Happens if you accidentally use the getItem()
instead of findItem()
.
MenuItem menuItem = menu.findItem(R.id.menu_item);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With