Search This Blog

Saturday 14 July 2012

Disabling menu options when they are not applicable

In the last post we learned how to present the user with menu options when they press the menu button on their phone.  Today we will look at how to disable menu options when they are not applicable.  For example in my Maths Test App, I do not want the user to be able to change Game Preferences in the middle of a game, so I disable the Game Preferences option while a game is in progress (download the Maths Test App from the Android Market / Google Play by searching for Sundev Pabla).

In order to enable and disable menu options at runtime you must override the onPrepareOptionsMenu.  The following extract shows the overridden onPrepareOptionsMenu from my Maths Test App:


    @Override
    public boolean onPrepareOptionsMenu(Menu menu)
    {
    super.onPrepareOptionsMenu(menu);
    // Don't display menu in the middle of a game
    if (!gameOver)
    {
    menu.getItem(0).setEnabled(false);
    }
    else
    {
    menu.getItem(0).setEnabled(true);
   
    }
    return true;    
    }
Essentially what this code is doing is getting the first menu option in my menu collection and either enabling or disabling the menu option depending on the state of the game (In the case of my Maths Test App, I only have one Menu Option so I know it will be the first one in the collection - 0 is used because the collection of menu items is zero based).

Its been a fairly small lesson today, but I believe in doing things in small bite size chunks.  Join me next time to learn how to present the user with custom dialogs and alerts (For example take a look at the dialog that is displayed when the user selects the 'Set Game Preferences' menu option on my Maths Test App).

Good bye for now.

No comments:

Post a Comment