`On I30(5
`
`developers
`
`
`
`User Interface >
`
`Creating Menus
`
`Menusare an important part of an application that provide a familiar
`interface for the user to access application functions and settings.
`Android offers an easy programming interface for you to provide
`application menusin your application.
`
`Android provides three types of application menus:
`
`Options Menu
`The primary menu for an Activity, which appears when the user
`presses the device MENU key. Within the Options Menu are two
`groups:
`
`Icon Menu
`The menuitemsvisible at the bottom of the screen at the
`press of the MENU key.It supports a maximum of six menu
`items. These are the only menu items that support icons
`and the only menuitems that do not support checkboxes or
`radio buttons.
`Expanded Menu
`The vertical list of menu items exposed by the "More" menu
`item in the Icon Menu. When the Icon Menu isfull, the
`expanded menu is comprised of the sixth menu item and
`the rest.
`
`In this document
`
`Defining Menus
`Inflating a Menu Resource
`
`Creating_an Options Menu
`Changing the menu whenit opens
`Creating a Context Menu
`Creating a Submenu
`Other Menu Features
`Menugroups
`Checkable menu items
`
`Shortcut keys
`Intents for menu items
`
`Key classes
`Menu
`Menultem
`ContextMenu
`SubMenu
`See also
`Menu Resource
`
`Context Menu
`
`A floating list of menu items that appears whenthe user performs a long-press on a View.
`
`Submenu
`A floating list of menu items that the user opens by pressing a menu item in the Options Menu or a context menu. A
`submenuitem cannot support a nested submenu.
`
`Defining Menus
`
`
`Instead of instantiating Menu objects in your application code, you should define a menu andall its items in an XML menu
`resource, then inflate the menu resource (load it as a programmable object) in your application code. Defining your menusin
`XML is a good practice because it separates your interface design from your application code (the same as when you define
`your Activitylayout).
`
`To define a menu, create an XML file inside your project's res/menu/ directory and build the menu with the following elements:
`
`<menu>
`
`Creates a Menu, whichis a container for menu items. It must be the root node and holds one or moreofthe following
`elements. You can also nest this element in an <item> to create a submenu.
`
`<item>
`
`Creates a MenuItem, which represents a single item in a menu.
`
`APPLE-1037
`
`1
`
`APPLE-1037
`
`
`
`<group>
`An optional, invisible container for <item> elements. It allows you to categorize menuitems so they share properties such
`
`as active state andvisibility. See Menu groups.
`
`For example,hereis a file in res/menu/ named game_menu. xml:
`
`<?xml version="1.0" encoding="utf-8" ?>
`<menu xmlns:android="http://schemas.android.com/apk/res/android">
`<item android: id="@+id/new_game”
`android: icon="@drawable/ic_new_game”
`android: title="@string/new_game" />
`<item android: id="@+id/quit"
`android: icon="@drawable/ic_quit”
`android: title="@string/quit" />
`
`</menu>
`
`This example defines a menu with two menu items. Each item includestheattributes:
`
`android:id
`
`A resourceID that's unique to the item so that the application can recognize the item whenthe userselectsit.
`
`android:icon
`A drawable resource thatis the icon visible to the user.
`
`android:title
`
`A string resourcethatis thetitle visible to the user.
`
`For more about the XML syntax and attributes for a menu resource, see the Menu Resourcereference.
`
`Inflating a Menu Resource
`
`You can inflate your menu resource (convert the XML resource into a programmable object) using MenuInflater.inflate().
`For example,the following codeinflates the game_menu. xml file defined above during the onCreateOptionsMenu() callback
`method, to be used for the Options Menu:
`
`@Override
`public boolean onCreateOptionsMenu(Menu menu) {
`MenuInflater inflater = getMenuInflater();
`inflater.inflate(R.menu.game_menu, menu) ;
`return true;
`
`The getMenuInflater() method returns a MenuInflater for the Activity. With this object, you can call inflate(.), which
`inflates a menu resourceinto a Menu object. In this example, the menu resource defined by game_menu.xm1 is inflated into the
`Menu that was passed into onCreateOptionsMenu(). (This callback method for creating an option menu is discussed morein
`the next section.)
`
`Creating an Options Menu
`
`The Options Menuis where you should include basic application functions and necessary navigation items (for example, a
`button to open application settings). The user can open the Options Menu with the device MENU key. Figure 1 shows a
`screenshotof an Options Menu.
`
`2
`
`
`
`Whenopened, thefirst visible portion of the Options Menu is called the Icon Menu. It
`holds thefirst six menu items. If you add morethansix items to the Options Menu,
`Android places the sixth item and thoseafterit into the Expanded Menu, which the
`user can open with the "More" menuitem.
`
`Whenthe user opens the Options Menuforthefirst time, Android calls your Activity's
`onCreateOptionsMenu() method. Override this method in your Activity and populate
`the Menu that is passed into the method. Populate the Menu byinflating a menu
`
`resource as describedin Inflating a Menu Resource. (You can also populate the menu
`in code, using add(.) to add menu items.)
`
`Whentheuser selects a menu item from the Options Menu, the system calls your
`Activity's onOptionsItemSelected(.) method. This method passes the MenuItemthat
`the user selected. You can identify the menu item by calling getItemId(.), which
`returns the unique ID for the menu item (defined by the android: id attribute in the
`menu resourceor with an integer passed to the add(_) method). You can matchthis ID
`against known menu items and 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.quit:
`quit();
`return true;
`default:
`return super.onOptionsItemSelected(item) ;
`
`}
`
`Li
`
`44
`
`EG http://www.google.com/...
`
`Fy
`
`Web Images Places News more+ @
`
`
`Instant (beta) is off: Turn on
`
`P See places near: Seattle, WA - update
`
`
`
`Figure 1. Screenshot of an
`Options Menu.
`
`In this example, getItemId() queries the ID for the selected menu item and the switch statement compares the ID against the
`resource IDs that were assigned to menu items in the XML resource. When a switch case successfully handles theitem,it
`returns "true" to indicate that the item selection was handled. Otherwise, the default statement passes the menuitem to the
`superclass in case it can handle the item selected. (If you've directly extended the Activity class, then the superclass returns
`"false", but it's a good practice to pass unhandled menu items to the superclass instead of directly returning "false".)
`
`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 have to manageonly one set
`of code for handling menu actions and each decendentclassinherits the menu behaviors.
`
`If you want to add menuitemsto one of your decendentactivities, 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 superclass's behaviorfor individual menu items.
`
`Changing the menu whenit opens
`
`The onCreateOptionsMenu(_)method is called only thefirst time the Options Menu is opened. The system keeps and re-uses
`the Menu youdefine in this method until your Activity is destroyed. If you want to change the Options Menu eachtimeit opens,
`you mustoverride the onPrepareOptionsMenu(.) method. This passes you the Menu object asit currently exists. This is usefulif
`you'd like to remove, add, disable, or enable menu items depending on the current state of your application.
`
`Note: You should never changeitemsin the Options Menu based on the View currently in focus. When in touch mode
`(whenthe useris not using a trackball or d-pad), Views cannot take focus, so you should never use focus asthe basis for
`
`3
`
`3
`
`
`
`| modifying items in the Options Menu. If you want to provide menuitems that are context-sensitive to a View, use a
`Context Menu.
`
`Creating a Context Menu
`
`A context menuis conceptually similar to the menu displayed whenthe userperformsa "right-click" on a PC. You should use a
`context menu to provide the user accessto actions that pertain to a specific item in the user interface. On Android, a context
`menu is displayed when the userperforms a "long press" (press and hold) on an item.
`
`You can create a context menu for any View, though context menus are most often used for items in a ListView. When the user
`performs a long-press onanitem in a ListView andthelist is registered to provide a context menu, thelist item signals to the
`user that a context menuis available by animating its background color—it transitions from orange to white before opening the
`context menu. (The Contacts application demonstrates this feature.)
`
`In order for a View to provide a context menu, you must"register"
`the view for a context menu. Call registerForContextMenu(,) and
`passit the View you want to give a context menu. Whenthis View
`then receives a long-press,it displays a context menu.
`
`To define the context menu's appearance and behavior, override
`yourActivity's context menu callback methods,
`onCreateContextMenu() and onContextItemSelected().
`
`For example, here's an onCreateContextMenu(.) that uses the
`context_menu.xml1 menu resource:
`
`Register a ListView
`
`If your Activity uses a ListView and you wantall list
`items to provide a context menu, register all items for a
`context menu by passing the ListView to
`registerForContextMenu(). For example, if you're
`:
`-
`—
`:
`“e
`.
`.
`using a ListActivity,register all list itemslike this:
`
`registerForContextMenu(getListView());
`
`@Override
`public void onCreateContextMenu(ContextMenu menu, View v,
`ContextMenuInfo menuInfo)
`super.onCreateContextMenu(menu, v, menuInfo) ;
`MenuInflater inflater = getMenuInflater();
`inflater.inflate(R.menu.context_menu, menu);
`
`{
`
`}
`
`MenuInflater is usedto inflate the context menu from a menu resource. (You can also use add(.) to add menu items.) The
`callback method parameters include the View that the user selected and a ContextMenu.ContextMenuInfo object that provides
`additional information about the item selected. You might use these parameters to determine which context menu should be
`created, but in this example, all context menusfor the Activity are the same.
`
`Then whenthe user selects an item from the context menu, the system calls onContextItemSelected(.). Here is an example of
`how you can handle selected items:
`
`@Override
`public boolean onContextItemSelected(MenuItem item) {
`AdapterContextMenuInfo info = (AdapterContextMenuInfo) item. getMenuInfo();
`switch (item.getItemId()) {
`case R.id.edit:
`editNote(info.id) ;
`return true;
`case R.id.delete:
`deleteNote(info.id) ;
`return true;
`default:
`return super.onContextItemSelected(item) ;
`
`}
`
`}
`
`4
`
`
`
`
`The structure of this code is similar to the example for Creating an Options Menu, in which getItemId() queries the ID for the
`selected menu item and a switch statement matches the item to the IDs that are defined in the menu resource. And like the
`
`options menu example, the default statement calls the super class in case it can handle menu items not handled here, if
`necessary.
`
`In this example, the selected item is an item from a ListView. To perform an action on the selected item, the application needs
`to knowthelist ID for the selected item (it's position in the ListView). To get the ID, the application calls getMenuInfo(), which
`returns a AdapterView.AdapterContextMenuInfo object that includes thelist ID for the selected item in the id field. The local
`methods editNote() and deleteNote() methods acceptthis list ID to perform an action on the data specified bythelist ID.
`
`Note: Items in a context menu do not support icons or shortcut keys.
`
`Creating Submenus
`
`A submenuis a menu that the user can openbyselecting an item in another menu. You can add a submenu to any menu
`(except a submenu). Submenusare useful whenyour application has a lot of functions that can be organizedinto topics, like
`items in a PC application's menubar(File, Edit, View, etc.).
`
`Whencreating your menu resource, you can create a submenu by adding a <menu> elementas the child of an <item>. For
`example:
`
`<?xml version="1.0" encoding="utf-8" ?>
`<menu xmlns:android="http://schemas.android.com/apk/res/android">
`<item android: id="@+id/file"
`android: icon="@drawable/file"
`android: title="@string/file" >
`<!-- "file" submenu -->
`<menu">
`
`<item android: id="@+id/new"
`android:title="@string/new" />
`<item android: id="@+id/open"
`android:title="@string/open" />
`
`</menu>
`</item>
`</menu>
`
`Whenthe userselects an item from a submenu, the parent menu's respective on-item-selected callback method receives the
`event. For instance,if the above menuis applied as an Options Menu, then the onOptionsItemSelected() methodis called
`when a submenu item is selected.
`
`You can also use addSubMenu()to dynamically add a SubMenu to an existing Menu. This returns the new SubMenu object, to
`which you can add submenu items, using add(.).
`
`Other Menu Features
`
`Here are someother features that you can apply to most menuitems.
`
`Menu groups
`
`A menu group is a collection of menu items that share certain traits. With a group, you can:
`
`e
`
`Showorhideall items with setGroupVisible()
`
`e Enable or disable all items with setGroupEnabled()
`
`e Specify whetherall items are checkable with setGroupCheckable()
`
`5
`
`5
`
`
`
`You can create a group by nesting <item> elements inside a <group> element in your menu resource or by specifying a group
`ID with the the add(.) method.
`
`Here's an example menu resourcethat includes a group:
`
`<?xml version="1.0" encoding="utf-8" ?>
`<menu xmlns:android="http://schemas.android.com/apk/res/android">
`<item android: id="@+id/item1"
`android: icon="@drawable/item1"
`android: title="@string/item1" />
`<!-- menu group -->
`<group android: id="@+id/group1">
`<item android: id="@+id/groupItem1"
`android: title="@string/groupItem1" />
`<item android: id="@+id/groupItem2"
`android: title="@string/groupItem2" />
`
`</group>
`</menu>
`
`The items that are in the group appear the sameasthefirst item that is not in a group—all three items in the menu aresiblings.
`However, you can modify thetraits of the two itemsin the group by referencing the group ID and using the methodslisted above.
`
`Checkable menu items
`
`A menu canbe useful as an interface for turning options on and off, using a checkbox
`for stand-alone options, or radio buttons for groups of mutually exclusive options.
`Figure 2 shows a submenu with items that are checkable with radio buttons.
`
`Note: Menu itemsin the Icon Menu (from the Options Menu) cannot display a
`checkboxor radio button. If you choose to makeitems in the Icon Menu checkable,
`you must manually indicate the checked state by swapping the icon and/ortext
`eachtime the state changes.
`
`You can define the checkable behaviorfor individual menu items using the
`android: checkableattribute in the <item> element, or for an entire group with the
`android: checkableBehavior attribute in the <group> element. For example, all
`items in this menu group are checkable with a radio button:
`
`<?xml version="1.0" encoding="utf-8" ?>
`<menu xmlns:android="http://schemas.android.com/apk/res/android">
`<group android: checkableBehavior="single">
`<item android: id="@t+id/red"
`android: title="@string/red" />
`<item android: id="@t+id/blue"
`android:title="@string/blue" />
`
`</group>
`</menu>
`
`Map Mode
`
`
`
`Figure 2. Screenshot of
`checkable menu items
`
`The android: checkableBehavior attribute accepts either:
`
`single
`Only oneitem from the group can be checked (radio buttons)
`
`all
`
`All items can be checked (checkboxes)
`
`none
`
`No items are checkable
`
`6
`
`
`
`You can apply a default checked state to an item using the android: checkedattribute in the <item> element and changeit in
`code with the setChecked(.) method.
`
`Whena checkable item is selected, the system calls your respective item-selected callback method (such as
`onOptionsItemSelected(.)). It is here that you must set the state of the checkbox, because a checkbox or radio button does
`not changeits state automatically. You can query the current state of the item (as it was before the user selectedit) with
`isChecked() and then set the checked state with setChecked(). For example:
`
`@Override
`public boolean onOptionsItemSelected(MenuItem item) {
`switch (item.getItemId()) {
`case R.id.vibrate:
`
`case R.id.dont_vibrate:
`if (item.isChecked()) item.setChecked(false) ;
`else item.setChecked(true) ;
`return true;
`default:
`return super.onOptionsItemSelected(item) ;
`
`}
`
`}
`
`If you don't set the checked state this way, then the visible state of the item (the checkbox or radio button) will not change when
`the user selects it. When you doset the state, the Activity preserves the checked state of the item so that when the user opens
`the menulater, the checked state that you setis visible.
`
`Note: Checkable menu items are intended to be used only on a per-session basis and not savedafter the application is
`
`destroyed. If you have application settings that you would like to save for the user, you should store the data using Shared
`Preferences.
`
`Shortcut keys
`
`You can add quick-access shortcut keys using letters and/or numbers to menu items with the android: alphabeticShortcut
`and android:numericShortcut attributes in the <item> element. You can also use the methods
`
`setAlphabeticShortcut(char) and setNumericShortcut(char). Shortcut keys are not case sensitive
`
`For example,if you apply the "s" character as an alphabetic shortcut to a "save" menu item, then when the menuis open (or
`while the user holds the MENU key) and the userpresses the "s" key, the "save" menuitem is selected.
`
`This shortcut key is displayed as a tip in the menu item, below the menu item name (exceptfor items in the Icon Menu, which are
`displayed only if the user holds the MENU key).
`
`Note: Shortcut keys for menu items only work on devices with a hardware keyboard. Shortcuts cannot be addedto items
`in a Context Menu.
`
`Intents for menu items
`
`Sometimes you'll want a menu item to launch an Activity using an Intent (whetherit's an Actvitity in your application or another
`application). When you knowtheIntent you want to use and have a specific menu item that should initiate the Intent, you can
`execute the Intent with startActivity() during the appropriate on-item-selected callback method (such as the
`onOptionsItemSelected(.) callback).
`
`However,if you are not certain that the user's device contains an application that handles the Intent, then adding a menuitem
`that executes the Intent can result in a non-functioning menu item, because the Intent might not resolve to an Activity that
`acceptsit. To solve this, Android lets you dynamically add menu items to your menu when Android finds activities on the device
`that handle yourIntent.
`
`If you're not familiar with creating Intents, read the Intents and Intent Filters.
`
`7
`
`
`
`Dynamically adding Intents
`
`Whenyou don't knowif the user's device has an application that handles a specific Intent, you can define the Intent and let
`Android search the devicefor activities that accept the Intent. Whenit finds activies that handle the Intent, it adds a menu item
`for each one to your menu and attaches the appropriate Intent to open the Activity when the userselectsit.
`
`To add menu items based onavailable activities that accept an Intent:
`
`1. Define an Intent with the category CATEGORY_ALTERNATIVE and/or CATEGORY_SELECTED ALTERNATIVE, plus any other
`requirements.
`
`
`2. Call Menu.addIntentOptions(.). Android then searchesfor any applications that can perform the Intent and adds them to
`your menu.
`
`If there are no applicationsinstalled that satisfy the Intent, then no menu items are added.
`
`Note: CATEGORY_SELECTED ALTERNATIVEis used to handle the currently selected element on the screen. So,it should
`only be used whencreating a Menu in onCreateContextMenu().
`
`For example:
`
`@Override
`public boolean onCreateOptionsMenu(Menu menu) {
`super .onCreateOptionsMenu (menu) ;
`
`// Create an Intent that describes the requirements to fulfill, to be included
`// in our menu. The offering app must include a category value of Intent.CATEGORY_ALTERNATIVE.
`Intent intent = new Intent(null, dataUri);
`intent.addCategory(Intent .CATEGORY_ALTERNATIVE) ;
`
`// Search and populate the menu with acceptable offering applications.
`menu. addIntentOptions(
`// Menu group to which new items will be added
`R.id.intent_group,
`Q,
`// Unique item ID (none)
`Q,
`// Order for the items (none)
`this.getComponentName(),
`// The current Activity name
`null,
`// Specific items to place first (none)
`intent, // Intent created above that describes our requirements
`Q,
`// Additional flags to control
`items (none)
`null);
`// Array of MenuItems that correlate to specific items (none)
`
`return true;
`
`For eachActivity found that provides an Intentfilter matching the Intent defined, a menu item is added, using the valuein the
`
`Intentfilter's android: label as the menuitemtitle and the application icon as the menu item icon. The addIntentOptions()
`method returns the number of menu items added.
`
`
`Note: Whenyoucall addIntentOptions(.), it overrides any and all menu items by the menu groupspecified in thefirst
`argument.
`
`Allowing your Activity to be added to menus
`
`You can also offer the services of your Activity to other applications, so your application can be included in the menu of others
`(reverse the roles described above).
`
`To be included in other application menus, you need to define anIntentfilter as usual, but be sure to include the
`CATEGORY_ALTERNATIVE and/or CATEGORY_SELECTED ALTERNATIVEvaluesforthe Intentfilter category. For example:
`
`<intent-filter label="Resize Image">
`
`<category android:name="android.intent.category.ALTERNATIVE" />
`<category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
`8
`
`8
`
`
`
`</intent-filter>
`
`Read more aboutwriting Intentfilters in the Intents and Intent Filters document.
`
`For a sample application using this technique, see the Note Pad sample code.
`< Back to User Interface
`
`Except as noted, this contentis licensed under Apache 2.0. For details and restrictions, see the Content License.
`Android 2.3 r1 - 14 Feb 2011 9:37
`
`Site Terms of Service - Privacy Policy - Brand Guidelines
`
`{Go to top
`
`9
`
`



