How do I inflate an Android options menu and set an item to Enabled=false?

Try menu.findItem() instead of getItem(). getItem() takes an index from [0, size) while findItem() takes an id.


this is what I do in my activity for the menu handling ...

//Android Activity Lifecycle Method
// This is only called once, the first time the options menu is displayed.
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);
    return true;
}


//Android Activity Lifecycle Method
// Called when a panel's menu is opened by the user.
@Override
public boolean onMenuOpened(int featureId, Menu menu)
{
    MenuItem mnuLogOut = menu.findItem(R.id.main_menu_log_out_id);
    MenuItem mnuLogIn = menu.findItem(R.id.main_menu_log_in_id);
    MenuItem mnuOptions = menu.findItem(R.id.main_menu_options_id);
    MenuItem mnuProfile = menu.findItem(R.id.main_menu_profile_id);


    //set the menu options depending on login status
    if (mBoolLoggedIn == true)
    {
        //show the log out option
        mnuLogOut.setVisible(true);
        mnuLogIn.setVisible(false);

        //show the options selection
        mnuOptions.setVisible(true);

        //show the edit profile selection
        mnuProfile.setVisible(true);
    }
    else
    {
        //show the log in option
        mnuLogOut.setVisible(false);
        mnuLogIn.setVisible(true);

        //hide the options selection
        mnuOptions.setVisible(false);

        //hide the edit profile selection
        mnuProfile.setVisible(false);
    }

    return true;
}


//Android Activity Lifecycle Method
// called whenever an item in your options menu is selected
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
    // Handle item selection
    switch (item.getItemId())
    {

    case R.id.main_menu_log_in_id:
    {
        ShowLoginUI();
        return true;
    }

    case R.id.main_menu_log_out_id:
    {
        ShowGoodbyeUI();
        return true;
    }

    case R.id.main_menu_options_id:
    {
        ShowOptionsUI();
        return true;
    }

    case R.id.main_menu_profile_id:
    {
        ShowProfileUI();
        return true;
    }

    default:
        return super.onOptionsItemSelected(item);
    }
}

I like this approach because it makes the code nice and modular


Use menu.findItem() instead of getItem(). because findItem is used to find item by id.

Tags:

Android