Programming and Personal Development

Android Menus Part 1

Every activity in android is associated with a menu. Menus in turn contain menu items and other sub menus. As of android 4.0 ( icecream sandwich), following are the  types of menus available to the developer.

  • Options menu:  Options menu show up when the user clicks on the menu button present in the android devices and are useful for showing global options that affect the entire application.
  • Context menu: Context menus are  the equivalent of right-click menus in desktop programs. You can invoke them with a long click ( touch and hold). They are useful for providing options that are specific to a UI element in the activity.
  • Popup menu: Pop-up menus can be invoked as a result of any UI event such as a button click. Android documentation recommends the use of pop-up menus to only display secondary or extended actions and handle the primary contextual actions in the context menu.

In this post lets focus on the options menu  creation, modification and handling of menu item selections. . We’ll cover the other menu types and their usage in subsequent posts.

Creating a menu

A android menu is composed of menu items and  each menu item has the following four attributes viz.

  • title: a title string or a string resource id
  • id: a integer that uniquely identifies the menu item
  • group id: integer that can be used for manipulating a set of menu items as a single group. eg: disabling all the menu items in a group using the group id
  • sort order: integer used for categorizing the menu items as secondary , system  etc. and determine the relative ordering of the menu items within the menu.

    menu constans available in android

    Android menu constants

To create the options menu, you override the onCreateOptionsMenu (Menu menu) method. This method takes in a menu object associated with the activity as a parameter. You can then call the add() method that takes in a combination of the four attributes mentioned above as parameters to add the desired set of menu items to the menu. At the very least you need to specify the title of the menu item and let android fill in  the default values for the remaining attributes. Android also provides certain menu constants such as Menu.FIRST and Menu.NONE that can be used to generate group and menu ids. Make sure that you return true at the end of this method, otherwise android wont show the menu on the screen.

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(
            Menu.NONE, // Group ID
            Menu.FIRST + 1, // ItemId
            Menu.NONE// ordering
            "Option " + rand.nextInt());// title
    return true; // to make the menu visible
}

Responding to menu item selection

Once the menu is created, you can invoke the menu by clicking the main menu button on the android device. You can respond to specific menu item selections by overriding the onOptionsItemSelected (MenuItem menuItem) method. Android passes the reference to the menu item that was selected by the user as parameter. You can then use this reference to take the desired action on the menu item. Here we display a Toast Message with the menu item’s title and Id.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    String text = item.getTitle() + ":" + item.getItemId();
    Toast.makeText(this, text, Toast.LENGTH_LONG).show();
    return true;
}

Modifying  Options menu at runtime

As of android 3.0, onCreateOptionsMenu () method is called once when the activity is created. Prior to that it was called on the first invocation of the options menu. The change is due to the addition of the action bar to the android 3.0 SDK.  Action bars are the recommended way to handle options for applications developed using 3.0 api and higher. We’ll cover them in a separate post.

What this means is, you cannot add or remove the items from the menu after its created in the onCreateOptionsMenu() method. If you do need to change the contents of the menu dynamically then you ‘ll have to override the  onPrepareOptionsMenu (Menu menu) method. This method gets called each time the menu button is pressed and the current menu object associated with the activity is passed in as a parameter.  You can then modify the menu items inside the method. For example, we can add a new menu item each time the menu button is click as shown below.  You can also force android to call the onCreateOptionsMenu () method again by calling the invalidateOptionsMenu (). This is useful say, when you want to reset the menu back to original state as defined in the onCreateOptionsMenu() method.

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    int size = menu.size();
    MenuItem lastItem = menu.getItem(size - 1);
    int itemId = lastItem.getItemId() + 1;
    menu.add(lastItem.getGroupId(),itemId,lastItem.getOrder(),"option "+ itemId);
    return super.onPrepareOptionsMenu(menu);
}

Happy Coding !!!

Web Analytics