I need to enable a MenuItem when a previous screen (Activity) returns.
I tried this code:
... ((MenuItem)findViewById(R.id.menu_how)).setEnabled(true); ...
but a null pointer exception is launched.
BTW, the menu_how is set to false in xml; and the code is part of onActivityResult(int requestCode, int resultCode, Intent data) call.
Try using menu.findItem(R.id.menu_how)
in onCreateOptionsMenu and save a reference for later use.
This should work fine with enabled
, however, I've found that setting a menu item to invisible in the XML means you can't show/hide it programmatically.
I found something at the android dev site that might be helpful (look for the section "Changing menu items at runtime")
It said that the onCreateOptionsMenu()
method fired only when the the menu for the activity is created, and it happens when this activity starts. So if you want to change the menu items after the menu/activity was created, you need to override the onPrepareOptionsMenu()
method instead. search the link for full details.
EDIT:
Just made it and it's working fine. I'm using one boolean var
per menuItem
which represents if this item should be enabled or not. This is my code:
/*************************************Game Menu**************************************/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId())
{
case R.id.gm_new_game:
//newGame();
return true;
case R.id.gm_stand_up:
//some code when "gm_stand_up" button clicked..
return true;
case R.id.gm_forfeit:
//some code when "gm_forfeit" button clicked..
return true;
case R.id.gm_surrender:
//some code when "gm_surrender" button clicked..
return true;
case R.id.gm_exit_table:
exitTableCommand();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
menu.findItem(R.id.gm_forfeit).setEnabled(forfeitMenuButtonIsEnabled);
menu.findItem(R.id.gm_surrender).setEnabled(surrenderMenuButtonIsEnabled);
menu.findItem(R.id.gm_new_game).setEnabled(newGameMenuButtonIsEnabled);
menu.findItem(R.id.gm_stand_up).setEnabled(standUpMenuButtonIsEnabled);
return super.onPrepareOptionsMenu(menu);
}
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