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">Defining a Menu in XML</a></li> 11 <li><a href="#options-menu">Creating an Options Menu</a> 12 <ol> 13 <li><a href="#RespondingOptionsMenu">Handling click events</a></li> 14 <li><a href="#ChangingTheMenu">Changing menu items at runtime</a></li> 15 </ol> 16 </li> 17 <li><a href="#context-menu">Creating Contextual Menus</a> 18 <ol> 19 <li><a href="#FloatingContextMenu">Creating a floating context menu</a></li> 20 <li><a href="#CAB">Using the contextual action mode</a></li> 21 </ol> 22 </li> 23 <li><a href="#PopupMenu">Creating a Popup Menu</a> 24 <ol> 25 <li><a href="#PopupEvents">Handling click events</a></li> 26 </ol> 27 </li> 28 <li><a href="#groups">Creating Menu Groups</a> 29 <ol> 30 <li><a href="#checkable">Using checkable menu items</a></li> 31 </ol> 32 </li> 33 <li><a href="#intents">Adding Menu Items Based on an Intent</a> 34 <ol> 35 <li><a href="#AllowingToAdd">Allowing your activity to be added to other menus</a></li> 36 </ol> 37 </li> 38</ol> 39 40 <h2>Key classes</h2> 41 <ol> 42 <li>{@link android.view.Menu}</li> 43 <li>{@link android.view.MenuItem}</li> 44 <li>{@link android.view.ContextMenu}</li> 45 <li>{@link android.view.ActionMode}</li> 46 </ol> 47 48 <h2>See also</h2> 49 <ol> 50 <li><a href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a></li> 51 <li><a href="{@docRoot}guide/topics/resources/menu-resource.html">Menu Resource</a></li> 52 <li><a 53href="http://android-developers.blogspot.com/2012/01/say-goodbye-to-menu-button.html">Say 54Goodbye to the Menu Button</a></li> 55 </ol> 56</div> 57</div> 58 59<p>Menus are a common user interface component in many types of applications. To provide a familiar 60and consistent user experience, you should use the {@link android.view.Menu} APIs to present user 61actions and other options in your activities.</p> 62 63<p>Beginning with Android 3.0 (API level 11), Android-powered devices are no longer required to 64provide a dedicated <em>Menu</em> button. With this change, Android apps should migrate away from a 65dependence on the traditional 6-item menu panel and instead provide an action bar to present common 66user actions.</p> 67 68<p>Although the design and user experience for some menu items have changed, the semantics to define 69a set of actions and options is still based on the {@link android.view.Menu} APIs. This 70guide shows how to create the three fundamental types of menus or action presentations on all 71versions of Android:</p> 72 73<dl> 74 <dt><strong>Options menu and action bar</strong></dt> 75 <dd>The <a href="#options-menu">options menu</a> is the primary collection of menu items for an 76activity. It's where you should place actions that have a global impact on the app, such as 77"Search," "Compose email," and "Settings." 78 <p>If you're developing for Android 2.3 or lower, users can 79reveal the options menu panel by pressing the <em>Menu</em> button.</p> 80 <p>On Android 3.0 and higher, items from the options menu are presented by the <a 81href="{@docRoot}guide/topics/ui/actionbar.html">action bar</a> as a combination of on-screen action 82items and overflow options. Beginning with Android 3.0, the <em>Menu</em> button is deprecated (some 83devices 84don't have one), so you should migrate toward using the action bar to provide access to actions and 85other options.</p> 86 <p>See the section about <a href="#options-menu">Creating an Options Menu</a>.</p> 87 </dd> 88 89 <dt><strong>Context menu and contextual action mode</strong></dt> 90 91 <dd>A context menu is a <a href="#FloatingContextMenu">floating menu</a> that appears when the 92user performs a long-click on an element. It provides actions that affect the selected content or 93context frame. 94 <p>When developing for Android 3.0 and higher, you should instead use the <a 95href="#CAB">contextual action mode</a> to enable actions on selected content. This mode displays 96action items that affect the selected content in a bar at the top of the screen and allows the user 97to select multiple items.</p> 98 <p>See the section about <a href="#context-menu">Creating Contextual Menus</a>.</p> 99</dd> 100 101 <dt><strong>Popup menu</strong></dt> 102 <dd>A popup menu displays a list of items in a vertical list that's anchored to the view that 103invoked the menu. It's good for providing an overflow of actions that relate to specific content or 104to provide options for a second part of a command. Actions in a popup menu should 105<strong>not</strong> directly affect the corresponding content—that's what contextual actions 106are for. Rather, the popup menu is for extended actions that relate to regions of content in your 107activity. 108 <p>See the section about <a href="#PopupMenu">Creating a Popup Menu</a>.</p> 109</dd> 110</dl> 111 112 113 114<h2 id="xml">Defining a Menu in XML</h2> 115 116<p>For all menu types, Android provides a standard XML format to define menu items. 117Instead of building a menu in your activity's code, you should define a menu and all its items in an 118XML <a href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>. You can then 119inflate the menu resource (load it as a {@link android.view.Menu} object) in your activity or 120fragment.</p> 121 122<p>Using a menu resource is a good practice for a few reasons:</p> 123<ul> 124 <li>It's easier to visualize the menu structure in XML.</li> 125 <li>It separates the content for the menu from your application's behavioral code.</li> 126 <li>It allows you to create alternative menu configurations for different platform versions, 127screen sizes, and other configurations by leveraging the <a 128href="{@docRoot}guide/topics/resources/index.html">app resources</a> framework.</li> 129</ul> 130 131<p>To define the menu, create an XML file inside your project's <code>res/menu/</code> 132directory and build the menu with the following elements:</p> 133<dl> 134 <dt><code><menu></code></dt> 135 <dd>Defines a {@link android.view.Menu}, which is a container for menu items. A 136<code><menu></code> element must be the root node for the file and can hold one or more 137<code><item></code> and <code><group></code> elements.</dd> 138 139 <dt><code><item></code></dt> 140 <dd>Creates a {@link android.view.MenuItem}, which represents a single item in a menu. This 141element may contain a nested <code><menu></code> element in order to create a submenu.</dd> 142 143 <dt><code><group></code></dt> 144 <dd>An optional, invisible container for {@code <item>} elements. It allows you to 145categorize menu items so they share properties such as active state and visibility. For more 146information, see the section about <a href="#groups">Creating Menu Groups</a>.</dd> 147</dl> 148 149 150<p>Here's an example menu named <code>game_menu.xml</code>:</p> 151<pre> 152<?xml version="1.0" encoding="utf-8"?> 153<menu xmlns:android="http://schemas.android.com/apk/res/android"> 154 <item android:id="@+id/new_game" 155 android:icon="@drawable/ic_new_game" 156 android:title="@string/new_game" 157 android:showAsAction="ifRoom"/> 158 <item android:id="@+id/help" 159 android:icon="@drawable/ic_help" 160 android:title="@string/help" /> 161</menu> 162</pre> 163 164<p>The <code><item></code> element supports several attributes you can use to define an item's 165appearance and behavior. The items in the above menu include the following attributes:</p> 166 167<dl> 168 <dt>{@code android:id}</dt> 169 <dd>A resource ID that's unique to the item, which allows the application can recognize the item 170when the user selects it.</dd> 171 <dt>{@code android:icon}</dt> 172 <dd>A reference to a drawable to use as the item's icon.</dd> 173 <dt>{@code android:title}</dt> 174 <dd>A reference to a string to use as the item's title.</dd> 175 <dt>{@code android:showAsAction}</dt> 176 <dd>Specifies when and how this item should appear as an action item in the <a 177href="{@docRoot}guide/topics/ui/actionbar.html">action bar</a>.</dd> 178</dl> 179 180<p>These are the most important attributes you should use, but there are many more available. 181For information about all the supported attributes, see the <a 182href="{@docRoot}guide/topics/resources/menu-resource.html">Menu Resource</a> document.</p> 183 184<p>You can add a submenu to an item in any menu (except a submenu) by adding a {@code <menu>} 185element as the child of an {@code <item>}. Submenus are useful when your application has a lot 186of functions that can be organized into topics, like items in a PC application's menu bar (File, 187Edit, View, etc.). For example:</p> 188 189<pre> 190<?xml version="1.0" encoding="utf-8"?> 191<menu xmlns:android="http://schemas.android.com/apk/res/android"> 192 <item android:id="@+id/file" 193 android:title="@string/file" > 194 <!-- "file" submenu --> 195 <menu> 196 <item android:id="@+id/create_new" 197 android:title="@string/create_new" /> 198 <item android:id="@+id/open" 199 android:title="@string/open" /> 200 </menu> 201 </item> 202</menu> 203</pre> 204 205<p>To use the menu in your activity, you need to inflate the menu resource (convert the XML 206resource into a programmable object) using {@link android.view.MenuInflater#inflate(int,Menu) 207MenuInflater.inflate()}. In the following sections, you'll see how to inflate a menu for each 208menu type.</p> 209 210 211 212<h2 id="options-menu">Creating an Options Menu</h2> 213 214<div class="figure" style="width:200px;margin:0"> 215 <img src="{@docRoot}images/options_menu.png" height="333" alt="" /> 216 <p class="img-caption"><strong>Figure 1.</strong> Options menu in the 217Browser, on Android 2.3.</p> 218</div> 219 220<p>The options menu is where you should include actions and other options that are relevant to the 221current activity context, such as "Search," "Compose email," and "Settings."</p> 222 223<p>Where the items in your options menu appear on the screen depends on the version for which you've 224developed your application:</p> 225 226<ul> 227 <li>If you've developed your application for <strong>Android 2.3.x (API level 10) or 228lower</strong>, the contents of your options menu appear at the bottom of the screen when the user 229presses the <em>Menu</em> button, as shown in figure 1. When opened, the first visible portion is 230the icon 231menu, which holds up to six menu items. If your menu includes more than six items, Android places 232the sixth item and the rest into the overflow menu, which the user can open by selecting 233<em>More</em>.</li> 234 235 <li>If you've developed your application for <strong>Android 3.0 (API level 11) and 236higher</strong>, items from the options menu are available in the <a 237href="{@docRoot}guide/topics/ui/actionbar.html">action bar</a>. By default, the system 238places all items in the action overflow, which the user can reveal with the action overflow icon on 239the right side of the action bar (or by pressing the device <em>Menu</em> button, if available). To 240enable 241quick access to important actions, you can promote a few items to appear in the action bar by adding 242{@code android:showAsAction="ifRoom"} to the corresponding {@code <item>} elements (see figure 2432). <p>For more information about action items and other action bar behaviors, see the <a 244href="{@docRoot}guide/topics/ui/actionbar.html">Action Bar</a> guide. </p> 245<p class="note"><strong>Note:</strong> Even if you're <em>not</em> developing for Android 3.0 or 246higher, you can build your own action bar layout for a similar effect. For an example of how you can 247support older versions of Android with an action bar, see the <a 248href="{@docRoot}resources/samples/ActionBarCompat/index.html">Action Bar Compatibility</a> 249sample.</p> 250</li> 251</ul> 252 253<img src="{@docRoot}images/ui/actionbar.png" alt="" /> 254<p class="img-caption"><strong>Figure 2.</strong> Action bar from the <a 255href="{@docRoot}resources/samples/HoneycombGallery/index.html">Honeycomb Gallery</a> app, showing 256navigation tabs and a camera action item (plus the action overflow button).</p> 257 258<p>You can declare items for the options menu from either your {@link android.app.Activity} 259subclass or a {@link android.app.Fragment} subclass. If both your activity and fragment(s) 260declare items for the options menu, they are combined in the UI. The activity's items appear 261first, followed by those of each fragment in the order in which each fragment is added to the 262activity. If necessary, you can re-order the menu items with the {@code android:orderInCategory} 263attribute in each {@code <item>} you need to move.</p> 264 265<p>To specify the options menu for an activity, override {@link 266android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} (fragments provide their 267own {@link android.app.Fragment#onCreateOptionsMenu onCreateOptionsMenu()} callback). In this 268method, you can inflate your menu resource (<a href="#xml">defined in XML</a>) into the {@link 269android.view.Menu} provided in the callback. For example:</p> 270 271<pre> 272@Override 273public boolean onCreateOptionsMenu(Menu menu) { 274 MenuInflater inflater = {@link android.app.Activity#getMenuInflater()}; 275 inflater.inflate(R.menu.game_menu, menu); 276 return true; 277} 278</pre> 279 280<p>You can also add menu items using {@link android.view.Menu#add(int,int,int,int) 281add()} and retrieve items with {@link android.view.Menu#findItem findItem()} to revise their 282properties with {@link android.view.MenuItem} APIs.</p> 283 284<p>If you've developed your application for Android 2.3.x and lower, the system calls {@link 285android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} to create the options menu 286when the user opens the menu for the first time. If you've developed for Android 3.0 and higher, the 287system calls {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} when 288starting the activity, in order to show items to the action bar.</p> 289 290 291 292<h3 id="RespondingOptionsMenu">Handling click events</h3> 293 294<p>When the user selects an item from the options menu (including action items in the action bar), 295the system calls your activity's {@link android.app.Activity#onOptionsItemSelected(MenuItem) 296onOptionsItemSelected()} method. This method passes the {@link android.view.MenuItem} selected. You 297can identify the item by calling {@link android.view.MenuItem#getItemId()}, which returns the unique 298ID for the menu item (defined by the {@code android:id} attribute in the menu resource or with an 299integer given to the {@link android.view.Menu#add(int,int,int,int) add()} method). You can match 300this ID against known menu items to perform the appropriate action. For example:</p> 301 302<pre> 303@Override 304public boolean onOptionsItemSelected(MenuItem item) { 305 // Handle item selection 306 switch (item.getItemId()) { 307 case R.id.new_game: 308 newGame(); 309 return true; 310 case R.id.help: 311 showHelp(); 312 return true; 313 default: 314 return super.onOptionsItemSelected(item); 315 } 316} 317</pre> 318 319<p>When you successfully handle a menu item, return {@code true}. If you don't handle the menu 320item, you should call the superclass implementation of {@link 321android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} (the default 322implementation returns false).</p> 323 324<p>If your activity includes fragments, the system first calls {@link 325android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} for the activity then 326for each fragment (in the order each fragment was added) until one returns 327{@code true} or all fragments have been called.</p> 328 329<p class="note"><strong>Tip:</strong> Android 3.0 adds the ability for you to define the on-click 330behavior for a menu item in XML, using the {@code android:onClick} attribute. The value for the 331attribute must be the name of a method defined by the activity using the menu. The method 332must be public and accept a single {@link android.view.MenuItem} parameter—when the system 333calls this method, it passes the menu item selected. For more information and an example, see the <a 334href="{@docRoot}guide/topics/resources/menu-resource.html">Menu Resource</a> document.</p> 335 336<p class="note"><strong>Tip:</strong> If your application contains multiple activities and 337some of them provide the same options menu, consider creating 338an activity that implements nothing except the {@link android.app.Activity#onCreateOptionsMenu(Menu) 339onCreateOptionsMenu()} and {@link android.app.Activity#onOptionsItemSelected(MenuItem) 340onOptionsItemSelected()} methods. Then extend this class for each activity that should share the 341same options menu. This way, you can manage one set of code for handling menu 342actions and each descendant class inherits the menu behaviors. 343If you want to add menu items to one of the descendant activities, 344override {@link android.app.Activity#onCreateOptionsMenu(Menu) 345onCreateOptionsMenu()} in that activity. Call {@code super.onCreateOptionsMenu(menu)} so the 346original menu items are created, then add new menu items with {@link 347android.view.Menu#add(int,int,int,int) menu.add()}. You can also override the super class's 348behavior for individual menu items.</p> 349 350 351<h3 id="ChangingTheMenu">Changing menu items at runtime</h3> 352 353<p>After the system calls {@link android.app.Activity#onCreateOptionsMenu(Menu) 354onCreateOptionsMenu()}, it retains an instance of the {@link android.view.Menu} you populate and 355will not call {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} 356again unless the menu is invalidated for some reason. However, you should use {@link 357android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} only to create the initial 358menu state and not to make changes during the activity lifecycle.</p> 359 360<p>If you want to modify the options menu based on 361events that occur during the activity lifecycle, you can do so in 362the {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()} method. This 363method passes you the {@link android.view.Menu} object as it currently exists so you can modify it, 364such as add, remove, or disable items. (Fragments also provide an {@link 365android.app.Fragment#onPrepareOptionsMenu onPrepareOptionsMenu()} callback.)</p> 366 367<p>On Android 2.3.x and lower, the system calls {@link 368android.app.Activity#onPrepareOptionsMenu(Menu) 369onPrepareOptionsMenu()} each time the user opens the options menu (presses the <em>Menu</em> 370button).</p> 371 372<p>On Android 3.0 and higher, the options menu is considered to always be open when menu items are 373presented in the action bar. When an event occurs and you want to perform a menu update, you must 374call {@link android.app.Activity#invalidateOptionsMenu invalidateOptionsMenu()} to request that the 375system call {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()}.</p> 376 377<p class="note"><strong>Note:</strong> 378You should never change items in the options menu based on the {@link android.view.View} currently 379in focus. When in touch mode (when the user is not using a trackball or d-pad), views 380cannot take focus, so you should never use focus as the basis for modifying 381items in the options menu. If you want to provide menu items that are context-sensitive to a {@link 382android.view.View}, use a <a href="#context-menu">Context Menu</a>.</p> 383 384 385 386 387<h2 id="context-menu">Creating Contextual Menus</h2> 388 389<div class="figure" style="width:420px;margin-top:-1em"> 390 <img src="{@docRoot}images/ui/menu-context.png" alt="" /> 391 <p class="img-caption"><strong>Figure 3.</strong> Screenshots of a floating context menu (left) 392and the contextual action bar (right).</p> 393</div> 394 395<p>A contextual menu offers actions that affect a specific item or context frame in the UI. You 396can provide a context menu for any view, but they are most often used for items in a {@link 397android.widget.ListView}, {@link android.widget.GridView}, or other view collections in which 398the user can perform direct actions on each item.</p> 399 400<p>There are two ways to provide contextual actions:</p> 401<ul> 402 <li>In a <a href="#FloatingContextMenu">floating context menu</a>. A menu appears as a 403floating list of menu items (similar to a dialog) when the user performs a long-click (press and 404hold) on a view that declares support for a context menu. Users can perform a contextual 405action on one item at a time.</li> 406 407 <li>In the <a href="#CAB">contextual action mode</a>. This mode is a system implementation of 408{@link android.view.ActionMode} that displays a <em>contextual action bar</em> at the top of the 409screen with action items that affect the selected item(s). When this mode is active, users 410can perform an action on multiple items at once (if your app allows it).</li> 411</ul> 412 413<p class="note"><strong>Note:</strong> The contextual action mode is available on Android 3.0 (API 414level 11) and higher and is the preferred technique for displaying contextual actions when 415available. If your app supports versions lower than 3.0 then you should fall back to a floating 416context menu on those devices.</p> 417 418 419<h3 id="FloatingContextMenu">Creating a floating context menu</h3> 420 421<p>To provide a floating context menu:</p> 422<ol> 423 <li>Register the {@link android.view.View} to which the context menu should be associated by 424calling {@link android.app.Activity#registerForContextMenu(View) registerForContextMenu()} and pass 425it the {@link android.view.View}. 426 <p>If your activity uses a {@link android.widget.ListView} or {@link android.widget.GridView} and 427you want each item to provide the same context menu, register all items for a context menu by 428passing the {@link android.widget.ListView} or {@link android.widget.GridView} to {@link 429android.app.Activity#registerForContextMenu(View) registerForContextMenu()}.</p> 430</li> 431 432 <li>Implement the {@link 433android.view.View.OnCreateContextMenuListener#onCreateContextMenu onCreateContextMenu()} method 434in your {@link android.app.Activity} or {@link android.app.Fragment}. 435 <p>When the registered view receives a long-click event, the system calls your {@link 436android.view.View.OnCreateContextMenuListener#onCreateContextMenu onCreateContextMenu()} 437method. This is where you define the menu items, usually by inflating a menu resource. For 438example:</p> 439<pre> 440@Override 441public void onCreateContextMenu(ContextMenu menu, View v, 442 ContextMenuInfo menuInfo) { 443 super.onCreateContextMenu(menu, v, menuInfo); 444 MenuInflater inflater = getMenuInflater(); 445 inflater.inflate(R.menu.context_menu, menu); 446} 447</pre> 448 449<p>{@link android.view.MenuInflater} allows you to inflate the context menu from a <a 450href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>. The callback method 451parameters include the {@link android.view.View} 452that the user selected and a {@link android.view.ContextMenu.ContextMenuInfo} object that provides 453additional information about the item selected. If your activity has several views that each provide 454a different context menu, you might use these parameters to determine which context menu to 455inflate.</p> 456</li> 457 458<li>Implement {@link android.app.Activity#onContextItemSelected(MenuItem) 459onContextItemSelected()}. 460 <p>When the user selects a menu item, the system calls this method so you can perform the 461appropriate action. For example:</p> 462 463<pre> 464@Override 465public boolean onContextItemSelected(MenuItem item) { 466 AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo(); 467 switch (item.getItemId()) { 468 case R.id.edit: 469 editNote(info.id); 470 return true; 471 case R.id.delete: 472 deleteNote(info.id); 473 return true; 474 default: 475 return super.onContextItemSelected(item); 476 } 477} 478</pre> 479 480<p>The {@link android.view.MenuItem#getItemId()} method queries the ID for 481the selected menu item, which you should assign to each menu item in XML using the {@code 482android:id} attribute, as shown in the section about <a href="#xml">Defining a Menu in 483XML</a>.</p> 484 485<p>When you successfully handle a menu item, return {@code true}. If you don't handle the menu item, 486you should pass the menu item to the superclass implementation. If your activity includes fragments, 487the activity receives this callback first. By calling the superclass when unhandled, the system 488passes the event to the respective callback method in each fragment, one at a time (in the order 489each fragment was added) until {@code true} or {@code false} is returned. (The default 490implementation for {@link android.app.Activity} and {@code android.app.Fragment} return {@code 491false}, so you should always call the superclass when unhandled.)</p> 492</li> 493</ol> 494 495 496<h3 id="CAB">Using the contextual action mode</h3> 497 498<p>The contextual action mode is a system implementation of {@link android.view.ActionMode} that 499focuses user interaction toward performing contextual actions. When a 500user enables this mode by selecting an item, a <em>contextual action bar</em> appears at the top of 501the screen to present actions the user can perform on the currently selected item(s). While this 502mode is enabled, the user can select multiple items (if you allow it), deselect items, and continue 503to navigate within the activity (as much as you're willing to allow). The action mode is disabled 504and the contextual action bar disappears when the user deselects all items, presses the BACK button, 505or selects the <em>Done</em> action on the left side of the bar.</p> 506 507<p class="note"><strong>Note:</strong> The contextual action bar is not necessarily 508associated with the <a href="{@docRoot}guide/topics/ui/actionbar.html">action bar</a>. They operate 509independently, even though the contextual action bar visually overtakes the action bar 510position.</p> 511 512<p>If you're developing for Android 3.0 (API level 11) or higher, you 513should usually use the contextual action mode to present contextual actions, instead of the <a 514href="#FloatingContextMenu">floating context menu</a>.</p> 515 516<p>For views that provide contextual actions, you should usually invoke the contextual action mode 517upon one of two events (or both):</p> 518<ul> 519 <li>The user performs a long-click on the view.</li> 520 <li>The user selects a checkbox or similar UI component within the view.</li> 521</ul> 522 523<p>How your application invokes the contextual action mode and defines the behavior for each 524action depends on your design. There are basically two designs:</p> 525<ul> 526 <li>For contextual actions on individual, arbitrary views.</li> 527 <li>For batch contextual actions on groups of items in a {@link 528android.widget.ListView} or {@link android.widget.GridView} (allowing the user to select multiple 529items and perform an action on them all).</li> 530</ul> 531 532<p>The following sections describe the setup required for each scenario.</p> 533 534 535<h4 id="CABforViews">Enabling the contextual action mode for individual views</h4> 536 537<p>If you want to invoke the contextual action mode only when the user selects specific 538views, you should:</p> 539<ol> 540 <li>Implement the {@link android.view.ActionMode.Callback} interface. In its callback methods, you 541can specify the actions for the contextual action bar, respond to click events on action items, and 542handle other lifecycle events for the action mode.</li> 543 <li>Call {@link android.app.Activity#startActionMode startActionMode()} when you want to show the 544bar (such as when the user long-clicks the view).</li> 545</ol> 546 547<p>For example:</p> 548 549<ol> 550 <li>Implement the {@link android.view.ActionMode.Callback ActionMode.Callback} interface: 551<pre> 552private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() { 553 554 // Called when the action mode is created; startActionMode() was called 555 @Override 556 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 557 // Inflate a menu resource providing context menu items 558 MenuInflater inflater = mode.getMenuInflater(); 559 inflater.inflate(R.menu.context_menu, menu); 560 return true; 561 } 562 563 // Called each time the action mode is shown. Always called after onCreateActionMode, but 564 // may be called multiple times if the mode is invalidated. 565 @Override 566 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 567 return false; // Return false if nothing is done 568 } 569 570 // Called when the user selects a contextual menu item 571 @Override 572 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 573 switch (item.getItemId()) { 574 case R.id.menu_share: 575 shareCurrentItem(); 576 mode.finish(); // Action picked, so close the CAB 577 return true; 578 default: 579 return false; 580 } 581 } 582 583 // Called when the user exits the action mode 584 @Override 585 public void onDestroyActionMode(ActionMode mode) { 586 mActionMode = null; 587 } 588}; 589</pre> 590 591<p>Notice that these event callbacks are almost exactly the same as the callbacks for the <a 592href="#options-menu">options menu</a>, except each of these also pass the {@link 593android.view.ActionMode} object associated with the event. You can use {@link 594android.view.ActionMode} APIs to make various changes to the CAB, such as revise the title and 595subtitle with {@link android.view.ActionMode#setTitle setTitle()} and {@link 596android.view.ActionMode#setSubtitle setSubtitle()} (useful to indicate how many items are 597selected).</p> 598 599<p>Also notice that the above sample sets the {@code mActionMode} variable null when the 600action mode is destroyed. In the next step, you'll see how it's initialized and how saving 601the member variable in your activity or fragment can be useful.</p> 602</li> 603 604 <li>Call {@link android.app.Activity#startActionMode startActionMode()} to enable the contextual 605action mode when appropriate, such as in response to a long-click on a {@link 606android.view.View}:</p> 607 608<pre> 609someView.setOnLongClickListener(new View.OnLongClickListener() { 610 // Called when the user long-clicks on someView 611 public boolean onLongClick(View view) { 612 if (mActionMode != null) { 613 return false; 614 } 615 616 // Start the CAB using the ActionMode.Callback defined above 617 mActionMode = getActivity().startActionMode(mActionModeCallback); 618 view.setSelected(true); 619 return true; 620 } 621}); 622</pre> 623 624<p>When you call {@link android.app.Activity#startActionMode startActionMode()}, the system returns 625the {@link android.view.ActionMode} created. By saving this in a member variable, you can 626make changes to the contextual action bar in response to other events. In the above sample, the 627{@link android.view.ActionMode} is used to ensure that the {@link android.view.ActionMode} instance 628is not recreated if it's already active, by checking whether the member is null before starting the 629action mode.</p> 630</li> 631</ol> 632 633 634 635<h4 id="CABforListView">Enabling batch contextual actions in a ListView or GridView</h4> 636 637<p>If you have a collection of items in a {@link android.widget.ListView} or {@link 638android.widget.GridView} (or another extension of {@link android.widget.AbsListView}) and want to 639allow users to perform batch actions, you should:</p> 640 641<ul> 642 <li>Implement the {@link android.widget.AbsListView.MultiChoiceModeListener} interface and set it 643for the view group with {@link android.widget.AbsListView#setMultiChoiceModeListener 644setMultiChoiceModeListener()}. In the listener's callback methods, you can specify the actions 645for the contextual action bar, respond to click events on action items, and handle other callbacks 646inherited from the {@link android.view.ActionMode.Callback} interface.</li> 647 648 <li>Call {@link android.widget.AbsListView#setChoiceMode setChoiceMode()} with the {@link 649android.widget.AbsListView#CHOICE_MODE_MULTIPLE_MODAL} argument.</li> 650</ul> 651 652<p>For example:</p> 653 654<pre> 655ListView listView = getListView(); 656listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); 657listView.setMultiChoiceModeListener(new MultiChoiceModeListener() { 658 659 @Override 660 public void onItemCheckedStateChanged(ActionMode mode, int position, 661 long id, boolean checked) { 662 // Here you can do something when items are selected/de-selected, 663 // such as update the title in the CAB 664 } 665 666 @Override 667 public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 668 // Respond to clicks on the actions in the CAB 669 switch (item.getItemId()) { 670 case R.id.menu_delete: 671 deleteSelectedItems(); 672 mode.finish(); // Action picked, so close the CAB 673 return true; 674 default: 675 return false; 676 } 677 } 678 679 @Override 680 public boolean onCreateActionMode(ActionMode mode, Menu menu) { 681 // Inflate the menu for the CAB 682 MenuInflater inflater = mode.getMenuInflater(); 683 inflater.inflate(R.menu.context, menu); 684 return true; 685 } 686 687 @Override 688 public void onDestroyActionMode(ActionMode mode) { 689 // Here you can make any necessary updates to the activity when 690 // the CAB is removed. By default, selected items are deselected/unchecked. 691 } 692 693 @Override 694 public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 695 // Here you can perform updates to the CAB due to 696 // an {@link android.view.ActionMode#invalidate} request 697 return false; 698 } 699}); 700</pre> 701 702<p>That's it. Now when the user selects an item with a long-click, the system calls the {@link 703android.widget.AbsListView.MultiChoiceModeListener#onCreateActionMode onCreateActionMode()} 704method and displays the contextual action bar with the specified actions. While the contextual 705action bar is visible, users can select additional items.</p> 706 707<p>In some cases in which the contextual actions provide common action items, you might 708want to add a checkbox or a similar UI element that allows users to select items, because they 709might not discover the long-click behavior. When a user selects the checkbox, you 710can invoke the contextual action mode by setting the respective list item to the checked 711state with {@link android.widget.AbsListView#setItemChecked setItemChecked()}.</p> 712 713 714 715 716<h2 id="PopupMenu">Creating a Popup Menu</h2> 717 718<div class="figure" style="width:220px"> 719<img src="{@docRoot}images/ui/popupmenu.png" alt="" /> 720<p><strong>Figure 4.</strong> A popup menu in the Gmail app, anchored to the overflow 721button at the top-right.</p> 722</div> 723 724<p>A {@link android.widget.PopupMenu} is a modal menu anchored to a {@link android.view.View}. 725It appears below the anchor view if there is room, or above the view otherwise. It's useful for:</p> 726<ul> 727 <li>Providing an overflow-style menu for actions that <em>relate to</em> specific content (such as 728Gmail's email headers, shown in figure 4). 729 <p class="note"><strong>Note:</strong> This is not the same as a context menu, which is 730generally for actions that <em>affect</em> selected content. For actions that affect selected 731content, use the <a href="#CAB">contextual action mode</a> or <a 732href="#FloatingContextMenu">floating context menu</a>.</p></li> 733 <li>Providing a second part of a command sentence (such as a button marked "Add" 734that produces a popup menu with different "Add" options).</li> 735 <li>Providing a drop-down similar to {@link android.widget.Spinner} that does not retain 736a persistent selection.</li> 737</ul> 738 739 740<p class="note"><strong>Note:</strong> {@link android.widget.PopupMenu} is available with API 741level 11 and higher.</p> 742 743<p>If you <a href="#xml">define your menu in XML</a>, here's how you can show the popup menu:</p> 744<ol> 745 <li>Instantate a {@link android.widget.PopupMenu} with its constructor, which takes the 746current application {@link android.content.Context} and the {@link android.view.View} to which the 747menu should be anchored.</li> 748 <li>Use {@link android.view.MenuInflater} to inflate your menu resource into the {@link 749android.view.Menu} object returned by {@link 750android.widget.PopupMenu#getMenu() PopupMenu.getMenu()}. On API level 14 and above, you can use 751{@link android.widget.PopupMenu#inflate PopupMenu.inflate()} instead.</li> 752 <li>Call {@link android.widget.PopupMenu#show() PopupMenu.show()}.</li> 753</ol> 754 755<p>For example, here's a button with the {@link android.R.attr#onClick android:onClick} attribute 756that shows a popup menu:</p> 757 758<pre> 759<ImageButton 760 android:layout_width="wrap_content" 761 android:layout_height="wrap_content" 762 android:src="@drawable/ic_overflow_holo_dark" 763 android:contentDescription="@string/descr_overflow_button" 764 android:onClick="showPopup" /> 765</pre> 766 767<p>The activity can then show the popup menu like this:</p> 768 769<pre> 770public void showPopup(View v) { 771 PopupMenu popup = new PopupMenu(this, v); 772 MenuInflater inflater = popup.getMenuInflater(); 773 inflater.inflate(R.menu.actions, popup.getMenu()); 774 popup.show(); 775} 776</pre> 777 778<p>In API level 14 and higher, you can combine the two lines that inflate the menu with {@link 779android.widget.PopupMenu#inflate PopupMenu.inflate()}.</p> 780 781<p>The menu is dismissed when the user selects an item or touches outside the menu 782area. You can listen for the dismiss event using {@link 783android.widget.PopupMenu.OnDismissListener}.</p> 784 785<h3 id="PopupEvents">Handling click events</h3> 786 787<p>To perform an 788action when the user selects a menu item, you must implement the {@link 789android.widget.PopupMenu.OnMenuItemClickListener} interface and register it with your {@link 790android.widget.PopupMenu} by calling {@link android.widget.PopupMenu#setOnMenuItemClickListener 791setOnMenuItemclickListener()}. When the user selects an item, the system calls the {@link 792android.widget.PopupMenu.OnMenuItemClickListener#onMenuItemClick onMenuItemClick()} callback in 793your interface.</p> 794 795<p>For example:</p> 796 797<pre> 798public void showMenu(View v) { 799 PopupMenu popup = new PopupMenu(this, v); 800 801 // This activity implements OnMenuItemClickListener 802 popup.setOnMenuItemClickListener(this); 803 popup.inflate(R.menu.actions); 804 popup.show(); 805} 806 807@Override 808public boolean onMenuItemClick(MenuItem item) { 809 switch (item.getItemId()) { 810 case R.id.archive: 811 archive(item); 812 return true; 813 case R.id.delete: 814 delete(item); 815 return true; 816 default: 817 return false; 818 } 819} 820</pre> 821 822 823<h2 id="groups">Creating Menu Groups</h2> 824 825<p>A menu group is a collection of menu items that share certain traits. With a group, you 826can:</p> 827<ul> 828 <li>Show or hide all items with {@link android.view.Menu#setGroupVisible(int,boolean) 829setGroupVisible()}</li> 830 <li>Enable or disable all items with {@link android.view.Menu#setGroupEnabled(int,boolean) 831setGroupEnabled()}</li> 832 <li>Specify whether all items are checkable with {@link 833android.view.Menu#setGroupCheckable(int,boolean,boolean) setGroupCheckable()}</li> 834</ul> 835 836<p>You can create a group by nesting {@code <item>} elements inside a {@code <group>} 837element in your menu resource or by specifying a group ID with the the {@link 838android.view.Menu#add(int,int,int,int) add()} method.</p> 839 840<p>Here's an example menu resource that includes a group:</p> 841 842<pre> 843<?xml version="1.0" encoding="utf-8"?> 844<menu xmlns:android="http://schemas.android.com/apk/res/android"> 845 <item android:id="@+id/menu_save" 846 android:icon="@drawable/menu_save" 847 android:title="@string/menu_save" /> 848 <!-- menu group --> 849 <group android:id="@+id/group_delete"> 850 <item android:id="@+id/menu_archive" 851 android:title="@string/menu_archive" /> 852 <item android:id="@+id/menu_delete" 853 android:title="@string/menu_delete" /> 854 </group> 855</menu> 856</pre> 857 858<p>The items that are in the group appear at the same level as the first item—all three items 859in the menu are siblings. However, you can modify the traits of the two 860items in the group by referencing the group ID and using the methods listed above. The system 861will also never separate grouped items. For example, if you declare {@code 862android:showAsAction="ifRoom"} for each item, they will either both appear in the action 863bar or both appear in the action overflow.</p> 864 865 866<h3 id="checkable">Using checkable menu items</h3> 867 868<div class="figure" style="width:200px"> 869 <img src="{@docRoot}images/radio_buttons.png" height="333" alt="" /> 870 <p class="img-caption"><strong>Figure 5.</strong> Screenshot of a submenu with checkable 871items.</p> 872</div> 873 874<p>A menu can be useful as an interface for turning options on and off, using a checkbox for 875stand-alone options, or radio buttons for groups of 876mutually exclusive options. Figure 5 shows a submenu with items that are checkable with radio 877buttons.</p> 878 879<p class="note"><strong>Note:</strong> Menu items in the Icon Menu (from the options menu) cannot 880display a checkbox or radio button. If you choose to make items in the Icon Menu checkable, 881you must manually indicate the checked state by swapping the icon and/or text 882each time the state changes.</p> 883 884<p>You can define the checkable behavior for individual menu items using the {@code 885android:checkable} attribute in the {@code <item>} element, or for an entire group with 886the {@code android:checkableBehavior} attribute in the {@code <group>} element. For 887example, all items in this menu group are checkable with a radio button:</p> 888 889<pre> 890<?xml version="1.0" encoding="utf-8"?> 891<menu xmlns:android="http://schemas.android.com/apk/res/android"> 892 <group android:checkableBehavior="single"> 893 <item android:id="@+id/red" 894 android:title="@string/red" /> 895 <item android:id="@+id/blue" 896 android:title="@string/blue" /> 897 </group> 898</menu> 899</pre> 900 901<p>The {@code android:checkableBehavior} attribute accepts either: 902<dl> 903 <dt>{@code single}</dt> 904 <dd>Only one item from the group can be checked (radio buttons)</dd> 905 <dt>{@code all}</dt> 906 <dd>All items can be checked (checkboxes)</dd> 907 <dt>{@code none}</dt> 908 <dd>No items are checkable</dd> 909</dl> 910 911<p>You can apply a default checked state to an item using the {@code android:checked} attribute in 912the {@code <item>} element and change it in code with the {@link 913android.view.MenuItem#setChecked(boolean) setChecked()} method.</p> 914 915<p>When a checkable item is selected, the system calls your respective item-selected callback method 916(such as {@link android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()}). It 917is here that you must set the state of the checkbox, because a checkbox or radio button does not 918change its state automatically. You can query the current state of the item (as it was before the 919user selected it) with {@link android.view.MenuItem#isChecked()} and then set the checked state with 920{@link android.view.MenuItem#setChecked(boolean) setChecked()}. For example:</p> 921 922<pre> 923@Override 924public boolean onOptionsItemSelected(MenuItem item) { 925 switch (item.getItemId()) { 926 case R.id.vibrate: 927 case R.id.dont_vibrate: 928 if (item.isChecked()) item.setChecked(false); 929 else item.setChecked(true); 930 return true; 931 default: 932 return super.onOptionsItemSelected(item); 933 } 934} 935</pre> 936 937<p>If you don't set the checked state this way, then the visible state of the item (the checkbox or 938radio button) will not 939change when the user selects it. When you do set the state, the activity preserves the checked state 940of the item so that when the user opens the menu later, the checked state that you 941set is visible.</p> 942 943<p class="note"><strong>Note:</strong> 944Checkable menu items are intended to be used only on a per-session basis and not saved after the 945application is destroyed. If you have application settings that you would like to save for the user, 946you should store the data using <a 947href="{@docRoot}guide/topics/data/data-storage.html#pref">Shared Preferences</a>.</p> 948 949 950 951<h2 id="intents">Adding Menu Items Based on an Intent</h2> 952 953<p>Sometimes you'll want a menu item to launch an activity using an {@link android.content.Intent} 954(whether it's an activity in your application or another application). When you know the intent you 955want to use and have a specific menu item that should initiate the intent, you can execute the 956intent with {@link android.app.Activity#startActivity(Intent) startActivity()} during the 957appropriate on-item-selected callback method (such as the {@link 958android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} callback).</p> 959 960<p>However, if you are not certain that the user's device 961contains an application that handles the intent, then adding a menu item that invokes it can result 962in a non-functioning menu item, because the intent might not resolve to an 963activity. To solve this, Android lets you dynamically add menu items to your menu 964when Android finds activities on the device that handle your intent.</p> 965 966<p>To add menu items based on available activities that accept an intent:</p> 967<ol> 968 <li>Define an 969intent with the category {@link android.content.Intent#CATEGORY_ALTERNATIVE} and/or 970{@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE}, plus any other requirements.</li> 971 <li>Call {@link 972android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[]) 973Menu.addIntentOptions()}. Android then searches for any applications that can perform the intent 974and adds them to your menu.</li> 975</ol> 976 977<p>If there are no applications installed 978that satisfy the intent, then no menu items are added.</p> 979 980<p class="note"><strong>Note:</strong> 981{@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE} is used to handle the currently 982selected element on the screen. So, it should only be used when creating a Menu in {@link 983android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenuInfo) 984onCreateContextMenu()}.</p> 985 986<p>For example:</p> 987 988<pre> 989@Override 990public boolean onCreateOptionsMenu(Menu menu){ 991 super.onCreateOptionsMenu(menu); 992 993 // Create an Intent that describes the requirements to fulfill, to be included 994 // in our menu. The offering app must include a category value of Intent.CATEGORY_ALTERNATIVE. 995 Intent intent = new Intent(null, dataUri); 996 intent.addCategory(Intent.CATEGORY_ALTERNATIVE); 997 998 // Search and populate the menu with acceptable offering applications. 999 menu.addIntentOptions( 1000 R.id.intent_group, // Menu group to which new items will be added 1001 0, // Unique item ID (none) 1002 0, // Order for the items (none) 1003 this.getComponentName(), // The current activity name 1004 null, // Specific items to place first (none) 1005 intent, // Intent created above that describes our requirements 1006 0, // Additional flags to control items (none) 1007 null); // Array of MenuItems that correlate to specific items (none) 1008 1009 return true; 1010}</pre> 1011 1012<p>For each activity found that provides an intent filter matching the intent defined, a menu 1013item is added, using the value in the intent filter's <code>android:label</code> as the 1014menu item title and the application icon as the menu item icon. The 1015{@link android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[]) 1016addIntentOptions()} method returns the number of menu items added.</p> 1017 1018<p class="note"><strong>Note:</strong> When you call {@link 1019android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[]) 1020addIntentOptions()}, it overrides any and all menu items by the menu group specified in the first 1021argument.</p> 1022 1023 1024<h3 id="AllowingToAdd">Allowing your activity to be added to other menus</h3> 1025 1026<p>You can also offer the services of your activity to other applications, so your 1027application can be included in the menu of others (reverse the roles described above).</p> 1028 1029<p>To be included in other application menus, you need to define an intent 1030filter as usual, but be sure to include the {@link android.content.Intent#CATEGORY_ALTERNATIVE} 1031and/or {@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE} values for the intent filter 1032category. For example:</p> 1033<pre> 1034<intent-filter label="@string/resize_image"> 1035 ... 1036 <category android:name="android.intent.category.ALTERNATIVE" /> 1037 <category android:name="android.intent.category.SELECTED_ALTERNATIVE" /> 1038 ... 1039</intent-filter> 1040</pre> 1041 1042<p>Read more about writing intent filters in the 1043<a href="/guide/components/intents-filters.html">Intents and Intent Filters</a> document.</p> 1044 1045<p>For a sample application using this technique, see the 1046<a href="{@docRoot}resources/samples/NotePad/src/com/example/android/notepad/NoteEditor.html">Note 1047Pad</a> sample code.</p> 1048