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