Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Enabling MenuItems by code

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.

like image 577
mauricio Avatar asked Dec 13 '22 20:12

mauricio


2 Answers

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.

like image 141
Dan Avatar answered Jan 18 '23 11:01

Dan


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);
}
like image 44
Pony Avatar answered Jan 18 '23 10:01

Pony