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