Learning Resources
 

Android Adding Menus


Menus are a common user interface component in many types of applications. To provide a familiar and consistent user experience, you should use the MenuAPIs to present user actions and other options in your activities.

Beginning with Android 3.0 (API level 11), Android-powered devices are no longer required to provide a dedicated Menu button. With this change, Android apps should migrate away from a dependence on the traditional 6-item menu panel and instead provide an action bar to present common user actions.

Although the design and user experience for some menu items have changed, the semantics to define a set of actions and options is still based on the MenuAPIs. This guide shows how to create the three fundamental types of menus or action presentations on all versions of Android:

Options menu and action bar
The options menu is the primary collection of menu items for an activity. It's where you should place actions that have a global impact on the app, such as "Search," "Compose email," and "Settings."

If you're developing for Android 2.3 or lower, users can reveal the options menu panel by pressing the Menu button.

On Android 3.0 and higher, items from the options menu are presented by the action bar as a combination of on-screen action items and overflow options. Beginning with Android 3.0, the Menu button is deprecated (some devices don't have one), so you should migrate toward using the action bar to provide access to actions and other options.

See the section about Creating an Options Menu.

Context menu and contextual action mode
A context menu is a floating menu that appears when the user performs a long-click on an element. It provides actions that affect the selected content or context frame.

When developing for Android 3.0 and higher, you should instead use the contextual action mode to enable actions on selected content. This mode displays action items that affect the selected content in a bar at the top of the screen and allows the user to select multiple items.

See the section about Creating Contextual Menus.

Popup menu
A popup menu displays a list of items in a vertical list that's anchored to the view that invoked the menu. It's good for providing an overflow of actions that relate to specific content or to provide options for a second part of a command. Actions in a popup menu should not directly affect the corresponding content—that's what contextual actions are for. Rather, the popup menu is for extended actions that relate to regions of content in your activity.

See the section about Creating a Popup Menu.

Defining a Menu in XML


For all menu types, Android provides a standard XML format to define menu items. Instead of building a menu in your activity's code, you should define a menu and all its items in an XML menu resource. You can then inflate the menu resource (load it as a Menuobject) in your activity or fragment.

Using a menu resource is a good practice for a few reasons:

  • It's easier to visualize the menu structure in XML.
  • It separates the content for the menu from your application's behavioral code.
  • It allows you to create alternative menu configurations for different platform versions, screen sizes, and other configurations by leveraging the app resources framework.

To define the menu, create an XML file inside your project's res/menu/directory and build the menu with the following elements:

Defines a Menu, which is a container for menu items. A element must be the root node for the file and can hold one or more and elements.
Creates a MenuItem, which represents a single item in a menu. This element may contain a nested element in order to create a submenu.
An optional, invisible container for elements. It allows you to categorize menu items so they share properties such as active state and visibility. For more information, see the section about Creating Menu Groups.

Here's an example menu named game_menu.xml:

xml version="1.0" encoding="utf-8"?>
 xmlns:android="https://schemas.android.com/apk/res/android">
     android:id="@+id/new_game"
          android:icon="@drawable/ic_new_game"
          android:title="@string/new_game"
          android:showAsAction="ifRoom"/>
     android:id="@+id/help"
          android:icon="@drawable/ic_help"
          android:title="@string/help" />

The element supports several attributes you can use to define an item's appearance and behavior. The items in the above menu include the following attributes:

android:id
A resource ID that's unique to the item, which allows the application can recognize the item when the user selects it.
android:icon
A reference to a drawable to use as the item's icon.
android:title
A reference to a string to use as the item's title.
android:showAsAction
Specifies when and how this item should appear as an action item in the action bar.

These are the most important attributes you should use, but there are many more available. For information about all the supported attributes, see the Menu Resource document.

You can add a submenu to an item in any menu (except a submenu) by adding a

element as the child of an . Submenus are useful when your application has a lot of functions that can be organized into topics, like items in a PC application's menu bar (File, Edit, View, etc.). For example:

xml version="1.0" encoding="utf-8"?>
 xmlns:android="https://schemas.android.com/apk/res/android">
     android:id="@+id/file"
          android:title="@string/file" >
        
        
             android:id="@+id/create_new"
                  android:title="@string/create_new" />
             android:id="@+id/open"
                  android:title="@string/open" />
        
    

To use the menu in your activity, you need to inflate the menu resource (convert the XML resource into a programmable object) using MenuInflater.inflate(). In the following sections, you'll see how to inflate a menu for each menu type.

Creating an Options Menu


Figure 1. Options menu in the Browser, on Android 2.3.

The options menu is where you should include actions and other options that are relevant to the current activity context, such as "Search," "Compose email," and "Settings."

Where the items in your options menu appear on the screen depends on the version for which you've developed your application:

  • If you've developed your application for Android 2.3.x (API level 10) or lower, the contents of your options menu appear at the bottom of the screen when the user presses the Menu button, as shown in figure 1. When opened, the first visible portion is the icon menu, which holds up to six menu items. If your menu includes more than six items, Android places the sixth item and the rest into the overflow menu, which the user can open by selecting More.
  • If you've developed your application for Android 3.0 (API level 11) and higher, items from the options menu are available in the action bar. By default, the system places all items in the action overflow, which the user can reveal with the action overflow icon on the right side of the action bar (or by pressing the device Menu button, if available). To enable quick access to important actions, you can promote a few items to appear in the action bar by adding android:showAsAction="ifRoom"to the corresponding elements (see figure 2).

    For more information about action items and other action bar behaviors, see the Action Bar guide.

    Note: Even if you're not developing for Android 3.0 or higher, you can build your own action bar layout for a similar effect. For an example of how you can support older versions of Android with an action bar, see the Action Bar Compatibility sample.

Figure 2. Action bar from the Honeycomb Gallery app, showing navigation tabs and a camera action item (plus the action overflow button).

You can declare items for the options menu from either your Activitysubclass or a Fragmentsubclass. If both your activity and fragment(s) declare items for the options menu, they are combined in the UI. The activity's items appear first, followed by those of each fragment in the order in which each fragment is added to the activity. If necessary, you can re-order the menu items with the android:orderInCategoryattribute in each you need to move.

To specify the options menu for an activity, override onCreateOptionsMenu()(fragments provide their own onCreateOptionsMenu()callback). In this method, you can inflate your menu resource (defined in XML) into the Menuprovided in the callback. For example:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}

You can also add menu items using add()and retrieve items with findItem()to revise their properties with MenuItemAPIs.

If you've developed your application for Android 2.3.x and lower, the system calls onCreateOptionsMenu()to create the options menu when the user opens the menu for the first time. If you've developed for Android 3.0 and higher, the system calls onCreateOptionsMenu()when starting the activity, in order to show items to the action bar.

Handling click events

When the user selects an item from the options menu (including action items in the action bar), the system calls your activity's onOptionsItemSelected()method. This method passes the MenuItemselected. You can identify the item by calling getItemId(), which returns the unique ID for the menu item (defined by the android:idattribute in the menu resource or with an integer given to the add()method). You can match this ID against known menu items to perform the appropriate action. For example:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.new_game:
            newGame();
            return true;
        case R.id.help:
            showHelp();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

When you successfully handle a menu item, return true. If you don't handle the menu item, you should call the superclass implementation of onOptionsItemSelected()(the default implementation returns false).

If your activity includes fragments, the system first calls onOptionsItemSelected()for the activity then for each fragment (in the order each fragment was added) until one returns trueor all fragments have been called.

Tip: Android 3.0 adds the ability for you to define the on-click behavior for a menu item in XML, using the android:onClickattribute. The value for the attribute must be the name of a method defined by the activity using the menu. The method must be public and accept a single MenuItemparameter—when the system calls this method, it passes the menu item selected. For more information and an example, see the Menu Resource document.

Tip: If your application contains multiple activities and some of them provide the same options menu, consider creating an activity that implements nothing except the onCreateOptionsMenu()and onOptionsItemSelected()methods. Then extend this class for each activity that should share the same options menu. This way, you can manage one set of code for handling menu actions and each descendant class inherits the menu behaviors. If you want to add menu items to one of the descendant activities, override onCreateOptionsMenu()in that activity. Call super.onCreateOptionsMenu(menu)so the original menu items are created, then add new menu items with menu.add(). You can also override the super class's behavior for individual menu items.

Changing menu items at runtime

After the system calls onCreateOptionsMenu(), it retains an instance of the Menuyou populate and will not call onCreateOptionsMenu()again unless the menu is invalidated for some reason. However, you should use onCreateOptionsMenu()only to create the initial menu state and not to make changes during the activity lifecycle.

If you want to modify the options menu based on events that occur during the activity lifecycle, you can do so in the onPrepareOptionsMenu()method. This method passes you the Menuobject as it currently exists so you can modify it, such as add, remove, or disable items. (Fragments also provide an onPrepareOptionsMenu()callback.)

On Android 2.3.x and lower, the system calls onPrepareOptionsMenu()each time the user opens the options menu (presses the Menu button).

On Android 3.0 and higher, the options menu is considered to always be open when menu items are presented in the action bar. When an event occurs and you want to perform a menu update, you must call invalidateOptionsMenu()to request that the system call onPrepareOptionsMenu().

Note: You should never change items in the options menu based on the Viewcurrently in focus. When in touch mode (when the user is not using a trackball or d-pad), views cannot take focus, so you should never use focus as the basis for modifying items in the options menu. If you want to provide menu items that are context-sensitive to a View, use a Context Menu.

Creating Contextual Menus


Figure 3. Screenshots of a floating context menu (left) and the contextual action bar (right).

A contextual menu of