• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Menus
2parent.title=User Interface
3parent.link=index.html
4@jd:body
5
6<div id="qv-wrapper">
7<div id="qv">
8  <h2>In this document</h2>
9  <ol>
10    <li><a href="#xml">Creating a Menu Resource</a></li>
11    <li><a href="#Inflating">Inflating a Menu Resource</a>
12    <li><a href="#options-menu">Creating an Options Menu</a>
13      <ol>
14        <li><a href="#ChangingTheMenu">Changing menu items at runtime</a></li>
15      </ol>
16    </li>
17    <li><a href="#context-menu">Creating a Context Menu</a></li>
18    <li><a href="#submenu">Creating a Submenu</a></li>
19    <li><a href="#features">Other Menu Features</a>
20      <ol>
21        <li><a href="#groups">Menu groups</a></li>
22        <li><a href="#checkable">Checkable menu items</a></li>
23        <li><a href="#shortcuts">Shortcut keys</a></li>
24        <li><a href="#intents">Dynamically adding menu intents</a></li>
25      </ol>
26    </li>
27  </ol>
28
29  <h2>Key classes</h2>
30  <ol>
31    <li>{@link android.view.Menu}</li>
32    <li>{@link android.view.MenuItem}</li>
33    <li>{@link android.view.ContextMenu}</li>
34    <li>{@link android.view.SubMenu}</li>
35  </ol>
36
37  <h2>See also</h2>
38  <ol>
39    <li><a href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a></li>
40    <li><a href="{@docRoot}guide/topics/resources/menu-resource.html">Menu Resource</a></li>
41  </ol>
42</div>
43</div>
44
45<p>Menus are an important part of an activity's user interface, which provide users a familiar
46way to perform actions. Android offers a simple framework for you to add standard
47menus to your application.</p>
48
49<p>There are three types of application menus:</p>
50<dl>
51  <dt><strong>Options Menu</strong></dt>
52    <dd>The primary collection of menu items for an activity, which appears when the user touches
53the MENU button. When your application is running on Android 3.0 or later, you can provide
54quick access to select menu items by placing them directly in the <a
55href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>, as "action items."</dd>
56  <dt><strong>Context Menu</strong></dt>
57    <dd>A floating list of menu items that appears when the user touches and holds a view
58that's registered to provide a context menu.
59</dd>
60  <dt><strong>Submenu</strong></dt>
61    <dd>A floating list of menu items that appears when the user touches a menu item that contains
62a nested menu.</dd>
63</dl>
64
65<p>This document shows you how to create each type of menu, using XML to define the content of
66the menu and callback methods in your activity to respond when the user selects an item.</p>
67
68
69
70<h2 id="xml">Creating a Menu Resource</h2>
71
72<p>Instead of instantiating a {@link android.view.Menu} in your application code, you should
73define a menu and all its items in an XML <a
74href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>, then inflate the menu
75resource (load it as a programmable object) in your application code. Using a menu resource to
76define your menu is a good practice because it separates the content for the menu from your
77application code. It's also easier to visualize the structure and content of a menu in XML.</p>
78
79<p>To create a menu resource, create an XML file inside your project's <code>res/menu/</code>
80directory and build the menu with the following elements:</p>
81<dl>
82  <dt><code>&lt;menu></code></dt>
83    <dd>Defines a {@link android.view.Menu}, which is a container for menu items. A
84<code>&lt;menu></code> element must be the root node for the file and can hold one or more
85<code>&lt;item></code> and <code>&lt;group></code> elements.</dd>
86
87  <dt><code>&lt;item></code></dt>
88    <dd>Creates a {@link android.view.MenuItem}, which represents a single item in a menu. This
89element may contain a nested <code>&lt;menu></code> element in order to create a submenu.</dd>
90
91  <dt><code>&lt;group></code></dt>
92    <dd>An optional, invisible container for {@code &lt;item&gt;} elements. It allows you to
93categorize menu items so they share properties such as active state and visibility. See the
94section about <a href="#groups">Menu groups</a>.</dd>
95</dl>
96
97
98<p>Here's an example menu named <code>game_menu.xml</code>:</p>
99<pre>
100&lt;?xml version="1.0" encoding="utf-8"?&gt;
101&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"&gt;
102    &lt;item android:id="@+id/new_game"
103          android:icon="@drawable/ic_new_game"
104          android:title="@string/new_game" /&gt;
105    &lt;item android:id="@+id/help"
106          android:icon="@drawable/ic_help"
107          android:title="@string/help" /&gt;
108&lt;/menu&gt;
109</pre>
110
111<p>This example defines a menu with two items. Each item includes the attributes:</p>
112<dl>
113  <dt>{@code android:id}</dt>
114    <dd>A resource ID that's unique to the item, which allows the application can recognize the item
115when the user selects it.</dd>
116  <dt>{@code android:icon}</dt>
117    <dd>A reference to a drawable to use as the item's icon.</dd>
118  <dt>{@code android:title}</dt>
119    <dd>A reference to a string to use as the item's title.</dd>
120</dl>
121
122<p>There are many more attributes you can include in an {@code &lt;item&gt;}, including some that
123 specify how the item may appear in the <a
124href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>. For more information about the XML
125syntax and attributes for a menu resource, see the <a
126href="{@docRoot}guide/topics/resources/menu-resource.html">Menu Resource</a> reference.</p>
127
128
129
130<h2 id="Inflating">Inflating a Menu Resource</h2>
131
132<p>From your application code, you can inflate a menu resource (convert the XML resource into a
133programmable object) using
134{@link android.view.MenuInflater#inflate(int,Menu) MenuInflater.inflate()}. For
135example, the following code inflates the <code>game_menu.xml</code> file defined above, during the
136{@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} callback method, to
137use the menu as the activity's Options Menu:</p>
138
139<pre>
140&#64;Override
141public boolean onCreateOptionsMenu(Menu menu) {
142    MenuInflater inflater = getMenuInflater();
143    inflater.inflate(R.menu.game_menu, menu);
144    return true;
145}
146</pre>
147
148<p>The {@link android.app.Activity#getMenuInflater()} method returns a {@link
149android.view.MenuInflater} for the activity. With this object, you can call {@link
150android.view.MenuInflater#inflate(int,Menu) inflate()}, which inflates a menu resource into a
151{@link android.view.Menu} object. In this example, the menu resource defined by
152<code>game_menu.xml</code>
153is inflated into the {@link android.view.Menu} that was passed into {@link
154android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()}. (This callback method for
155the Options Menu is discussed more in the next section.)</p>
156
157
158
159<h2 id="options-menu">Creating an Options Menu</h2>
160
161<div class="figure" style="width:200px">
162  <img src="{@docRoot}images/options_menu.png" height="333" alt="" />
163  <p class="img-caption"><strong>Figure 1.</strong> Screenshot of the Options Menu in the
164Browser.</p>
165</div>
166
167<p>The Options Menu is where you should include basic activity actions and necessary navigation
168items (for example, a button to open the application settings). Items in the Options Menu are
169accessible in two distinct ways: the MENU button or in the <a
170href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a> (on devices running Android 3.0
171or higher).</p>
172
173<p>When running on a device with Android 2.3 and lower, the Options Menu appears at the bottom of
174the screen, as shown in figure 1. When opened, the first visible portion of the Options Menu is
175the icon menu. It holds the first six menu items. If you add more than six items to the
176Options Menu, Android places the sixth item and those after it into the overflow menu, which the
177user can open by touching the "More" menu item.</p>
178
179<p>On Android 3.0 and higher, items from the Options Menu is placed in the Action Bar, which appears
180at the top of the activity in place of the traditional title bar. By default all items from the
181Options Menu are placed in the overflow menu, which the user can open by touching the menu icon
182on the right side of the Action Bar. However, you can place select menu items directly in the
183Action Bar as "action items," for instant access, as shown in figure 2.</p>
184
185<p>When the Android system creates the Options Menu for the first time, it calls your
186activity's {@link android.app.Activity#onCreateOptionsMenu(Menu)
187onCreateOptionsMenu()} method. Override this method in your activity
188and populate the {@link android.view.Menu} that is passed into the method,
189{@link android.view.Menu} by inflating a menu resource as described above in <a
190href="#Inflating">Inflating a Menu Resource</a>. For example:</p>
191
192<pre>
193&#64;Override
194public boolean onCreateOptionsMenu(Menu menu) {
195    MenuInflater inflater = getMenuInflater();
196    inflater.inflate(R.menu.game_menu, menu);
197    return true;
198}
199</pre>
200
201<div class="figure" style="width:500px">
202<img src="{@docRoot}images/ui/actionbar.png" height="34" alt="" />
203<p class="img-caption"><strong>Figure 2.</strong> Screenshot of the Action Bar in the Email
204application, with two action items from the Options Menu, plus the overflow menu.</p>
205</div>
206
207<p>You can also populate the menu in code, using {@link android.view.Menu#add(int,int,int,int)
208add()} to add items to the {@link android.view.Menu}.</p>
209
210<p class="note"><strong>Note:</strong> On Android 2.3 and lower, the system calls {@link
211android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} to create the Options Menu
212when the user opens it for the first time, but on Android 3.0 and greater, the system creates it as
213soon as the activity is created, in order to populate the Action Bar.</p>
214
215
216<h3 id="RespondingOptionsMenu">Responding to user action</h3>
217
218<p>When the user selects a menu item from the Options Menu (including action items in the
219Action Bar), the system calls your activity's
220{@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}
221method. This method passes the
222{@link android.view.MenuItem} that the user selected. You can identify the menu item by calling
223{@link android.view.MenuItem#getItemId()}, which returns the unique ID for the menu
224item (defined by the {@code android:id} attribute in the menu resource or with an integer
225given to the {@link android.view.Menu#add(int,int,int,int) add()} method). You can match this ID
226against known menu items and perform the appropriate action. For example:</p>
227
228<pre>
229&#64;Override
230public boolean onOptionsItemSelected(MenuItem item) {
231    // Handle item selection
232    switch (item.getItemId()) {
233    case R.id.new_game:
234        newGame();
235        return true;
236    case R.id.help:
237        showHelp();
238        return true;
239    default:
240        return super.onOptionsItemSelected(item);
241    }
242}
243</pre>
244
245<p>In this example, {@link android.view.MenuItem#getItemId()} queries the ID for the selected menu
246item and the switch statement compares the ID against the resource IDs that were assigned to menu
247items in the XML resource. When a switch case successfully handles the menu item, it
248returns {@code true} to indicate that the item selection was handled. Otherwise, the default
249statement passes the menu item to the super class, in
250case it can handle the item selected. (If you've directly extended the {@link android.app.Activity}
251class, then the super class returns {@code false}, but it's a good practice to
252pass unhandled menu items to the super class instead of directly returning {@code false}.)</p>
253
254<p>Additionally, Android 3.0 adds the ability for you to define the on-click behavior for a menu
255item in the <a href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a> XML,
256using the {@code android:onClick} attribute. So you don't need to implement {@link
257android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}. Using the {@code
258android:onClick} attribute, you can specify a method to call when the user selects the menu item.
259Your activity must then implement the method specified in the {@code android:onClick} attribute so
260that it accepts a single {@link android.view.MenuItem} parameter&mdash;when the system calls this
261method, it passes the menu item selected.</p>
262
263<p class="note"><strong>Tip:</strong> If your application contains multiple activities and
264some of them provide the same Options Menu, consider creating
265an activity that implements nothing except the {@link android.app.Activity#onCreateOptionsMenu(Menu)
266onCreateOptionsMenu()} and {@link android.app.Activity#onOptionsItemSelected(MenuItem)
267onOptionsItemSelected()} methods. Then extend this class for each activity that should share the
268same Options Menu. This way, you have to manage only one set of code for handling menu
269actions and each descendant class inherits the menu behaviors.<br/><br/>
270If you want to add menu items to one of your descendant activities,
271override {@link android.app.Activity#onCreateOptionsMenu(Menu)
272onCreateOptionsMenu()} in that activity. Call {@code super.onCreateOptionsMenu(menu)} so the
273original menu items are created, then add new menu items with {@link
274android.view.Menu#add(int,int,int,int) menu.add()}. You can also override the super class's
275behavior for individual menu items.</p>
276
277
278<h3 id="ChangingTheMenu">Changing menu items at runtime</h3>
279
280<p>Once the activity is created, the {@link android.app.Activity#onCreateOptionsMenu(Menu)
281onCreateOptionsMenu()} method is
282called only once, as described above. The system keeps and re-uses the {@link
283android.view.Menu} you define in this method until your activity is destroyed. If you want to change
284the Options Menu any time after it's first created, you must override the
285{@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()} method. This passes
286you the {@link android.view.Menu} object as it currently exists. This is useful if you'd like to
287remove, add, disable, or enable menu items depending on the current state of your application.</p>
288
289<p>On Android 2.3 and lower, the system calls {@link android.app.Activity#onPrepareOptionsMenu(Menu)
290onPrepareOptionsMenu()} each time the user opens the Options Menu.</p>
291
292<p>On Android 3.0 and higher, you must call {@link android.app.Activity#invalidateOptionsMenu
293invalidateOptionsMenu()} when you want to update the menu, because the menu is always open. The
294system will then call {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()}
295so you can update the menu items.</p>
296
297<p class="note"><strong>Note:</strong>
298You should never change items in the Options Menu based on the {@link android.view.View} currently
299in focus. When in touch mode (when the user is not using a trackball or d-pad), views
300cannot take focus, so you should never use focus as the basis for modifying
301items in the Options Menu. If you want to provide menu items that are context-sensitive to a {@link
302android.view.View}, use a <a href="#context-menu">Context Menu</a>.</p>
303
304<p>If you're developing for Android 3.0 or higher, be sure to also read the <a
305href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a> developer guide.</p>
306
307
308
309
310<h2 id="context-menu">Creating a Context Menu</h2>
311
312<p>A context menu is conceptually similar to the menu displayed when the user performs a
313"right-click" on a PC. You should use a context menu to provide the user access to
314actions that pertain to a specific item in the user interface. On Android, a context menu is
315displayed when the user performs a "long press" (press and hold) on an item.</p>
316
317<p>You can create a context menu for any View, though context menus are most often used for items in
318a {@link android.widget.ListView}. When the user performs a long-press on an item in a ListView and
319the list is registered to provide a context menu, the list item signals to the user that a context
320menu is available by animating its background color&mdash;it transitions from
321orange to white before opening the context menu. (The Contacts application demonstrates this
322feature.)</p>
323
324<div class="sidebox-wrapper">
325<div class="sidebox">
326<h3>Register a ListView</h3>
327<p>If your activity uses a {@link android.widget.ListView} and
328you want all list items to provide a context menu, register all items for a context
329menu by passing the {@link android.widget.ListView} to {@link
330android.app.Activity#registerForContextMenu(View) registerForContextMenu()}. For
331example, if you're using a {@link android.app.ListActivity}, register all list items like this:</p>
332<p><code>registerForContextMenu({@link android.app.ListActivity#getListView()});</code></p>
333</div>
334</div>
335
336<p>In order for a View to provide a context menu, you must "register" the view for a context
337menu. Call {@link android.app.Activity#registerForContextMenu(View) registerForContextMenu()} and
338pass it the {@link android.view.View} you want to give a context menu. When this View then
339receives a long-press, it displays a context menu.</p>
340
341<p>To define the context menu's appearance and behavior, override your activity's context menu
342callback methods, {@link android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenuInfo)
343onCreateContextMenu()} and
344{@link android.app.Activity#onContextItemSelected(MenuItem) onContextItemSelected()}.</p>
345
346<p>For example, here's an {@link
347android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenuInfo)
348onCreateContextMenu()} that uses the {@code context_menu.xml} menu resource:</p>
349<pre>
350&#64;Override
351public void onCreateContextMenu(ContextMenu menu, View v,
352                                ContextMenuInfo menuInfo) {
353  super.onCreateContextMenu(menu, v, menuInfo);
354  MenuInflater inflater = getMenuInflater();
355  inflater.inflate(R.menu.context_menu, menu);
356}
357</pre>
358
359<p>{@link android.view.MenuInflater} is used to inflate the context menu from a <a
360href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>. (You can also use
361{@link android.view.Menu#add(int,int,int,int) add()} to add menu items.) The callback method
362parameters include the {@link android.view.View}
363that the user selected and a {@link android.view.ContextMenu.ContextMenuInfo} object that provides
364additional information about the item selected. You might use these parameters to determine
365which context menu should be created, but in this example, all context menus for the activity are
366the same.</p>
367
368<p>Then when the user selects an item from the context menu, the system calls {@link
369android.app.Activity#onContextItemSelected(MenuItem) onContextItemSelected()}. Here is an example
370of how you can handle selected items:</p>
371
372<pre>
373&#64;Override
374public boolean onContextItemSelected(MenuItem item) {
375  AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
376  switch (item.getItemId()) {
377  case R.id.edit:
378    editNote(info.id);
379    return true;
380  case R.id.delete:
381    deleteNote(info.id);
382    return true;
383  default:
384    return super.onContextItemSelected(item);
385  }
386}
387</pre>
388
389<p>The structure of this code is similar to the example for <a href="#options-menu">Creating an
390Options Menu</a>, in which {@link android.view.MenuItem#getItemId()} queries the ID for the selected
391menu item and a switch statement matches the item to the IDs that are defined in the menu resource.
392And like the options menu example, the default statement calls the super class in case it
393can handle menu items not handled here, if necessary.</p>
394
395<p>In this example, the selected item is an item from a {@link android.widget.ListView}. To
396perform an action on the selected item, the application needs to know the list
397ID for the selected item (it's position in the ListView). To get the ID, the application calls
398{@link android.view.MenuItem#getMenuInfo()}, which returns a {@link
399android.widget.AdapterView.AdapterContextMenuInfo} object that includes the list ID for the
400selected item in the {@link android.widget.AdapterView.AdapterContextMenuInfo#id id} field. The
401local methods <code>editNote()</code> and <code>deleteNote()</code> methods accept this list ID to
402perform an action on the data specified by the list ID.</p>
403
404<p class="note"><strong>Note:</strong> Items in a context menu do not support icons or shortcut
405keys.</p>
406
407
408
409<h2 id="submenu">Creating Submenus</h2>
410
411<p>A submenu is a menu that the user can open by selecting an item in another menu. You can add a
412submenu to any menu (except a submenu). Submenus are useful when your application has a lot of
413functions that can be organized into topics, like items in a PC application's menu bar (File, Edit,
414View, etc.).</p>
415
416<p>When creating your <a href="{@docRoot}guide/topics/resources/menu-resource.html">menu
417resource</a>, you can create a submenu by adding a {@code &lt;menu&gt;} element as the child of an
418{@code &lt;item&gt;}. For example:</p>
419
420<pre>
421&lt;?xml version="1.0" encoding="utf-8"?&gt;
422&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"&gt;
423    &lt;item android:id="@+id/file"
424          android:icon="@drawable/file"
425          android:title="@string/file" &gt;
426        &lt;!-- "file" submenu --&gt;
427        &lt;menu&gt;
428            &lt;item android:id="@+id/create_new"
429                  android:title="@string/create_new" /&gt;
430            &lt;item android:id="@+id/open"
431                  android:title="@string/open" /&gt;
432        &lt;/menu&gt;
433    &lt;/item&gt;
434&lt;/menu&gt;
435</pre>
436
437<p>When the user selects an item from a submenu, the parent menu's respective on-item-selected
438callback method receives the event. For instance, if the above menu is applied as an Options Menu,
439then the {@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} method
440is called when a submenu item is selected.</p>
441
442<p>You can also use {@link android.view.Menu#addSubMenu(int,int,int,int) addSubMenu()} to
443dynamically add a {@link android.view.SubMenu} to an existing {@link android.view.Menu}. This
444returns the new {@link android.view.SubMenu} object, to which you can add
445submenu items, using {@link android.view.Menu#add(int,int,int,int) add()}</p>
446
447
448
449<h2 id="features">Other Menu Features</h2>
450
451<p>Here are some other features that you can apply to most menu items.</p>
452
453<h3 id="groups">Menu groups</h3>
454
455<p>A menu group is a collection of menu items that share certain traits. With a group, you
456can:</p>
457<ul>
458  <li>Show or hide all items with {@link android.view.Menu#setGroupVisible(int,boolean)
459setGroupVisible()}</li>
460  <li>Enable or disable all items with {@link android.view.Menu#setGroupEnabled(int,boolean)
461setGroupEnabled()}</li>
462  <li>Specify whether all items are checkable with {@link
463android.view.Menu#setGroupCheckable(int,boolean,boolean) setGroupCheckable()}</li>
464</ul>
465
466<p>You can create a group by nesting {@code &lt;item&gt;} elements inside a {@code &lt;group&gt;}
467element in your menu resource or by specifying a group ID with the the {@link
468android.view.Menu#add(int,int,int,int) add()} method.</p>
469
470<p>Here's an example menu resource that includes a group:</p>
471
472<pre>
473&lt;?xml version="1.0" encoding="utf-8"?&gt;
474&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"&gt;
475    &lt;item android:id="@+id/item1"
476          android:icon="@drawable/item1"
477          android:title="@string/item1" /&gt;
478    &lt;!-- menu group --&gt;
479    &lt;group android:id="@+id/group1"&gt;
480        &lt;item android:id="@+id/groupItem1"
481              android:title="@string/groupItem1" /&gt;
482        &lt;item android:id="@+id/groupItem2"
483              android:title="@string/groupItem2" /&gt;
484    &lt;/group&gt;
485&lt;/menu&gt;
486</pre>
487
488<p>The items that are in the group appear the same as the first item that is not in a
489group&mdash;all three items in the menu are siblings. However, you can modify the traits of the two
490items in the group by referencing the group ID and using the methods listed above.</p>
491
492
493<h3 id="checkable">Checkable menu items</h3>
494
495<div class="figure" style="width:200px">
496  <img src="{@docRoot}images/radio_buttons.png" height="333" alt="" />
497  <p class="img-caption"><strong>Figure 3.</strong> Screenshot of a submenu with checkable
498items.</p>
499</div>
500
501<p>A menu can be useful as an interface for turning options on and off, using a checkbox for
502stand-alone options, or radio buttons for groups of
503mutually exclusive options. Figure 2 shows a submenu with items that are checkable with radio
504buttons.</p>
505
506<p class="note"><strong>Note:</strong> Menu items in the Icon Menu (from the Options Menu) cannot
507display a checkbox or radio button. If you choose to make items in the Icon Menu checkable,
508you must manually indicate the checked state by swapping the icon and/or text
509each time the state changes.</p>
510
511<p>You can define the checkable behavior for individual menu items using the {@code
512android:checkable} attribute in the {@code &lt;item&gt;} element, or for an entire group with
513the {@code android:checkableBehavior} attribute in the {@code &lt;group&gt;} element. For
514example, all items in this menu group are checkable with a radio button:</p>
515
516<pre>
517&lt;?xml version="1.0" encoding="utf-8"?&gt;
518&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"&gt;
519    &lt;group android:checkableBehavior="single"&gt;
520        &lt;item android:id="@+id/red"
521              android:title="@string/red" /&gt;
522        &lt;item android:id="@+id/blue"
523              android:title="@string/blue" /&gt;
524    &lt;/group&gt;
525&lt;/menu&gt;
526</pre>
527
528<p>The {@code android:checkableBehavior} attribute accepts either:
529<dl>
530  <dt>{@code single}</dt>
531    <dd>Only one item from the group can be checked (radio buttons)</dd>
532  <dt>{@code all}</dt>
533    <dd>All items can be checked (checkboxes)</dd>
534  <dt>{@code none}</dt>
535    <dd>No items are checkable</dd>
536</dl>
537
538<p>You can apply a default checked state to an item using the {@code android:checked} attribute in
539the {@code &lt;item&gt;} element and change it in code with the {@link
540android.view.MenuItem#setChecked(boolean) setChecked()} method.</p>
541
542<p>When a checkable item is selected, the system calls your respective item-selected callback method
543(such as {@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}). It
544is here that you must set the state of the checkbox, because a checkbox or radio button does not
545change its state automatically. You can query the current state of the item (as it was before the
546user selected it) with {@link android.view.MenuItem#isChecked()} and then set the checked state with
547{@link android.view.MenuItem#setChecked(boolean) setChecked()}. For example:</p>
548
549<pre>
550&#64;Override
551public boolean onOptionsItemSelected(MenuItem item) {
552  switch (item.getItemId()) {
553  case R.id.vibrate:
554  case R.id.dont_vibrate:
555    if (item.isChecked()) item.setChecked(false);
556    else item.setChecked(true);
557    return true;
558  default:
559    return super.onOptionsItemSelected(item);
560  }
561}
562</pre>
563
564<p>If you don't set the checked state this way, then the visible state of the item (the checkbox or
565radio button) will not
566change when the user selects it. When you do set the state, the activity preserves the checked state
567of the item so that when the user opens the menu later, the checked state that you
568set is visible.</p>
569
570<p class="note"><strong>Note:</strong>
571Checkable menu items are intended to be used only on a per-session basis and not saved after the
572application is destroyed. If you have application settings that you would like to save for the user,
573you should store the data using <a
574href="{@docRoot}guide/topics/data/data-storage.html#pref">Shared Preferences</a>.</p>
575
576
577<h3 id="shortcuts">Shortcut keys</h3>
578
579<p>To facilitate quick access to items in the Options Menu when the user's device has a hardware
580keyboard, you can add quick-access shortcut keys using letters and/or numbers, with the
581{@code android:alphabeticShortcut} and {@code android:numericShortcut} attributes in the {@code
582&lt;item&gt;} element. You can also use the methods {@link
583android.view.MenuItem#setAlphabeticShortcut(char)} and {@link
584android.view.MenuItem#setNumericShortcut(char)}. Shortcut keys are <em>not</em>
585case sensitive.</p>
586
587<p>For example, if you apply the "s" character as an alphabetic shortcut to a "save" menu item, then
588when the menu is open (or while the user holds the MENU button) and the user presses the "s" key,
589the "save" menu item is selected.</p>
590
591<p>This shortcut key is displayed as a tip in the menu item, below the menu item name
592(except for items in the Icon Menu, which are displayed only if the user holds the MENU
593button).</p>
594
595<p class="note"><strong>Note:</strong> Shortcut keys for menu items only work on devices with a
596hardware keyboard. Shortcuts cannot be added to items in a Context Menu.</p>
597
598
599
600<h3 id="intents">Dynamically adding menu intents</h3>
601
602<p>Sometimes you'll want a menu item to launch an activity using an {@link android.content.Intent}
603(whether it's an activity in your application or another application). When you know the intent you
604want to use and have a specific menu item that should initiate the intent, you can execute the
605intent with {@link android.app.Activity#startActivity(Intent) startActivity()} during the
606appropriate on-item-selected callback method (such as the {@link
607android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} callback).</p>
608
609<p>However, if you are not certain that the user's device
610contains an application that handles the intent, then adding a menu item that invokes it can result
611in a non-functioning menu item, because the intent might not resolve to an
612activity. To solve this, Android lets you dynamically add menu items to your menu
613when Android finds activities on the device that handle your intent.</p>
614
615<p>To add menu items based on available activities that accept an intent:</p>
616<ol>
617  <li>Define an
618intent with the category {@link android.content.Intent#CATEGORY_ALTERNATIVE} and/or
619{@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE}, plus any other requirements.</li>
620  <li>Call {@link
621android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[])
622Menu.addIntentOptions()}. Android then searches for any applications that can perform the intent
623and adds them to your menu.</li>
624</ol>
625
626<p>If there are no applications installed
627that satisfy the intent, then no menu items are added.</p>
628
629<p class="note"><strong>Note:</strong>
630{@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE} is used to handle the currently
631selected element on the screen. So, it should only be used when creating a Menu in {@link
632android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenuInfo)
633onCreateContextMenu()}.</p>
634
635<p>For example:</p>
636
637<pre>
638&#64;Override
639public boolean onCreateOptionsMenu(Menu menu){
640    super.onCreateOptionsMenu(menu);
641
642    // Create an Intent that describes the requirements to fulfill, to be included
643    // in our menu. The offering app must include a category value of Intent.CATEGORY_ALTERNATIVE.
644    Intent intent = new Intent(null, dataUri);
645    intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
646
647    // Search and populate the menu with acceptable offering applications.
648    menu.addIntentOptions(
649         R.id.intent_group,  // Menu group to which new items will be added
650         0,      // Unique item ID (none)
651         0,      // Order for the items (none)
652         this.getComponentName(),   // The current activity name
653         null,   // Specific items to place first (none)
654         intent, // Intent created above that describes our requirements
655         0,      // Additional flags to control items (none)
656         null);  // Array of MenuItems that correlate to specific items (none)
657
658    return true;
659}</pre>
660
661<p>For each activity found that provides an intent filter matching the intent defined, a menu
662item is added, using the value in the intent filter's <code>android:label</code> as the
663menu item title and the application icon as the menu item icon. The
664{@link android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[])
665addIntentOptions()} method returns the number of menu items added.</p>
666
667<p class="note"><strong>Note:</strong> When you call {@link
668android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[])
669addIntentOptions()}, it overrides any and all menu items by the menu group specified in the first
670argument.</p>
671
672
673<h4>Allowing your activity to be added to other menus</h4>
674
675<p>You can also offer the services of your activity to other applications, so your
676application can be included in the menu of others (reverse the roles described above).</p>
677
678<p>To be included in other application menus, you need to define an intent
679filter as usual, but be sure to include the {@link android.content.Intent#CATEGORY_ALTERNATIVE}
680and/or {@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE} values for the intent filter
681category. For example:</p>
682<pre>
683&lt;intent-filter label="Resize Image">
684    ...
685    &lt;category android:name="android.intent.category.ALTERNATIVE" />
686    &lt;category android:name="android.intent.category.SELECTED_ALTERNATIVE" />
687    ...
688&lt;/intent-filter>
689</pre>
690
691<p>Read more about writing intent filters in the
692<a href="/guide/topics/intents/intents-filters.html">Intents and Intent Filters</a> document.</p>
693
694<p>For a sample application using this technique, see the
695<a href="{@docRoot}resources/samples/NotePad/src/com/example/android/notepad/NoteEditor.html">Note
696Pad</a> sample code.</p>
697