summaryrefslogtreecommitdiffstats
path: root/docs/html/guide/topics/ui/menus.jd
blob: 7b5b3dc2f3c1899204366ea9d09be7fb52f43d5d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
page.title=Menus
parent.title=User Interface
parent.link=index.html
@jd:body

<div id="qv-wrapper">
<div id="qv">
  <h2>In this document</h2>
  <ol>
    <li><a href="#xml">Creating a Menu Resource</a></li>
    <li><a href="#Inflating">Inflating a Menu Resource</a>
    <li><a href="#options-menu">Creating an Options Menu</a>
      <ol>
        <li><a href="#ChangingTheMenu">Changing menu items at runtime</a></li>
      </ol>
    </li>
    <li><a href="#context-menu">Creating a Context Menu</a></li>
    <li><a href="#submenu">Creating a Submenu</a></li>
    <li><a href="#features">Other 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">Dynamically adding menu intents</a></li>
      </ol>
    </li>
  </ol>

  <h2>Key classes</h2>
  <ol>
    <li>{@link android.view.Menu}</li>
    <li>{@link android.view.MenuItem}</li>
    <li>{@link android.view.ContextMenu}</li>
    <li>{@link android.view.SubMenu}</li>
  </ol>

  <h2>See also</h2>
  <ol>
    <li><a href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a></li>
    <li><a href="{@docRoot}guide/topics/resources/menu-resource.html">Menu Resource</a></li>
  </ol>
</div>
</div>

<p>Menus are an important part of an activity's user interface, which provide users a familiar
way to perform actions. Android offers a simple framework for you to add standard
menus to your application.</p>

<p>There are three types of application menus:</p>
<dl>
  <dt><strong>Options Menu</strong></dt>
    <dd>The primary collection of menu items for an activity, which appears when the user touches
the MENU button. When your application is running on Android 3.0 or later, you can provide
quick access to select menu items by placing them directly in the <a
href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>, as "action items."</dd>
  <dt><strong>Context Menu</strong></dt>
    <dd>A floating list of menu items that appears when the user touches and holds a view
that's registered to provide a context menu.
</dd>
  <dt><strong>Submenu</strong></dt>
    <dd>A floating list of menu items that appears when the user touches a menu item that contains
a nested menu.</dd>
</dl>

<p>This document shows you how to create each type of menu, using XML to define the content of
the menu and callback methods in your activity to respond when the user selects an item.</p>



<h2 id="xml">Creating a Menu Resource</h2>

<p>Instead of instantiating a {@link android.view.Menu} in your application code, you should
define a menu and all its items in an XML <a
href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>, then inflate the menu
resource (load it as a programmable object) in your application code. Using a menu resource to
define your menu is a good practice because it separates the content for the menu from your
application code. It's also easier to visualize the structure and content of a menu in XML.</p>

<p>To create a menu resource, create an XML file inside your project's <code>res/menu/</code>
directory and build the menu with the following elements:</p>
<dl>
  <dt><code>&lt;menu></code></dt>
    <dd>Defines a {@link android.view.Menu}, which is a container for menu items. A
<code>&lt;menu></code> element must be the root node for the file and can hold one or more
<code>&lt;item></code> and <code>&lt;group></code> elements.</dd>

  <dt><code>&lt;item></code></dt>
    <dd>Creates a {@link android.view.MenuItem}, which represents a single item in a menu. This
element may contain a nested <code>&lt;menu></code> element in order to create a submenu.</dd>
    
  <dt><code>&lt;group></code></dt>
    <dd>An optional, invisible container for {@code &lt;item&gt;} elements. It allows you to
categorize menu items so they share properties such as active state and visibility. See the
section about <a href="#groups">Menu groups</a>.</dd>
</dl>


<p>Here's an example menu named <code>game_menu.xml</code>:</p>
<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    &lt;item android:id="@+id/new_game"
          android:icon="@drawable/ic_new_game"
          android:title="@string/new_game" /&gt;
    &lt;item android:id="@+id/help"
          android:icon="@drawable/ic_help"
          android:title="@string/help" /&gt;
&lt;/menu&gt;
</pre>

<p>This example defines a menu with two items. Each item includes the attributes:</p>
<dl>
  <dt>{@code android:id}</dt>
    <dd>A resource ID that's unique to the item, which allows the application can recognize the item
when the user selects it.</dd>
  <dt>{@code android:icon}</dt>
    <dd>A reference to a drawable to use as the item's icon.</dd>
  <dt>{@code android:title}</dt>
    <dd>A reference to a string to use as the item's title.</dd>
</dl>

<p>There are many more attributes you can include in an {@code &lt;item&gt;}, including some that
 specify how the item may appear in the <a
href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a>. For more information about the XML
syntax and attributes for a menu resource, see the <a
href="{@docRoot}guide/topics/resources/menu-resource.html">Menu Resource</a> reference.</p>



<h2 id="Inflating">Inflating a Menu Resource</h2>

<p>From your application code, you can inflate a menu resource (convert the XML resource into a
programmable object) using
{@link android.view.MenuInflater#inflate(int,Menu) MenuInflater.inflate()}. For
example, the following code inflates the <code>game_menu.xml</code> file defined above, during the
{@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} callback method, to
use the menu as the activity's Options Menu:</p>

<pre>
&#64;Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}
</pre>

<p>The {@link android.app.Activity#getMenuInflater()} method returns a {@link
android.view.MenuInflater} for the activity. With this object, you can call {@link
android.view.MenuInflater#inflate(int,Menu) inflate()}, which inflates a menu resource into a
{@link android.view.Menu} object. In this example, the menu resource defined by
<code>game_menu.xml</code>
is inflated into the {@link android.view.Menu} that was passed into {@link
android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()}. (This callback method for
the Options Menu is discussed more in the next section.)</p>



<h2 id="options-menu">Creating an Options Menu</h2>

<div class="figure" style="width:200px">
  <img src="{@docRoot}images/options_menu.png" height="333" alt="" />
  <p class="img-caption"><strong>Figure 1.</strong> Screenshot of the Options Menu in the
Browser.</p>
</div>

<p>The Options Menu is where you should include basic activity actions and necessary navigation
items (for example, a button to open the application settings). Items in the Options Menu are
accessible in two distinct ways: the MENU button or in the <a
href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a> (on devices running Android 3.0
or higher).</p>

<p>When running on a device with Android 2.3 and lower, the Options Menu appears at the bottom of
the screen, as shown in figure 1. When opened, the first visible portion of the Options Menu is
the icon menu. It holds the first six menu items. If you add more than six items to the
Options Menu, Android places the sixth item and those after it into the overflow menu, which the
user can open by touching the "More" menu item.</p>

<p>On Android 3.0 and higher, items from the Options Menu is placed in the Action Bar, which appears
at the top of the activity in place of the traditional title bar. By default all items from the
Options Menu are placed in the overflow menu, which the user can open by touching the menu icon
on the right side of the Action Bar. However, you can place select menu items directly in the
Action Bar as "action items," for instant access, as shown in figure 2.</p>

<p>When the Android system creates the Options Menu for the first time, it calls your
activity's {@link android.app.Activity#onCreateOptionsMenu(Menu)
onCreateOptionsMenu()} method. Override this method in your activity
and populate the {@link android.view.Menu} that is passed into the method,
{@link android.view.Menu} by inflating a menu resource as described above in <a
href="#Inflating">Inflating a Menu Resource</a>. For example:</p>

<pre>
&#64;Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.game_menu, menu);
    return true;
}
</pre>

<div class="figure" style="width:450px">
<img src="{@docRoot}images/ui/actionbar.png" alt="" />
<p class="img-caption"><strong>Figure 2.</strong> Action bar from the <a
href="{@docRoot}resources/samples/HoneycombGallery/index.html">Honeycomb Gallery</a> app, including
navigation tabs and a camera action item (plus the overflow menu button).</p>
</div>

<p>You can also populate the menu in code, using {@link android.view.Menu#add(int,int,int,int)
add()} to add items to the {@link android.view.Menu}.</p>

<p class="note"><strong>Note:</strong> On Android 2.3 and lower, the system calls {@link
android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} to create the Options Menu
when the user opens it for the first time, but on Android 3.0 and greater, the system creates it as
soon as the activity is created, in order to populate the Action Bar.</p>


<h3 id="RespondingOptionsMenu">Responding to user action</h3>

<p>When the user selects a menu item from the Options Menu (including action items in the
Action Bar), the system calls your activity's
{@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}
method. This method passes the
{@link android.view.MenuItem} that the user selected. You can identify the menu item by calling
{@link android.view.MenuItem#getItemId()}, which returns the unique ID for the menu
item (defined by the {@code android:id} attribute in the menu resource or with an integer
given to the {@link android.view.Menu#add(int,int,int,int) add()} method). You can match this ID
against known menu items and perform the appropriate action. For example:</p>

<pre>
&#64;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);
    }
}
</pre>

<p>In this example, {@link android.view.MenuItem#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 the menu item, it
returns {@code true} to indicate that the item selection was handled. Otherwise, the default
statement passes the menu item to the super class, in
case it can handle the item selected. (If you've directly extended the {@link android.app.Activity}
class, then the super class returns {@code false}, but it's a good practice to
pass unhandled menu items to the super class instead of directly returning {@code false}.)</p>

<p>Additionally, Android 3.0 adds the ability for you to define the on-click behavior for a menu
item in the <a href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a> XML,
using the {@code android:onClick} attribute. So you don't need to implement {@link
android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}. Using the {@code
android:onClick} attribute, you can specify a method to call when the user selects the menu item.
Your activity must then implement the method specified in the {@code android:onClick} attribute so 
that it accepts a single {@link android.view.MenuItem} parameter&mdash;when the system calls this
method, it passes the menu item selected.</p>

<p class="note"><strong>Tip:</strong> If your application contains multiple activities and
some of them provide the same Options Menu, consider creating
an activity that implements nothing except the {@link android.app.Activity#onCreateOptionsMenu(Menu)
onCreateOptionsMenu()} and {@link android.app.Activity#onOptionsItemSelected(MenuItem)
onOptionsItemSelected()} methods. Then extend this class for each activity that should share the
same Options Menu. This way, you have to manage only one set of code for handling menu
actions and each descendant class inherits the menu behaviors.<br/><br/>
If you want to add menu items to one of your descendant activities,
override {@link android.app.Activity#onCreateOptionsMenu(Menu)
onCreateOptionsMenu()} in that activity. Call {@code super.onCreateOptionsMenu(menu)} so the
original menu items are created, then add new menu items with {@link
android.view.Menu#add(int,int,int,int) menu.add()}. You can also override the super class's
behavior for individual menu items.</p>


<h3 id="ChangingTheMenu">Changing menu items at runtime</h3>

<p>Once the activity is created, the {@link android.app.Activity#onCreateOptionsMenu(Menu)
onCreateOptionsMenu()} method is
called only once, as described above. The system keeps and re-uses the {@link
android.view.Menu} you define in this method until your activity is destroyed. If you want to change
the Options Menu any time after it's first created, you must override the
{@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()} method. This passes
you the {@link android.view.Menu} object as it currently exists. This is useful if you'd like to
remove, add, disable, or enable menu items depending on the current state of your application.</p>

<p>On Android 2.3 and lower, the system calls {@link android.app.Activity#onPrepareOptionsMenu(Menu)
onPrepareOptionsMenu()} each time the user opens the Options Menu.</p>

<p>On Android 3.0 and higher, you must call {@link android.app.Activity#invalidateOptionsMenu
invalidateOptionsMenu()} when you want to update the menu, because the menu is always open. The
system will then call {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()}
so you can update the menu items.</p>

<p class="note"><strong>Note:</strong> 
You should never change items in the Options Menu based on the {@link android.view.View} currently
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 {@link
android.view.View}, use a <a href="#context-menu">Context Menu</a>.</p>

<p>If you're developing for Android 3.0 or higher, be sure to also read the <a
href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a> developer guide.</p>




<h2 id="context-menu">Creating a Context Menu</h2>

<p>A context menu is conceptually similar to the menu displayed when the user performs a
"right-click" on a PC. You should use a context menu to provide the user access to
actions that pertain to a specific item in the user interface. On Android, a context menu is
displayed when the user performs a "long press" (press and hold) on an item.</p>

<p>You can create a context menu for any View, though context menus are most often used for items in
a {@link android.widget.ListView}. When the user performs a long-press on an item in a ListView and
the list is registered to provide a context menu, the list item signals to the user that a context
menu is available by animating its background color&mdash;it transitions from
orange to white before opening the context menu. (The Contacts application demonstrates this
feature.)</p>

<div class="sidebox-wrapper">
<div class="sidebox">
<h3>Register a ListView</h3>
<p>If your activity uses a {@link android.widget.ListView} and
you want all list items to provide a context menu, register all items for a context
menu by passing the {@link android.widget.ListView} to {@link
android.app.Activity#registerForContextMenu(View) registerForContextMenu()}. For
example, if you're using a {@link android.app.ListActivity}, register all list items like this:</p>
<p><code>registerForContextMenu({@link android.app.ListActivity#getListView()});</code></p>
</div>
</div>

<p>In order for a View to provide a context menu, you must "register" the view for a context
menu. Call {@link android.app.Activity#registerForContextMenu(View) registerForContextMenu()} and
pass it the {@link android.view.View} you want to give a context menu. When this View then
receives a long-press, it displays a context menu.</p>

<p>To define the context menu's appearance and behavior, override your activity's context menu
callback methods, {@link android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenuInfo)
onCreateContextMenu()} and
{@link android.app.Activity#onContextItemSelected(MenuItem) onContextItemSelected()}.</p>

<p>For example, here's an {@link
android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenuInfo)
onCreateContextMenu()} that uses the {@code context_menu.xml} menu resource:</p>
<pre>
&#64;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);
}
</pre>

<p>{@link android.view.MenuInflater} is used to inflate the context menu from a <a
href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>. (You can also use
{@link android.view.Menu#add(int,int,int,int) add()} to add menu items.) The callback method
parameters include the {@link android.view.View}
that the user selected and a {@link android.view.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 menus for the activity are
the same.</p>

<p>Then when the user selects an item from the context menu, the system calls {@link
android.app.Activity#onContextItemSelected(MenuItem) onContextItemSelected()}. Here is an example
of how you can handle selected items:</p>

<pre>
&#64;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);
  }
}
</pre>

<p>The structure of this code is similar to the example for <a href="#options-menu">Creating an
Options Menu</a>, in which {@link android.view.MenuItem#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.</p>

<p>In this example, the selected item is an item from a {@link android.widget.ListView}. To
perform an action on the selected item, the application needs to know the list
ID for the selected item (it's position in the ListView). To get the ID, the application calls
{@link android.view.MenuItem#getMenuInfo()}, which returns a {@link
android.widget.AdapterView.AdapterContextMenuInfo} object that includes the list ID for the
selected item in the {@link android.widget.AdapterView.AdapterContextMenuInfo#id id} field. The
local methods <code>editNote()</code> and <code>deleteNote()</code> methods accept this list ID to
perform an action on the data specified by the list ID.</p>

<p class="note"><strong>Note:</strong> Items in a context menu do not support icons or shortcut
keys.</p>



<h2 id="submenu">Creating Submenus</h2>

<p>A submenu is a menu that the user can open by selecting an item in another menu. You can add a
submenu to any menu (except a submenu). 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.).</p>

<p>When creating your <a href="{@docRoot}guide/topics/resources/menu-resource.html">menu
resource</a>, you can create a submenu by adding a {@code &lt;menu&gt;} element as the child of an
{@code &lt;item&gt;}. For example:</p>

<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    &lt;item android:id="@+id/file"
          android:icon="@drawable/file"
          android:title="@string/file" &gt;
        &lt;!-- "file" submenu --&gt;
        &lt;menu&gt;
            &lt;item android:id="@+id/create_new"
                  android:title="@string/create_new" /&gt;
            &lt;item android:id="@+id/open"
                  android:title="@string/open" /&gt;
        &lt;/menu&gt;
    &lt;/item&gt;
&lt;/menu&gt;
</pre>

<p>When the user selects an item from a submenu, the parent menu's respective on-item-selected
callback method receives the event. For instance, if the above menu is applied as an Options Menu,
then the {@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} method
is called when a submenu item is selected.</p>

<p>You can also use {@link android.view.Menu#addSubMenu(int,int,int,int) addSubMenu()} to
dynamically add a {@link android.view.SubMenu} to an existing {@link android.view.Menu}. This
returns the new {@link android.view.SubMenu} object, to which you can add
submenu items, using {@link android.view.Menu#add(int,int,int,int) add()}</p>



<h2 id="features">Other Menu Features</h2>

<p>Here are some other features that you can apply to most menu items.</p>

<h3 id="groups">Menu groups</h3>

<p>A menu group is a collection of menu items that share certain traits. With a group, you
can:</p>
<ul>
  <li>Show or hide all items with {@link android.view.Menu#setGroupVisible(int,boolean)
setGroupVisible()}</li>
  <li>Enable or disable all items with {@link android.view.Menu#setGroupEnabled(int,boolean)
setGroupEnabled()}</li>
  <li>Specify whether all items are checkable with {@link
android.view.Menu#setGroupCheckable(int,boolean,boolean) setGroupCheckable()}</li>
</ul>

<p>You can create a group by nesting {@code &lt;item&gt;} elements inside a {@code &lt;group&gt;}
element in your menu resource or by specifying a group ID with the the {@link
android.view.Menu#add(int,int,int,int) add()} method.</p>

<p>Here's an example menu resource that includes a group:</p>

<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    &lt;item android:id="@+id/item1"
          android:icon="@drawable/item1"
          android:title="@string/item1" /&gt;
    &lt;!-- menu group --&gt;
    &lt;group android:id="@+id/group1"&gt;
        &lt;item android:id="@+id/groupItem1"
              android:title="@string/groupItem1" /&gt;
        &lt;item android:id="@+id/groupItem2"
              android:title="@string/groupItem2" /&gt;
    &lt;/group&gt;
&lt;/menu&gt;
</pre>

<p>The items that are in the group appear the same as the first item that is not in a
group&mdash;all three items in the menu are siblings. However, you can modify the traits of the two
items in the group by referencing the group ID and using the methods listed above.</p>


<h3 id="checkable">Checkable menu items</h3>

<div class="figure" style="width:200px">
  <img src="{@docRoot}images/radio_buttons.png" height="333" alt="" />
  <p class="img-caption"><strong>Figure 3.</strong> Screenshot of a submenu with checkable
items.</p>
</div>

<p>A menu can be 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.</p>

<p class="note"><strong>Note:</strong> Menu items in the Icon Menu (from the Options Menu) cannot
display a checkbox or radio button. If you choose to make items in the Icon Menu checkable,
you must manually indicate the checked state by swapping the icon and/or text
each time the state changes.</p>

<p>You can define the checkable behavior for individual menu items using the {@code
android:checkable} attribute in the {@code &lt;item&gt;} element, or for an entire group with
the {@code android:checkableBehavior} attribute in the {@code &lt;group&gt;} element. For
example, all items in this menu group are checkable with a radio button:</p>

<pre>
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;menu xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    &lt;group android:checkableBehavior="single"&gt;
        &lt;item android:id="@+id/red"
              android:title="@string/red" /&gt;
        &lt;item android:id="@+id/blue"
              android:title="@string/blue" /&gt;
    &lt;/group&gt;
&lt;/menu&gt;
</pre>

<p>The {@code android:checkableBehavior} attribute accepts either:
<dl>
  <dt>{@code single}</dt>
    <dd>Only one item from the group can be checked (radio buttons)</dd>
  <dt>{@code all}</dt>
    <dd>All items can be checked (checkboxes)</dd>
  <dt>{@code none}</dt>
    <dd>No items are checkable</dd>
</dl>

<p>You can apply a default checked state to an item using the {@code android:checked} attribute in
the {@code &lt;item&gt;} element and change it in code with the {@link
android.view.MenuItem#setChecked(boolean) setChecked()} method.</p>

<p>When a checkable item is selected, the system calls your respective item-selected callback method
(such as {@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}). It
is here that you must set the state of the checkbox, because a checkbox or radio button does not
change its state automatically. You can query the current state of the item (as it was before the
user selected it) with {@link android.view.MenuItem#isChecked()} and then set the checked state with
{@link android.view.MenuItem#setChecked(boolean) setChecked()}. For example:</p>

<pre>
&#64;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);
  }
}
</pre>

<p>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 do set the state, the activity preserves the checked state
of the item so that when the user opens the menu later, the checked state that you
set is visible.</p>

<p class="note"><strong>Note:</strong>
Checkable menu items are intended to be used only on a per-session basis and not saved after the
application is destroyed. If you have application settings that you would like to save for the user,
you should store the data using <a
href="{@docRoot}guide/topics/data/data-storage.html#pref">Shared Preferences</a>.</p>


<h3 id="shortcuts">Shortcut keys</h3>

<p>To facilitate quick access to items in the Options Menu when the user's device has a hardware
keyboard, you can add quick-access shortcut keys using letters and/or numbers, with the
{@code android:alphabeticShortcut} and {@code android:numericShortcut} attributes in the {@code
&lt;item&gt;} element. You can also use the methods {@link
android.view.MenuItem#setAlphabeticShortcut(char)} and {@link
android.view.MenuItem#setNumericShortcut(char)}. Shortcut keys are <em>not</em>
case sensitive.</p>

<p>For example, if you apply the "s" character as an alphabetic shortcut to a "save" menu item, then
when the menu is open (or while the user holds the MENU button) and the user presses the "s" key,
the "save" menu item is selected.</p>

<p>This shortcut key is displayed as a tip in the menu item, below the menu item name
(except for items in the Icon Menu, which are displayed only if the user holds the MENU
button).</p>

<p class="note"><strong>Note:</strong> Shortcut keys for menu items only work on devices with a
hardware keyboard. Shortcuts cannot be added to items in a Context Menu.</p>



<h3 id="intents">Dynamically adding menu intents</h3>

<p>Sometimes you'll want a menu item to launch an activity using an {@link android.content.Intent}
(whether it's an activity in your application or another application). When you know the intent you
want to use and have a specific menu item that should initiate the intent, you can execute the
intent with {@link android.app.Activity#startActivity(Intent) startActivity()} during the
appropriate on-item-selected callback method (such as the {@link
android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} callback).</p>

<p>However, if you are not certain that the user's device
contains an application that handles the intent, then adding a menu item that invokes it can result
in a non-functioning menu item, because the intent might not resolve to an
activity. To solve this, Android lets you dynamically add menu items to your menu
when Android finds activities on the device that handle your intent.</p>

<p>To add menu items based on available activities that accept an intent:</p>
<ol>
  <li>Define an
intent with the category {@link android.content.Intent#CATEGORY_ALTERNATIVE} and/or
{@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE}, plus any other requirements.</li>
  <li>Call {@link
android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[])
Menu.addIntentOptions()}. Android then searches for any applications that can perform the intent
and adds them to your menu.</li>
</ol>

<p>If there are no applications installed
that satisfy the intent, then no menu items are added.</p>

<p class="note"><strong>Note:</strong>
{@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE} is used to handle the currently
selected element on the screen. So, it should only be used when creating a Menu in {@link
android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenuInfo)
onCreateContextMenu()}.</p>

<p>For example:</p>

<pre>
&#64;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(
         R.id.intent_group,  // Menu group to which new items will be added
         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 is added, using the value in the intent filter's <code>android:label</code> as the
menu item title and the application icon as the menu item icon. The
{@link android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[])
addIntentOptions()} method returns the number of menu items added.</p>

<p class="note"><strong>Note:</strong> When you call {@link
android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[])
addIntentOptions()}, it overrides any and all menu items by the menu group specified in the first
argument.</p>


<h4>Allowing your activity to be added to other menus</h4>

<p>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).</p>

<p>To be included in other application menus, you need to define an intent
filter as usual, but be sure to include the {@link android.content.Intent#CATEGORY_ALTERNATIVE}
and/or {@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE} values for the intent filter
category. 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/src/com/example/android/notepad/NoteEditor.html">Note
Pad</a> sample code.</p>