blob: cf3c7decbcfdce4653b8af415a37e67a463504df [file] [log] [blame]
page.title=Creating Menus
parent.title=User Interface
parent.link=index.html
@jd:body
<div id="qv-wrapper">
<div id="qv">
<h2>Key classes</h2>
<ol>
<li>{@link android.view.Menu}</li>
<li>{@link android.view.ContextMenu}</li>
<li>{@link android.view.SubMenu}</li>
</ol>
<h2>In this document</h2>
<ol>
<li><a href="#options-menu">Options Menu</a></li>
<li><a href="#context-menu">Context Menu</a></li>
<li><a href="#submenu">Submenu</a></li>
<li><a href="#xml">Define Menus in XML</a></li>
<li><a href="#features">Menu Features</a>
<ol>
<li><a href="#groups">Menu groups</a></li>
<li><a href="#checkable">Checkable menu items</a></li>
<li><a href="#shortcuts">Shortcut keys</a></li>
<li><a href="#intents">Menu item intents</a></li>
</ol>
</li>
</ol>
</div>
</div>
<p>Menus are an important part of any application. They provide familiar interfaces
that reveal application functions and settings. Android offers an easy programming interface
for developers to provide standardized application menus for various situations.</p>
<p>Android offers three fundamental types of application menus:</p>
<dl>
<dt><strong>Options Menu</strong></dt>
<dd>This is the primary set of menu items for an Activity. It is revealed by pressing
the device MENU key. Within the Options Menu are two groups of menu items:
<dl style="margin-top:1em">
<dt><em>Icon Menu</em></dt>
<dd>This is the collection of items initially visible 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 menu items that <em>do not</em> support
checkboxes or radio buttons.</dd>
<dt><em>Expanded Menu</em></dt>
<dd>This is a vertical list of items exposed by the "More" menu item from the Icon Menu.
It exists only when the Icon Menu becomes over-loaded and is comprised of the sixth
Option Menu item and the rest.</dd>
</dl>
</dd>
<dt><strong>Context Menu</strong></dt>
<dd>This is a floating list of menu items that may appear when you perform a long-press on a View
(such as a list item). </dd>
<dt><strong>Submenu</strong></dt>
<dd>This is a floating list of menu items that is revealed by an item in the Options Menu
or a Context Menu. A Submenu item cannot support nested Submenus. </dd>
</dl>
<h2 id="options-menu">Options Menu</h2>
<img align="right" src="{@docRoot}images/options_menu.png" />
<p>The Options Menu is opened by pressing the device MENU key.
When opened, the Icon Menu is displayed, which holds the first six menu items.
If more than six items are added to the Options Menu, then those that can't fit
in the Icon Menu are revealed in the Expanded Menu, via the "More" menu item. The Expanded Menu
is automatically added when there are more than six items.</p>
<p>The Options Menu is where you should include basic application functions
and any necessary navigation items (e.g., to a home screen or application settings).
You can also add <a href="#submenu">Submenus</a> for organizing topics
and including extra menu functionality.</p>
<p>When this menu is opened for the first time,
the Android system will call the Activity <code>{@link android.app.Activity#onCreateOptionsMenu(Menu)
onCreateOptionsMenu()}</code> callback method. Override this method in your Activity
and populate the {@link android.view.Menu} object given to you. You can populate the menu by
inflating a menu resource that was <a href="#xml">defined in XML</a>, or by calling
<code>{@link android.view.Menu#add(CharSequence) add()}</code>
for each item you'd like in the menu. This method adds a {@link android.view.MenuItem}, and returns the
newly created object to you. You can use the returned MenuItem to set additional properties like
an icon, a keyboard shortcut, an intent, and other settings for the item.</p>
<p>There are multiple <code>{@link android.view.Menu#add(CharSequence) add()}</code> methods.
Usually, you'll want to use one that accepts an <var>itemId</var> argument.
This is a unique integer that allows you to identify the item during a callback.</p>
<p>When a menu item is selected from the Options Menu, you will receive a callback to the
<code>{@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}</code>
method of your Activity. This callback passes you the
<code>MenuItem</code> that has been selected. You can identify the item by requesting the
<var>itemId</var>, with <code>{@link android.view.MenuItem#getItemId() getItemId()}</code>,
which returns the integer that was assigned with the <code>add()</code> method. Once you identify
the menu item, you can take the appropriate action.</p>
<p>Here's an example of this procedure, inside an Activity, wherein we create an
Options Menu and handle item selections:</p>
<pre>
/* Creates the menu items */
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_NEW_GAME, 0, "New Game");
menu.add(0, MENU_QUIT, 0, "Quit");
return true;
}
/* Handles item selections */
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_NEW_GAME:
newGame();
return true;
case MENU_QUIT:
quit();
return true;
}
return false;
}
</pre>
<p>The <code>add()</code> method used in this sample takes four arguments:
<var>groupId</var>, <var>itemId</var>, <var>order</var>, and <var>title</var>.
The <var>groupId</var> allows you to associate this menu item with a group of other items
(more about <a href="#groups">Menu groups</a>, below) &mdash; in
this example, we ignore it. <var>itemId</var> is a unique integer that we give the
MenuItem so that can identify it in the next callback. <var>order</var> allows us to
define the display order of the item &mdash; by default, they are displayed by the
order in which we add them. <var>title</var> is, of course, the name that goes on the
menu item (this can also be a
<a href="{@docRoot}guide/topics/resources/available-resources.html#stringresources">string resource</a>,
and we recommend you do it that way for easier localization).</p>
<p class="note"><strong>Tip:</strong>
If you have several menu items that can be grouped together with a title,
consider organizing them into a <a href="#submenu">Submenu</a>.</p>
<h3>Adding icons</h3>
<p>Icons can also be added to items that appears in the Icon Menu with
<code>{@link android.view.MenuItem#setIcon(Drawable) setIcon()}</code>. For example:</p>
<pre>
menu.add(0, MENU_QUIT, 0, "Quit")
.setIcon(R.drawable.menu_quit_icon);</pre>
<h3>Modifying the menu</h3>
<p>If you want to sometimes re-write the Options Menu as it is opened, override the
<code>{@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()}</code> method, which is
called each time the menu is opened. This will pass you the Menu object, just like the
<code>onCreateOptionsMenu()</code> callback. This is useful if you'd like to add or remove
menu options depending on the current state of an application or game.</p>
<p class="note"><strong>Note:</strong>
When changing items in the menu, it's bad practice to do so based on the currently selected item.
Keep in mind that, when in touch mode, there will not be a selected (or focused) item. Instead, you
should use a <a href="#context-menu">Context Menu</a> for such behaviors, when you want to provide
functionality based on a particular item in the UI.</p>
<h2 id="context-menu">Context Menu</h2>
<p>The Android context menu is similar, in concept, to the menu revealed with a "right-click" on a PC.
When a view is registered to a context menu,
performing a "long-press" (press and hold for about two seconds) on the object
will reveal a floating menu that provides functions relating to that item.
Context menus can be registered to any View object,
however, they are most often used for items in a
{@link android.widget.ListView}, which helpfully indicates the presence of the context menu
by transforming the background color of the ListView item when pressed.
(The items in the phone's contact list offer an example of this feature.)
</p>
<p class="note"><strong>Note:</strong> Context menu items do not support icons or shortcut keys.</p>
<p>To create a context menu, you must override the Activity's context menu callback methods:
<code>{@link android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenuInfo) onCreateContextMenu()}</code> and
<code>{@link android.app.Activity#onContextItemSelected(MenuItem) onContextItemSelected()}</code>.
Inside the <code>onCreateContextMenu()</code> callback method, you can add menu items using one of the
<code>{@link android.view.Menu#add(CharSequence) add()}</code> methods, or by
inflating a menu resource that was <a href="#xml">defined in XML</a>.
Then, register a {@link android.view.ContextMenu} for the View, with
<code>{@link android.app.Activity#registerForContextMenu(View) registerForContextMenu()}</code>.</p>
<p>For example, here is some code that can be used with the
<a href="{@docRoot}resources/tutorials/notepad/index.html">Notepad application</a>
to add a context menu for each note in the list:</p>
<pre>
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, EDIT_ID, 0, "Edit");
menu.add(0, DELETE_ID, 0, "Delete");
}
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()) {
case EDIT_ID:
editNote(info.id);
return true;
case DELETE_ID:
deleteNote(info.id);
return true;
default:
return super.onContextItemSelected(item);
}
}
</pre>
<p>In <code>onCreateContextMenu()</code>, we are given not only the ContextMenu to
which we will add {@link android.view.MenuItem}s, but also the {@link android.view.View}
that was selected and a {@link android.view.ContextMenu.ContextMenuInfo ContextMenuInfo} object,
which provides additional information about the object that was selected.
In this example, nothing special is done in <code>onCreateContextMenu()</code> &mdash; just
a couple items are added as usual. In the <code>onContextItemSelected()</code>
callback, we request the {@link android.widget.AdapterView.AdapterContextMenuInfo AdapterContextMenuInfo}
from the {@code MenuItem}, which provides information about the currently selected item.
All we need from
this is the list ID for the selected item, so whether editing a note or deleting it,
we find the ID with the {@code AdapterContextMenuInfo.info} field of the object. This ID
is passed to the <code>editNote()</code> and <code>deleteNote()</code> methods to perform
the respective action.</p>
<p>Now, to register this context menu for all the items in a {@link android.widget.ListView},
we pass the entire {@code ListView} to the
<code>{@link android.app.Activity#registerForContextMenu(View)}</code> method:</p>
<pre>registerForContextMenu(getListView());</pre>
<p>Remember, you can pass any View object to register a context menu. Here,
<code>{@link android.app.ListActivity#getListView()}</code> returns the ListView
object used in the Notepad application's {@link android.app.ListActivity}. As such, each item
in the list is registered to this context menu.</p>
<h2 id="submenu">Submenus</h2>
<p>A sub menu can be added within any menu, except another sub menu.
These are very useful when your application has a lot of functions that may be
organized in topics, like the items in a PC application's menu bar (File, Edit, View, etc.).</p>
<p>A sub menu is created by adding it to an existing {@link android.view.Menu}
with <code>{@link android.view.Menu#addSubMenu(CharSequence) addSubMenu()}</code>.
This returns a {@link android.view.SubMenu} object (an extension of {@link android.view.Menu}).
You can then add additional items to this menu, with the normal routine, using
the <code>{@link android.view.Menu#add(CharSequence) add()}</code> methods. For example:</p>
<pre>
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
SubMenu fileMenu = menu.addSubMenu("File");
SubMenu editMenu = menu.addSubMenu("Edit");
fileMenu.add("new");
fileMenu.add("open");
fileMenu.add("save");
editMenu.add("undo");
editMenu.add("redo");
return result;
}
</pre>
<p>Callbacks for items selected in a sub menu are made to the parent menu's callback method.
For the example above, selections in the sub menu will be handled by the
<code>onOptionsItemSelected()</code> callback.</p>
<p>You can also add Submenus when you <a href="#xml">define the parent menu in XML</a>.</p>
<h2 id="xml">Define Menus in XML</h2>
<p>Just like Android UI layouts, you can define application menus in XML, then inflate them
in your menu's <code>onCreate...()</code> callback method. This makes your application code cleaner and
separates more interface design into XML, which is easier to visualize.</p>
<p>To start, create a new folder in your project <code>res/</code> directory called <code>menu</code>.
This is where you should keep all XML files that define your application menus.</p>
<p>In a menu XML layout, there are
three valid elements: <code>&lt;menu></code>, <code>&lt;group></code> and <code>&lt;item></code>. The
<code>item</code> and <code>group</code> elements must be children of a <code>menu</code>, but <code>item</code>
elements may also be the children of a <code>group</code>, and another <code>menu</code> element may be the child
of an <code>item</code> (to create a Submenu). Of course, the root node of any file
must be a <code>menu</code> element.</p>
<p>As an example, we'll define the same menu created in the <a href="#options-menu">Options Menu</a> section,
above. We start with an XML file named <code>options_menu.xml</code> inside the <code>res/menu/</code> folder:</p>
<pre>
&lt;menu xmlns:android="http://schemas.android.com/apk/res/android">
&lt;item android:id="@+id/new_game"
android:title="New Game" />
&lt;item android:id="@+id/quit"
android:title="Quit" />
&lt;/menu>
</pre>
<p>Then, in the <code>onCreateOptionsMenu()</code> method, we inflate this resource using
<code>{@link android.view.MenuInflater#inflate(int,Menu) MenuInflater.inflate()}</code>:</p>
<pre>
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
</pre>
<p>The <code>{@link android.app.Activity#getMenuInflater()}</code> method returns the {@link android.view.MenuInflater}
for our activity's context. We then call <code>{@link android.view.MenuInflater#inflate(int,Menu) inflate()}</code>,
passing it a pointer to our menu resource and the Menu object given by the callback.</code></p>
<p>While this small sample may seem like more effort, compared to creating the menu items in the
<code>onCreateOptionsMenu()</code> method, this will save a lot of trouble when dealing with more items
and it keeps your application code clean.</p>
<p>You can define <a href="#groups">menu groups</a> by wrapping <code>item</code> elements in a <code>group</code>
element, and create Submenus by nesting another <code>menu</code> inside an <code>item</code>.
Each element also supports all the necessary attributes to control features like shortcut keys,
checkboxes, icons, and more. To learn about these attributes and more about the XML syntax, see the Menus
topic in the <a href="{@docRoot}guide/topics/resources/available-resources.html#menus">Available
Resource Types</a> document.</p>
<h2 id="features">Menu Features</h2>
<p>Here are some other features that can be applied to most menu items.</p>
<h3 id="groups">Menu groups</h3>
<p>When adding new items to a menu, you can optionally include each item in a group.
A menu group is a collection of menu items that can share certain traits, like
whether they are visible, enabled, or checkable.</p>
<p>A group is defined by an integer (or a resource id, in XML). A menu item is added to the group when it is
added to the menu, using one of the <code>add()</code> methods that accepts a <var>groupId</var>
as an argument, such as <code>{@link android.view.Menu#add(int,int,int,int)}</code>.</p>
<p>You can show or hide the entire group with
<code>{@link android.view.Menu#setGroupVisible(int,boolean) setGroupVisible()}</code>;
enable or disable the group with
<code>{@link android.view.Menu#setGroupEnabled(int,boolean) setGroupEnabled()}</code>;
and set whether the items can be checkable with
<code>{@link android.view.Menu#setGroupCheckable(int,boolean,boolean) setGroupCheckable()}</code>.
</p>
<h3 id="checkable">Checkable menu items</h3>
<img align="right" src="{@docRoot}images/radio_buttons.png" alt="" />
<p>Any menu item can be used as an interface for turning options on and off. This can
be indicated with a checkbox for stand-alone options, or radio buttons for groups of
mutually exclusive options (see the screenshot, to the right).</p>
<p class="note"><strong>Note:</strong> Menu items in the Icon Menu cannot
display a checkbox or radio button. If you choose to make items in the Icon Menu checkable,
then you must personally indicate the state by swapping the icon and/or text
each time the state changes between on and off.</p>
<p>To make a single item checkable, use the <code>{@link android.view.MenuItem#setCheckable(boolean)
setCheckable()}</code> method, like so:</p>
<pre>
menu.add(0, VIBRATE_SETTING_ID, 0, "Vibrate")
.setCheckable(true);
</pre>
<p>This will display a checkbox with the menu item (unless it's in the Icon Menu). When the item
is selected, the <code>onOptionsItemSelected()</code> callback is called as usual. It is here that
you must set the state of the checkbox. You can query the current state of the item with
<code>{@link android.view.MenuItem#isChecked()}</code> and set the checked state with
<code>{@link android.view.MenuItem#setChecked(boolean) setChecked()}</code>.
Here's what this looks like inside the
<code>onOptionsItemSelected()</code> callback:</p>
<pre>
switch (item.getItemId()) {
case VIBRATE_SETTING_ID:
if (item.isChecked()) item.setChecked(false);
else item.setChecked(true);
return true;
...
}
</pre>
<p>To make a group of mutually exclusive radio button items, simply
assign the same group ID to each menu item
and call <code>{@link android.view.Menu#setGroupCheckable(int,boolean,boolean)
setGroupCheckable()}</code>. In this case, you don't need to call <code>setCheckable()</code>
on each menu items, because the group as a whole is set checkable. Here's an example of
two mutually exclusive options in a Submenu:</p>
<pre>
SubMenu subMenu = menu.addSubMenu("Color");
subMenu.add(COLOR_MENU_GROUP, COLOR_RED_ID, 0, "Red");
subMenu.add(COLOR_MENU_GROUP, COLOR_BLUE_ID, 0, "Blue");
subMenu.setGroupCheckable(COLOR_MENU_GROUP, true, true);
</pre>
<p>In the <code>setGroupCheckable()</code> method, the first argument is the group ID
that we want to set checkable. The second argument is whether we want the group items
to be checkable. The last one is whether we want each item to be exclusively checkable
(if we set this <em>false</em>, then all the items will be checkboxes instead of radio buttons).
When the group is set to be exclusive (radio buttons), each time a new item is selected,
all other are automatically de-selected.</p>
<p>
<p class="note"><strong>Note:</strong>
Checkable menu items are intended to be used only on a per-session basis and not saved to the device
(e.g., the <em>Map mode</em> setting in the Maps application is not saved &mdash; screenshot above).
If there are application settings that you would like to save for the user,
then you should store the data using <a href="#{@docRoot}guide/topics/data/data-storage.html#pref">Preferences</a>,
and manage them with a {@link android.preference.PreferenceActivity}.</p>
<h3 id="shortcuts">Shortcut keys</h3>
<p>Quick access shortcut keys using letters and/or numbers can be added to menu items with
<code>setAlphabeticShortcut(char)</code> (to set char shortcut), <code>setNumericShortcut(int)</code>
(to set numeric shortcut),
or <code>setShortcut(char,int)</code> (to set both)</code>. Case is <em>not</em> sensitive.
For example:</p>
<pre>
menu.add(0, MENU_QUIT, 0, "Quit")
.setAlphabeticShortcut('q');
</pre>
<p>Now, when the menu is open (or while holding the MENU key), pressing the "q" key will
select this item.</p>
<p>This shortcut key will be displayed as a tip in the menu item, below the menu item name
(except for items in the Icon Menu).</p>
<p class="note"><strong>Note:</strong> Shortcuts cannot be added to items in a Context Menu.</p>
<h3 id="intents">Menu item intents</h3>
<p>If you've read the <a href="{@docRoot}guide/topics/fundamentals.html">Application
Fundamentals</a>, then you're at least a little familiar
with Android Intents. These allow applications to bind with each other, share information,
and perform user tasks cooperatively. Just like your application might fire an Intent to launch a web browser,
an email client, or another Activity in your application,
you can perform such actions from within a menu.
There are two ways to do this: define an Intent and assign it to a single menu item, or
define an Intent and allow Android to search the device for activities and dynamically add a
menu item for each one that meets the Intent criteria.</p>
<p>For more information on creating Intents and providing your application's services to other applications,
read the <a href="/guide/topics/intents/intents-filters.html">Intents
and Intent Filters</a> document.</p>
<h4>Set an intent for a single menu item</h4>
<p>If you want to offer a specific menu item that launches a new Activity, then you
can specifically define an Intent for the menu item with the
<code>{@link android.view.MenuItem#setIntent(Intent)
setIntent()}</code> method.</p>
<p>For example, inside the <code>{@link android.app.Activity#onCreateOptionsMenu(Menu)
onCreateOptionsMenu()}</code> method, you can define a new menu item with an Intent like this:</p>
<pre>
MenuItem menuItem = menu.add(0, PHOTO_PICKER_ID, 0, "Select Photo");
menuItem.setIntent(new Intent(this, PhotoPicker.class));
</pre>
<p>Android will automatically launch the Activity when the item is selected.</p>
<p class="note"><strong>Note:</strong> This will not return a result to your Activity.
If you wish to be returned a result, then do not use <code>setIntent()</code>.
Instead, handle the selection as usual in the <code>onOptionsMenuItemSelected()</code>
or <code>onContextMenuItemSelected()</code> callback and call
<code>{@link android.app.Activity#startActivityForResult(Intent,int) startActivityForResult()}</code>.
</p>
<h4>Dynamically add intents</h4>
<p>If there are potentially multiple activities that are relevant to your current
Activity or selected item, then the application can dynamically add menu items that execute other
services.</p>
<p>During menu creation, define an Intent with the category <var>Intent.ALTERNATIVE_CATEGORY</var> and/or
<var>Intent.SELECTED_ALTERNATIVE</var>, the MIME type currently selected (if any), and any other
requirements, the same way as you would satisfy an intent filter to open a new
Activity. Then call
<code>{@link android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[])
addIntentOptions()}</code> to have Android search for any services meeting those requirements
and add them to the menu for you. If there are no applications installed
that satisfy the Intent, then no additional menu items are added.</p>
<p class="note"><strong>Note:</strong>
<var>SELECTED_ALTERNATIVE</var> is used to handle the currently selected element on the
screen. So, it should only be used when creating a Menu in <code>onCreateContextMenu()</code> or
<code>onPrepareOptionsMenu()</code>, which is called every time the Options Menu is opened.</p>
<p>Here's an example demonstrating how an application would search for
additional services to display on its menu.</p>
<pre>
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, getIntent().getData());
intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
// Search for, and populate the menu with, acceptable offering applications.
menu.addIntentOptions(
thisClass.INTENT_OPTIONS, // Menu group
0, // Unique item ID (none)
0, // 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
0, // Additional flags to control items (none)
null); // Array of MenuItems that correlate to specific items (none)
return true;
}</pre>
<p>For each Activity found that provides an Intent Filter matching the Intent defined, a menu
item will be added, using the <var>android:label</var> value of the intent filter as the text
for the menu item.
The <code>{@link android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[]) addIntentOptions()}</code> method will also return the number of menu items added.</p>
<p>Also be aware that, when <code>addIntentOptions()</code> is called, it will override any and all
menu items in the menu group specified in the first argument.</p>
<p>If you wish to offer the services of your Activity to other application menus, then you
only need to define an intent filter as usual. Just be sure to include the <var>ALTERNATIVE</var> and/or
<var>SELECTED_ALTERNATIVE</var> values in the <var>name</var> attribute of
a <code>&lt;category></code> element in the intent filter. For example:</p>
<pre>
&lt;intent-filter label="Resize Image">
...
&lt;category android:name="android.intent.category.ALTERNATIVE" />
&lt;category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
...
&lt;/intent-filter>
</pre>
<p>read more about writing intent filters in the
<a href="/guide/topics/intents/intents-filters.html">Intents and Intent Filters</a> document.</p>
<p>For a sample application using this technique, see the
<a href="{@docRoot}resources/samples/NotePad/index.html">Note Pad</a>
sample code.</p>