1 page.title=Menus 2 parent.title=User Interface 3 parent.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 53 href="http://android-developers.blogspot.com/2012/01/say-goodbye-to-menu-button.html">Say 54 Goodbye 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 60 and consistent user experience, you should use the {@link android.view.Menu} APIs to present user 61 actions 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 64 provide a dedicated <em>Menu</em> button. With this change, Android apps should migrate away from a 65 dependence on the traditional 6-item menu panel and instead provide an app bar to present common 66 user actions.</p> 67 68 <p>Although the design and user experience for some menu items have changed, the semantics to define 69 a set of actions and options is still based on the {@link android.view.Menu} APIs. This 70 guide shows how to create the three fundamental types of menus or action presentations on all 71 versions 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 76 activity. 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 84 user performs a long-click on an element. It provides actions that affect the selected content or 85 context frame. 86 <p>The <a href="#CAB">contextual action mode</a> displays 87 action items that affect the selected content in a bar at the top of the screen and allows the user 88 to 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 94 invoked the menu. It's good for providing an overflow of actions that relate to specific content or 95 to 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 97 are for. Rather, the popup menu is for extended actions that relate to regions of content in your 98 activity. 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. 108 Instead of building a menu in your activity's code, you should define a menu and all its items in an 109 XML <a href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>. You can then 110 inflate the menu resource (load it as a {@link android.view.Menu} object) in your activity or 111 fragment.</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, 118 screen sizes, and other configurations by leveraging the <a 119 href="{@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> 123 directory 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 132 element 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 136 categorize menu items so they share properties such as active state and visibility. For more 137 information, 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 156 appearance 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 161 when 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. 172 For information about all the supported attributes, see the <a 173 href="{@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>} 176 element as the child of an {@code <item>}. Submenus are useful when your application has a lot 177 of functions that can be organized into topics, like items in a PC application's menu bar (File, 178 Edit, 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 197 resource into a programmable object) using {@link android.view.MenuInflater#inflate(int,Menu) 198 MenuInflater.inflate()}. In the following sections, you'll see how to inflate a menu for each 199 menu 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 208 Browser, 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 212 current 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 215 developed your application:</p> 216 217 <ul> 218 <li>If you've developed your application for <strong>Android 2.3.x (API level 10) or 219 lower</strong>, the contents of your options menu appear at the bottom of the screen when the user 220 presses the <em>Menu</em> button, as shown in figure 1. When opened, the first visible portion is 221 the icon 222 menu, which holds up to six menu items. If your menu includes more than six items, Android places 223 the 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 227 higher</strong>, items from the options menu are available in the 228 app bar. By default, the system 229 places all items in the action overflow, which the user can reveal with the action overflow icon on 230 the right side of the app bar (or by pressing the device <em>Menu</em> button, if available). To 231 enable 232 quick 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 234 2). <p>For more information about action items and other app bar behaviors, see the <a 235 href="{@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 241 href="{@docRoot}resources/samples/HoneycombGallery/index.html">Honeycomb Gallery</a> app, showing 242 navigation 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} 245 subclass or a {@link android.app.Fragment} subclass. If both your activity and fragment(s) 246 declare items for the options menu, they are combined in the UI. The activity's items appear 247 first, followed by those of each fragment in the order in which each fragment is added to the 248 activity. If necessary, you can re-order the menu items with the {@code android:orderInCategory} 249 attribute in each {@code <item>} you need to move.</p> 250 251 <p>To specify the options menu for an activity, override {@link 252 android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} (fragments provide their 253 own {@link android.app.Fragment#onCreateOptionsMenu onCreateOptionsMenu()} callback). In this 254 method, you can inflate your menu resource (<a href="#xml">defined in XML</a>) into the {@link 255 android.view.Menu} provided in the callback. For example:</p> 256 257 <pre> 258 @Override 259 public 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) 267 add()} and retrieve items with {@link android.view.Menu#findItem findItem()} to revise their 268 properties 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 271 android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} to create the options menu 272 when the user opens the menu for the first time. If you've developed for Android 3.0 and higher, 273 the system calls {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} when 274 starting 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), 281 the system calls your activity's {@link android.app.Activity#onOptionsItemSelected(MenuItem) 282 onOptionsItemSelected()} method. This method passes the {@link android.view.MenuItem} selected. You 283 can identify the item by calling {@link android.view.MenuItem#getItemId()}, which returns the unique 284 ID for the menu item (defined by the {@code android:id} attribute in the menu resource or with an 285 integer given to the {@link android.view.Menu#add(int,int,int,int) add()} method). You can match 286 this ID against known menu items to perform the appropriate action. For example:</p> 287 288 <pre> 289 @Override 290 public 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 306 item, you should call the superclass implementation of {@link 307 android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} (the default 308 implementation returns false).</p> 309 310 <p>If your activity includes fragments, the system first calls {@link 311 android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} for the activity then 312 for 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 316 behavior for a menu item in XML, using the {@code android:onClick} attribute. The value for the 317 attribute must be the name of a method defined by the activity using the menu. The method 318 must be public and accept a single {@link android.view.MenuItem} parameter—when the system 319 calls this method, it passes the menu item selected. For more information and an example, see the <a 320 href="{@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 323 some of them provide the same options menu, consider creating 324 an activity that implements nothing except the {@link android.app.Activity#onCreateOptionsMenu(Menu) 325 onCreateOptionsMenu()} and {@link android.app.Activity#onOptionsItemSelected(MenuItem) 326 onOptionsItemSelected()} methods. Then extend this class for each activity that should share the 327 same options menu. This way, you can manage one set of code for handling menu 328 actions and each descendant class inherits the menu behaviors. 329 If you want to add menu items to one of the descendant activities, 330 override {@link android.app.Activity#onCreateOptionsMenu(Menu) 331 onCreateOptionsMenu()} in that activity. Call {@code super.onCreateOptionsMenu(menu)} so the 332 original menu items are created, then add new menu items with {@link 333 android.view.Menu#add(int,int,int,int) menu.add()}. You can also override the super class's 334 behavior 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) 340 onCreateOptionsMenu()}, it retains an instance of the {@link android.view.Menu} you populate and 341 will not call {@link android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} 342 again unless the menu is invalidated for some reason. However, you should use {@link 343 android.app.Activity#onCreateOptionsMenu(Menu) onCreateOptionsMenu()} only to create the initial 344 menu state and not to make changes during the activity lifecycle.</p> 345 346 <p>If you want to modify the options menu based on 347 events that occur during the activity lifecycle, you can do so in 348 the {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()} method. This 349 method passes you the {@link android.view.Menu} object as it currently exists so you can modify it, 350 such as add, remove, or disable items. (Fragments also provide an {@link 351 android.app.Fragment#onPrepareOptionsMenu onPrepareOptionsMenu()} callback.)</p> 352 353 <p>On Android 2.3.x and lower, the system calls {@link 354 android.app.Activity#onPrepareOptionsMenu(Menu) 355 onPrepareOptionsMenu()} each time the user opens the options menu (presses the <em>Menu</em> 356 button).</p> 357 358 <p>On Android 3.0 and higher, the options menu is considered to always be open when menu items are 359 presented in the app bar. When an event occurs and you want to perform a menu update, you must 360 call {@link android.app.Activity#invalidateOptionsMenu invalidateOptionsMenu()} to request that the 361 system call {@link android.app.Activity#onPrepareOptionsMenu(Menu) onPrepareOptionsMenu()}.</p> 362 363 <p class="note"><strong>Note:</strong> 364 You should never change items in the options menu based on the {@link android.view.View} currently 365 in focus. When in touch mode (when the user is not using a trackball or d-pad), views 366 cannot take focus, so you should never use focus as the basis for modifying 367 items in the options menu. If you want to provide menu items that are context-sensitive to a {@link 368 android.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) 378 and 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 382 can provide a context menu for any view, but they are most often used for items in a {@link 383 android.widget.ListView}, {@link android.widget.GridView}, or other view collections in which 384 the 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 389 floating list of menu items (similar to a dialog) when the user performs a long-click (press and 390 hold) on a view that declares support for a context menu. Users can perform a contextual 391 action 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 395 screen with action items that affect the selected item(s). When this mode is active, users 396 can 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 400 level 11) and higher and is the preferred technique for displaying contextual actions when 401 available. If your app supports versions lower than 3.0 then you should fall back to a floating 402 context 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 410 calling {@link android.app.Activity#registerForContextMenu(View) registerForContextMenu()} and pass 411 it the {@link android.view.View}. 412 <p>If your activity uses a {@link android.widget.ListView} or {@link android.widget.GridView} and 413 you want each item to provide the same context menu, register all items for a context menu by 414 passing the {@link android.widget.ListView} or {@link android.widget.GridView} to {@link 415 android.app.Activity#registerForContextMenu(View) registerForContextMenu()}.</p> 416 </li> 417 418 <li>Implement the {@link 419 android.view.View.OnCreateContextMenuListener#onCreateContextMenu onCreateContextMenu()} method 420 in 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 422 android.view.View.OnCreateContextMenuListener#onCreateContextMenu onCreateContextMenu()} 423 method. This is where you define the menu items, usually by inflating a menu resource. For 424 example:</p> 425 <pre> 426 @Override 427 public 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 436 href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>. The callback method 437 parameters include the {@link android.view.View} 438 that the user selected and a {@link android.view.ContextMenu.ContextMenuInfo} object that provides 439 additional information about the item selected. If your activity has several views that each provide 440 a different context menu, you might use these parameters to determine which context menu to 441 inflate.</p> 442 </li> 443 444 <li>Implement {@link android.app.Activity#onContextItemSelected(MenuItem) 445 onContextItemSelected()}. 446 <p>When the user selects a menu item, the system calls this method so you can perform the 447 appropriate action. For example:</p> 448 449 <pre> 450 @Override 451 public 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 467 the selected menu item, which you should assign to each menu item in XML using the {@code 468 android:id} attribute, as shown in the section about <a href="#xml">Defining a Menu in 469 XML</a>.</p> 470 471 <p>When you successfully handle a menu item, return {@code true}. If you don't handle the menu item, 472 you should pass the menu item to the superclass implementation. If your activity includes fragments, 473 the activity receives this callback first. By calling the superclass when unhandled, the system 474 passes the event to the respective callback method in each fragment, one at a time (in the order 475 each fragment was added) until {@code true} or {@code false} is returned. (The default 476 implementation for {@link android.app.Activity} and {@code android.app.Fragment} return {@code 477 false}, 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 485 focuses user interaction toward performing contextual actions. When a 486 user enables this mode by selecting an item, a <em>contextual action bar</em> appears at the top of 487 the screen to present actions the user can perform on the currently selected item(s). While this 488 mode is enabled, the user can select multiple items (if you allow it), deselect items, and continue 489 to navigate within the activity (as much as you're willing to allow). The action mode is disabled 490 and the contextual action bar disappears when the user deselects all items, presses the BACK button, 491 or 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 494 associated with the app bar. They operate 495 independently, even though the contextual action bar visually overtakes the app bar 496 position.</p> 497 498 <p>For views that provide contextual actions, you should usually invoke the contextual action mode 499 upon 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 506 action 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 510 android.widget.ListView} or {@link android.widget.GridView} (allowing the user to select multiple 511 items 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 520 views, you should:</p> 521 <ol> 522 <li>Implement the {@link android.view.ActionMode.Callback} interface. In its callback methods, you 523 can specify the actions for the contextual action bar, respond to click events on action items, and 524 handle other lifecycle events for the action mode.</li> 525 <li>Call {@link android.app.Activity#startActionMode startActionMode()} when you want to show the 526 bar (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> 534 private 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 574 href="#options-menu">options menu</a>, except each of these also pass the {@link 575 android.view.ActionMode} object associated with the event. You can use {@link 576 android.view.ActionMode} APIs to make various changes to the CAB, such as revise the title and 577 subtitle with {@link android.view.ActionMode#setTitle setTitle()} and {@link 578 android.view.ActionMode#setSubtitle setSubtitle()} (useful to indicate how many items are 579 selected).</p> 580 581 <p>Also notice that the above sample sets the {@code mActionMode} variable null when the 582 action mode is destroyed. In the next step, you'll see how it's initialized and how saving 583 the 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 587 action mode when appropriate, such as in response to a long-click on a {@link 588 android.view.View}:</p> 589 590 <pre> 591 someView.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 607 the {@link android.view.ActionMode} created. By saving this in a member variable, you can 608 make 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 610 is not recreated if it's already active, by checking whether the member is null before starting the 611 action 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 620 android.widget.GridView} (or another extension of {@link android.widget.AbsListView}) and want to 621 allow users to perform batch actions, you should:</p> 622 623 <ul> 624 <li>Implement the {@link android.widget.AbsListView.MultiChoiceModeListener} interface and set it 625 for the view group with {@link android.widget.AbsListView#setMultiChoiceModeListener 626 setMultiChoiceModeListener()}. In the listener's callback methods, you can specify the actions 627 for the contextual action bar, respond to click events on action items, and handle other callbacks 628 inherited from the {@link android.view.ActionMode.Callback} interface.</li> 629 630 <li>Call {@link android.widget.AbsListView#setChoiceMode setChoiceMode()} with the {@link 631 android.widget.AbsListView#CHOICE_MODE_MULTIPLE_MODAL} argument.</li> 632 </ul> 633 634 <p>For example:</p> 635 636 <pre> 637 ListView listView = getListView(); 638 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); 639 listView.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 685 android.view.ActionMode.Callback#onCreateActionMode onCreateActionMode()} 686 method and displays the contextual action bar with the specified actions. While the contextual 687 action 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 690 want to add a checkbox or a similar UI element that allows users to select items, because they 691 might not discover the long-click behavior. When a user selects the checkbox, you 692 can invoke the contextual action mode by setting the respective list item to the checked 693 state 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 703 button 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}. 707 It 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 710 Gmail'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 712 generally for actions that <em>affect</em> selected content. For actions that affect selected 713 content, use the <a href="#CAB">contextual action mode</a> or <a 714 href="#FloatingContextMenu">floating context menu</a>.</p></li> 715 <li>Providing a second part of a command sentence (such as a button marked "Add" 716 that 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 718 a persistent selection.</li> 719 </ul> 720 721 722 <p class="note"><strong>Note:</strong> {@link android.widget.PopupMenu} is available with API 723 level 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 728 current application {@link android.content.Context} and the {@link android.view.View} to which the 729 menu should be anchored.</li> 730 <li>Use {@link android.view.MenuInflater} to inflate your menu resource into the {@link 731 android.view.Menu} object returned by {@link 732 android.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 737 that 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> 751 public 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 760 android.widget.PopupMenu#inflate PopupMenu.inflate()}.</p> 761 762 <p>The menu is dismissed when the user selects an item or touches outside the menu 763 area. You can listen for the dismiss event using {@link 764 android.widget.PopupMenu.OnDismissListener}.</p> 765 766 <h3 id="PopupEvents">Handling click events</h3> 767 768 <p>To perform an 769 action when the user selects a menu item, you must implement the {@link 770 android.widget.PopupMenu.OnMenuItemClickListener} interface and register it with your {@link 771 android.widget.PopupMenu} by calling {@link android.widget.PopupMenu#setOnMenuItemClickListener 772 setOnMenuItemclickListener()}. When the user selects an item, the system calls the {@link 773 android.widget.PopupMenu.OnMenuItemClickListener#onMenuItemClick onMenuItemClick()} callback in 774 your interface.</p> 775 776 <p>For example:</p> 777 778 <pre> 779 public 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 789 public 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 807 can:</p> 808 <ul> 809 <li>Show or hide all items with {@link android.view.Menu#setGroupVisible(int,boolean) 810 setGroupVisible()}</li> 811 <li>Enable or disable all items with {@link android.view.Menu#setGroupEnabled(int,boolean) 812 setGroupEnabled()}</li> 813 <li>Specify whether all items are checkable with {@link 814 android.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>} 818 element in your menu resource or by specifying a group ID with the {@link 819 android.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 840 in the menu are siblings. However, you can modify the traits of the two 841 items in the group by referencing the group ID and using the methods listed above. The system 842 will also never separate grouped items. For example, if you declare {@code 843 android:showAsAction="ifRoom"} for each item, they will either both appear in the action 844 bar 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 852 items.</p> 853 </div> 854 855 <p>A menu can be useful as an interface for turning options on and off, using a checkbox for 856 stand-alone options, or radio buttons for groups of 857 mutually exclusive options. Figure 5 shows a submenu with items that are checkable with radio 858 buttons.</p> 859 860 <p class="note"><strong>Note:</strong> Menu items in the Icon Menu (from the options menu) cannot 861 display a checkbox or radio button. If you choose to make items in the Icon Menu checkable, 862 you must manually indicate the checked state by swapping the icon and/or text 863 each time the state changes.</p> 864 865 <p>You can define the checkable behavior for individual menu items using the {@code 866 android:checkable} attribute in the {@code <item>} element, or for an entire group with 867 the {@code android:checkableBehavior} attribute in the {@code <group>} element. For 868 example, 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 893 the {@code <item>} element and change it in code with the {@link 894 android.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 898 is here that you must set the state of the checkbox, because a checkbox or radio button does not 899 change its state automatically. You can query the current state of the item (as it was before the 900 user 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 905 public 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 919 radio button) will not 920 change when the user selects it. When you do set the state, the activity preserves the checked state 921 of the item so that when the user opens the menu later, the checked state that you 922 set is visible.</p> 923 924 <p class="note"><strong>Note:</strong> 925 Checkable menu items are intended to be used only on a per-session basis and not saved after the 926 application is destroyed. If you have application settings that you would like to save for the user, 927 you should store the data using <a 928 href="{@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 936 want to use and have a specific menu item that should initiate the intent, you can execute the 937 intent with {@link android.app.Activity#startActivity(Intent) startActivity()} during the 938 appropriate on-item-selected callback method (such as the {@link 939 android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} callback).</p> 940 941 <p>However, if you are not certain that the user's device 942 contains an application that handles the intent, then adding a menu item that invokes it can result 943 in a non-functioning menu item, because the intent might not resolve to an 944 activity. To solve this, Android lets you dynamically add menu items to your menu 945 when 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 950 intent 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 953 android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[]) 954 Menu.addIntentOptions()}. Android then searches for any applications that can perform the intent 955 and adds them to your menu.</li> 956 </ol> 957 958 <p>If there are no applications installed 959 that 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 963 selected element on the screen. So, it should only be used when creating a Menu in {@link 964 android.app.Activity#onCreateContextMenu(ContextMenu,View,ContextMenuInfo) 965 onCreateContextMenu()}.</p> 966 967 <p>For example:</p> 968 969 <pre> 970 @Override 971 public 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 994 item is added, using the value in the intent filter's <code>android:label</code> as the 995 menu 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[]) 997 addIntentOptions()} method returns the number of menu items added.</p> 998 999 <p class="note"><strong>Note:</strong> When you call {@link 1000 android.view.Menu#addIntentOptions(int,int,int,ComponentName,Intent[],Intent,int,MenuItem[]) 1001 addIntentOptions()}, it overrides any and all menu items by the menu group specified in the first 1002 argument.</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 1008 application 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 1011 filter as usual, but be sure to include the {@link android.content.Intent#CATEGORY_ALTERNATIVE} 1012 and/or {@link android.content.Intent#CATEGORY_SELECTED_ALTERNATIVE} values for the intent filter 1013 category. 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 1028 Pad</a> sample code.</p> 1029