1 page.title=Action Bar 2 parent.title=User Interface 3 parent.link=index.html 4 @jd:body 5 6 <div id="qv-wrapper"> 7 <div id="qv"> 8 9 <h2>In this document</h2> 10 <ol> 11 <li><a href="#Adding">Adding the Action Bar</a> 12 <ol> 13 <li><a href="#Removing">Removing the action bar</a></li> 14 </ol> 15 </li> 16 <li><a href="#ActionItems">Adding Action Items</a> 17 <ol> 18 <li><a href="#ChoosingActionItems">Choosing your action items</a></li> 19 <li><a href="#SplitBar">Using split action bar</a></li> 20 </ol> 21 </li> 22 <li><a href="#Home">Using the App Icon for Navigation</a> 23 <ol> 24 <li><a href="#Up">Navigating up</a></li> 25 </ol> 26 </li> 27 <li><a href="#ActionView">Adding an Action View</a> 28 <ol> 29 <li><a href="#ActionViewCollapsing">Handling collapsible action views</a></li> 30 </ol> 31 </li> 32 <li><a href="#ActionProvider">Adding an Action Provider</a> 33 <ol> 34 <li><a href="#ShareActionProvider">Using the ShareActionProvider</a></li> 35 <li><a href="#CreatingActionProvider">Creating a custom action provider</a></li> 36 </ol> 37 </li> 38 <li><a href="#Tabs">Adding Navigation Tabs</a></li> 39 <li><a href="#Dropdown">Adding Drop-down Navigation</a></li> 40 <li><a href="#Style">Styling the Action Bar</a> 41 <ol> 42 <li><a href="#GeneralStyles">General appearance</a></li> 43 <li><a href="#ActionItemStyles">Action items</a></li> 44 <li><a href="#NavigationStyles">Navigation tabs</a></li> 45 <li><a href="#DropDownStyles">Drop-down lists</a></li> 46 <li><a href="#AdvancedStyles">Advanced styling</a></li> 47 </ol> 48 </li> 49 </ol> 50 51 <h2>Key classes</h2> 52 <ol> 53 <li>{@link android.app.ActionBar}</li> 54 <li>{@link android.view.Menu}</li> 55 <li>{@link android.view.ActionProvider}</li> 56 </ol> 57 58 <h2>Related samples</h2> 59 <ol> 60 <li><a 61 href="{@docRoot}resources/samples/HoneycombGallery/index.html">Honeycomb Gallery</a></li> 62 <li><a 63 href="{@docRoot}resources/samples/ActionBarCompat/index.html">Action Bar Compatibility</a></li> 64 <li><a 65 href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/index.html#ActionBar"> 66 API Demos</a></li> 67 </ol> 68 69 <h2>See also</h2> 70 <ol> 71 <li><a 72 href="{@docRoot}design/patterns/actionbar.html">Android Design: Action Bar</a></li> 73 <li><a href="{@docRoot}guide/topics/ui/menus.html">Menus</a></li> 74 <li><a href="{@docRoot}guide/practices/tablets-and-handsets.html">Supporting Tablets 75 and Handsets</a></li> 76 </ol> 77 </div> 78 </div> 79 80 <p>The action bar is a window feature that identifies the application and user location, and 81 provides user actions and navigation modes. You should use the action bar in most activities that 82 need to prominently present user actions or global navigation, because the action bar offers users a 83 consistent interface across applications and the system gracefully adapts the action bar's 84 appearance for different screen configurations. You can control the behaviors and visibility of the 85 action bar with the {@link android.app.ActionBar} APIs, which were added in Android 3.0 (API level 86 11).</p> 87 88 <p>The primary goals of the action bar are to:</p> 89 90 <ul> 91 <li>Provide a dedicated space for identifying the application brand and user location. 92 <p>This is accomplished with the app icon or logo on the left side and the activity title. 93 You might choose to remove the activity title, however, if the current view is identified by a 94 navigation label, such as the currently selected tab.</p></li> 95 96 <li>Provide consistent navigation and view refinement across different applications. 97 <p>The action bar provides built-in tab navigation for switching between <a 98 href="{@docRoot}guide/components/fragments.html">fragments</a>. It also offers a drop-down 99 list you can use as an alternative navigation mode or to refine the current view (such as to sort 100 a list by different criteria).</p> 101 </li> 102 103 <li>Make key actions for the activity (such as "search", "create", "share", etc.) prominent and 104 accessible to the user in a predictable way. 105 <p>You can provide instant access to key user actions by placing items from the <a 106 href="{@docRoot}guide/topics/ui/menus.html#OptionsMenu">options menu</a> directly in the action bar, 107 as "action items." Action items can also provide an "action view," which provides an embedded 108 widget for even more immediate action behaviors. Menu items that are not promoted 109 to an action item are available in the overflow menu, revealed by either the device <em>Menu</em> 110 button 111 (when available) or by an "overflow menu" button in the action bar (when the device does not 112 include a <em>Menu</em> button).</p> 113 </li> 114 </ul> 115 116 <img src="{@docRoot}images/ui/actionbar.png" alt="" width="440" /> 117 <p class="img-caption"><strong>Figure 1.</strong> Action bar from the <a 118 href="{@docRoot}resources/samples/HoneycombGallery/index.html">Honeycomb Gallery</a> app (on a 119 landscape handset), showing the logo on the left, navigation tabs, and an action item on the 120 right (plus the overflow menu button).</p> 121 122 <p class="note"><strong>Note:</strong> If you're looking for information about the contextual 123 action bar for displaying contextual action items, see the <a 124 href="{@docRoot}guide/topics/ui/menus.html#context-menu">Menu</a> guide.</p> 125 126 127 <div class="note design"> 128 <p><strong>Action Bar Design</strong></p> 129 <p>For design guidelines, read Android Design's <a 130 href="{@docRoot}design/patterns/actionbar.html">Action Bar</a> guide.</p> 131 </div> 132 133 134 135 <div class="sidebox-wrapper"> 136 <div class="sidebox"> 137 <h2>Remaining backward-compatible</h2> 138 <p>If you want to provide an action bar in your application <em>and</em> remain compatible with 139 versions of Android older than 3.0, you need to create the action bar in your 140 activity's layout (because the {@link android.app.ActionBar} class is not available on older 141 versions).</p> 142 <p>To help you, the <a 143 href="{@docRoot}resources/samples/ActionBarCompat/index.html">Action Bar Compatibility</a> sample 144 app provides an API layer and action bar layout that allows your app to use some of the {@link 145 android.app.ActionBar} APIs and also support older versions of Android by replacing the traditional 146 title bar with a custom action bar layout.</p> 147 </div> 148 </div> 149 150 151 <h2 id="Adding">Adding the Action Bar</h2> 152 153 <p>Beginning with Android 3.0 (API level 11), the action bar is included in all 154 activities that use the {@link android.R.style#Theme_Holo Theme.Holo} theme (or one of its 155 descendants), which is the default theme when either the <a 156 href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#target">{@code targetSdkVersion}</a> or 157 <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a> 158 attribute is set to {@code "11"} or greater. For example:</p> 159 160 <pre> 161 <manifest ... > 162 <uses-sdk android:minSdkVersion="4" 163 <b>android:targetSdkVersion="11"</b> /> 164 ... 165 </manifest> 166 </pre> 167 168 <p>In this example, the application requires a minimum version of API Level 4 (Android 1.6), but it 169 also targets API level 11 (Android 3.0). This way, when the application runs on Android 3.0 or 170 greater, the system applies the holographic theme to each activity, and thus, each activity includes 171 the action bar.</p> 172 173 <p>If you want to use {@link android.app.ActionBar} APIs, such as to add navigation modes and modify 174 action bar styles, you should set the <a 175 href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a> to {@code 176 "11"} or greater. If you want your app 177 to support older versions of Android, there are ways to use a limited set of {@link 178 android.app.ActionBar} APIs on devices that support API level 11 or higher, while still running 179 on older versions. See the sidebox for information about remaining backward-compatible.</p> 180 181 182 <h3 id="Removing">Removing the action bar</h3> 183 184 <p>If you don't want the action bar for a particular activity, set the activity theme to 185 {@link android.R.style#Theme_Holo_NoActionBar Theme.Holo.NoActionBar}. For example:</p> 186 187 <pre> 188 <activity android:theme="@android:style/Theme.Holo.NoActionBar"> 189 </pre> 190 191 <p>You can also hide the action bar at runtime by calling {@link android.app.ActionBar#hide}. For 192 example:</p> 193 194 <pre> 195 ActionBar actionBar = {@link android.app.Activity#getActionBar()}; 196 actionBar.hide(); 197 </pre> 198 199 <p>When the action bar hides, the system adjusts your activity layout to fill all the 200 screen space now available. You can bring the action bar back with {@link 201 android.app.ActionBar#show()}.</p> 202 203 <p>Beware that hiding and removing the action bar causes your activity to re-layout in order to 204 account for the space consumed by the action bar. If your activity regularly hides and shows the 205 action bar (such as in the Android Gallery app), you might want to use overlay mode. Overlay mode 206 draws the action bar on top of your activity layout rather than in its own area of the screen. This 207 way, your layout remains fixed when the action bar hides and re-appears. To enable overlay mode, 208 create a theme for your activity and set {@link android.R.attr#windowActionBarOverlay 209 android:windowActionBarOverlay} to {@code true}. For more information, see the section about <a 210 href="#Style">Styling the Action Bar</a>.</p> 211 212 <p class="note"><strong>Tip:</strong> If you have a custom activity theme in which you'd like to 213 remove the action bar, set the {@link android.R.styleable#Theme_windowActionBar 214 android:windowActionBar} style property to {@code false}. However, if you remove the action bar 215 using a theme, then the window will not allow the action bar at all, so you cannot add it 216 later—calling {@link android.app.Activity#getActionBar()} will return null.</p> 217 218 219 220 <h2 id="ActionItems">Adding Action Items</h2> 221 222 <p>Sometimes you might want to give users immediate access to an item from the <a 223 href="{@docRoot}guide/topics/ui/menus.html#OptionsMenu">options menu</a>. To do this, you can 224 declare that the menu item should appear in the action bar as an "action item." An action item can 225 include an icon and/or a text title. If a menu item does not appear as an action item, then the 226 system places it in the overflow menu. The overflow menu is revealed either by the device 227 <em>Menu</em> 228 button (if provided by the device) or an additional button in the action bar (if the device does not 229 provide the <em>Menu</em> button).</p> 230 231 <div class="figure" style="width:359px"> 232 <img src="{@docRoot}images/ui/actionbar-item-withtext.png" height="57" alt="" /> 233 <p class="img-caption"><strong>Figure 2.</strong> Two action items with icon and text titles, and 234 the overflow menu button.</p> 235 </div> 236 237 <p>When the activity first starts, the system populates the action bar and overflow menu by calling 238 {@link android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()} for your activity. As 239 discussed in the <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide, it's in 240 this callback method that you should inflate an XML <a 241 href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a> that defines the 242 menu items. For example:</p> 243 244 <pre> 245 @Override 246 public boolean onCreateOptionsMenu(Menu menu) { 247 MenuInflater inflater = getMenuInflater(); 248 inflater.inflate(R.menu.main_activity, menu); 249 return true; 250 } 251 </pre> 252 253 <p>In the XML file, you can request a menu item to appear as an action item by declaring {@code 254 android:showAsAction="ifRoom"} for the {@code <item>} element. This way, the menu item appears 255 in the action bar for quick access only <em>if there is room</em> available. If there's not 256 enough room, the item appears in the overflow menu.</p> 257 258 <p>If your menu item supplies both a title and an icon—with the {@code android:title} and 259 {@code android:icon} attributes—then the action item shows only the icon by default. If you 260 want to display the text title, add {@code "withText"} to the {@code android:showAsAction} 261 attribute. For example:</p> 262 263 <pre> 264 <?xml version="1.0" encoding="utf-8"?> 265 <menu xmlns:android="http://schemas.android.com/apk/res/android"> 266 <item android:id="@+id/menu_save" 267 android:icon="@drawable/ic_menu_save" 268 android:title="@string/menu_save" 269 <b>android:showAsAction="ifRoom|withText"</b> /> 270 </menu> 271 </pre> 272 273 <p class="note"><strong>Note:</strong> The {@code "withText"} value is a <em>hint</em> to the 274 action bar that the text title should appear. The action bar will show the title when possible, but 275 might not if an icon is available and the action bar is constrained for space.</p> 276 277 <p>When the user selects an action item, your activity receives a call to 278 {@link android.app.Activity#onOptionsItemSelected(MenuItem) 279 onOptionsItemSelected()}, passing the ID supplied by the {@code android:id} attribute—the same 280 callback received for all items in the options menu.</p> 281 282 <p>It's important that you always define {@code android:title} for each menu item—even if you 283 don't declare that the title appear with the action item—for three reasons:</p> 284 <ul> 285 <li>If there's not enough room in the action bar for the action item, the menu item appears 286 in the overflow menu and only the title appears.</li> 287 <li>Screen readers for sight-impaired users read the menu item's title.</li> 288 <li>If the action item appears with only the icon, a user can long-press the item to reveal a 289 tool-tip that displays the action item's title.</li> 290 </ul> 291 292 <p>The {@code android:icon} is always optional, but recommended. For icon design recommendations, 293 see the <a href="{@docRoot}guide/practices/ui_guidelines/icon_design_action_bar.html">Action Bar 294 Icon</a> design guidelines.</p> 295 296 <p class="note"><strong>Note:</strong> If you added the menu item from a fragment, via the {@link 297 android.app.Fragment} class's {@link android.app.Fragment#onCreateOptionsMenu onCreateOptionsMenu} 298 callback, then the system calls the respective {@link 299 android.app.Fragment#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} method for that 300 fragment when the user selects one of the fragment's items. However the activity gets a chance to 301 handle the event first, so the system calls {@link 302 android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} on the activity before 303 calling the same callback for the fragment.</p> 304 305 <p>You can also declare an item to <em>"always"</em> appear as an action item, instead of being 306 placed in the overflow menu when space is limited. In most cases, you <strong>should not</strong> 307 force an item to appear in the action bar by using the {@code "always"} value. However, you might 308 need an item to always appear when it provides an <a href="#ActionView">action view</a> that does 309 not offer a default action for the overflow menu. Beware that too 310 many action items can create a cluttered UI and cause layout problems on devices with a narrow 311 screen. It's best to instead use {@code "ifRoom"} to request that an item appear in the action 312 bar, but allow the system to move it into the overflow menu when there's not enough room.</p> 313 314 <p>For more information about creating the options menu that defines your action items, see the <a 315 href="{@docRoot}guide/topics/ui/menus.html#options-menu">Menus</a> developer guide.</p> 316 317 318 319 <h3 id="ChoosingActionItems">Choosing your action items</h3> 320 321 <div class="sidebox-wrapper"> 322 <div class="sidebox"> 323 <h4>Menu items vs. other app controls</h4> 324 <p>As a general rule, all items in the <a 325 href="{@docRoot}guide/topics/ui/menus.html#OptionsMenu">options menu</a> (let alone action items) 326 should have a global impact on the app, rather than affect only a small portion of the interface. 327 For example, if you have a multi-pane layout and one pane shows a video while another lists all 328 videos, the video player controls should appear within the pane containing the video (not in the 329 action bar), while the action bar might provide action items to share the video or save the video to 330 a favorites list.</p> 331 <p>So, even before deciding whether a menu item should appear as an action item, be sure that 332 the item has a global scope for the current activity. If it doesn't, then you should place it 333 as a button in the appropriate context of the activity layout.</p> 334 </div> 335 </div> 336 337 <p>You should carefully choose which items from your options menu should appear as action items by 338 assessing a few key traits. In general, each action item should be <em>at least one</em> 339 of the following:</p> 340 341 <ol> 342 <li><strong>Frequently used</strong>: It's an action that your users need seven out of ten visits 343 or they use it several times in a row. 344 <p>Example frequent actions: "New message" in the Messaging app and 345 "Search" on Google Play.</p> 346 </li> 347 348 <li><strong>Important</strong>: It's an action that you need users to easily discover or, if it's 349 not frequently used, it's important that it be effortless to perform in the few cases that users do 350 need it. 351 <p>Example important actions: "Add network" in Wi-Fi settings and "Switch to camera" in the 352 Gallery app.</p> 353 </li> 354 355 <li><strong>Typical</strong>: It's an action that is typically provided in the action bar in 356 similar apps, so your users expect to find it in yours. 357 <p>Example typical actions: "Refresh" in an email or social app, and "New contact" in the 358 People app.</p> 359 </ol> 360 361 <p>If you believe that more than four of your menu items can be justified as action items, then you 362 should carefully consider their relative level of importance and try to set no more than four as 363 action items (and do so using the {@code "ifRoom"} value to allow the system to put some back in the 364 overflow menu when space is limited on smaller screens). Even if space is available on a wide 365 screen, you should not create a long stream of action items that clutter the UI and appear like a 366 desktop toolbar, so keep the number of action items to a minimum.</p> 367 368 <p>Additionally, the following actions should never appear as action items: Settings, Help, 369 Feedback, or similar. Always keep them in the overflow menu.</p> 370 371 <p class="note"><strong>Note:</strong> Remember that not all devices provide a dedicated hardware 372 button for Search, so if it's an important feature in your app, it should always appear as an 373 action item (and usually as the first item, especially if you offer it with an <a 374 href="#ActionView">action view</a>).</p> 375 376 377 378 <h3 id="SplitBar">Using split action bar</h3> 379 380 <p>When your application is running on Android 4.0 (API level 14) and higher, there's an extra mode 381 available for the action bar called "split action bar." When you enable split action bar, a separate 382 bar appears at the bottom of the screen to display all action items when the activity is running on 383 a narrow screen (such as a portrait-oriented handset). Splitting the action bar to separate 384 the action items ensures that a reasonable amount of space is available to display all your action 385 items on a narrow screen, while leaving room for navigation and title elements at the top.</p> 386 387 <p>To enable split action bar, simply add {@code uiOptions="splitActionBarWhenNarrow"} to your 388 <a href="{@docRoot}guide/topics/manifest/activity-element.html">{@code <activity>}</a> or 389 <a href="{@docRoot}guide/topics/manifest/application-element.html">{@code <application>}</a> 390 manifest element.</p> 391 392 <p>Be aware that Android adjusts the action bar's appearance in a variety of ways, based on the 393 current screen size. Using split action bar is just one option that you can enable to allow the 394 action bar to further optimize the user experience for different screen sizes. In doing so, you 395 may also allow the action bar to collapse navigation tabs into the main action bar. That is, if you 396 use <a href="#Tabs">navigation tabs</a> in your action bar, once the action items are 397 separated on a narrow screen, the navigation tabs may be able to fit into the main action bar rather 398 than be separated into the "stacked action bar." Specifically, if you've disabled the action bar 399 icon and title (with {@link android.app.ActionBar#setDisplayShowHomeEnabled 400 setDisplayShowHomeEnabled(false)} and {@link android.app.ActionBar#setDisplayShowTitleEnabled 401 setDisplayShowTitleEnabled(false)}), then the navigation tabs collapse into the main action bar, as 402 shown by the second device in figure 3.</p> 403 404 <img src="{@docRoot}images/practices/actionbar-phone-splitaction.png" alt=""/> 405 <p class="img-caption"><strong>Figure 3.</strong> Mock-ups of split action bar with navigation tabs 406 on the left; with the app icon and title disabled on the right.</p> 407 408 <p class="note"><strong>Note:</strong> Although the {@link android.R.attr#uiOptions 409 android:uiOptions} attribute was added in Android 4.0 (API level 14), you can safely include it in 410 your application even if your <a 411 href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a> is set to 412 a value lower than {@code "14"} to remain compatible with older versions of Android. When running on 413 older versions, the system simply ignores the XML attribute because it doesn't understand it. The 414 only condition to including it in your manifest is that you must compile your application against a 415 platform version that supports API level 14 or higher. Just be sure that you don't openly use other 416 APIs in your application code that aren't supported by the version declared by your <a 417 href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a> 418 attribute—only XML attributes are safely ignored by older platforms.</p> 419 420 421 422 423 <h2 id="Home">Using the App Icon for Navigation</h2> 424 425 426 <div class="sidebox-wrapper"> 427 <div class="sidebox"> 428 <h2>Using a logo instead of icon</h2> 429 <p>By default, the system uses your application icon in the action bar, as specified by the <a 430 href="{@docRoot}guide/topics/manifest/application-element.html#icon">{@code android:icon}</a> 431 attribute in the <a href="{@docRoot}guide/topics/manifest/application-element.html">{@code 432 <application>}</a> or <a 433 href="{@docRoot}guide/topics/manifest/activity-element.html">{@code 434 <activity>}</a> element. However, if you also specify the <a 435 href="{@docRoot}guide/topics/manifest/application-element.html#logo">{@code android:logo}</a> 436 attribute, then the action bar uses the logo image instead of the icon.</p> 437 <p>A logo should usually be wider than the icon, but should not include unnecessary text. You 438 should generally use a logo only when it represents your brand in a traditional format that users 439 recognize. A good example is the YouTube app's logo—the logo represents the expected user 440 brand, whereas the app's icon is a modified version that conforms to the square requirement.</p> 441 </div> 442 </div> 443 444 445 <p>By default, your application icon appears in the action bar on the left side. If you'd like, 446 you can enable the icon to behave as an action item. In response to user action on the icon, your 447 application should do one of two things:</p> 448 449 <ul> 450 <li>Go to the application "home" activity, or</li> 451 <li>Navigate "up" the application's structural hierarchy</li> 452 </ul> 453 454 <p>When the user touches the icon, the system calls your activity's {@link 455 android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} method with the {@code 456 android.R.id.home} ID. In response, you should either start the home activity or 457 take the user one step up in your application's structural hierarchy.</p> 458 459 <p>If you respond to the application icon by returning to the home activity, you should include 460 the {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} flag in the {@link 461 android.content.Intent}. With this flag, if the activity you're starting already exists in the 462 current task, then all activities on top of it are destroyed and it is brought to the front. 463 Adding this flag is often important because going "home" is an action that's equivalent to "going 464 back" and you should usually not create a new instance of the home activity. Otherwise, you 465 might end up with a long stack of activities in the current task with multiple instances of the 466 home activity.</p> 467 468 <p>For example, here's an implementation of {@link android.app.Activity#onOptionsItemSelected 469 onOptionsItemSelected()} that returns to the application's "home" activity:</p> 470 471 <pre> 472 @Override 473 public boolean onOptionsItemSelected(MenuItem item) { 474 switch (item.getItemId()) { 475 case android.R.id.home: 476 // app icon in action bar clicked; go home 477 Intent intent = new Intent(this, HomeActivity.class); 478 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 479 startActivity(intent); 480 return true; 481 default: 482 return super.onOptionsItemSelected(item); 483 } 484 } 485 </pre> 486 487 <p>In case the user can enter the current activity from another application, you might also want to 488 add the {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag. This flag ensures that, when the 489 user navigates either "home" or "up", the new activity is <strong>not</strong> added to the current 490 task, but instead started in a task that belongs to your application. For example, if the user 491 starts an activity in your application through an intent invoked by another application, then 492 selects the action bar icon to navigate home or up, the {@link 493 android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} flag starts the activity in a task that belongs to 494 your application (not the current task). The system either starts a new task with your new activity 495 as the root activity or, if an existing task exists in the background with an instance of that 496 activity, then that task is brought forward and the target activity receives {@link 497 android.app.Activity#onNewIntent onNewIntent()}. So if your activity accepts intents from other 498 applications (it declares any generic intent filters), you should usually add the {@link 499 android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag to the intent:</p> 500 501 <pre> 502 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 503 </pre> 504 505 <p>For more information about these flags and other back stack behaviors, read the <a 506 href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack</a> 507 developer guide.</p> 508 509 <p class="note"><strong>Note:</strong> If you're using the icon to navigate to the home 510 activity, beware that beginning with Android 4.0 (API level 14), you must explicitly enable the 511 icon as an action item by calling {@link android.app.ActionBar#setHomeButtonEnabled 512 setHomeButtonEnabled(true)} (in previous versions, the icon was enabled as an action item by 513 default).</p> 514 515 516 517 <h3 id="Up">Navigating up</h3> 518 519 <div class="figure" style="width:230px;margin-top:-1em"> 520 <img src="{@docRoot}images/ui/actionbar-logo.png" alt="" /> 521 <p class="img-caption"><strong>Figure 4.</strong> The Email app's standard icon 522 (left) and the "navigate up" icon (right). The system automatically adds the "up" indicator.</p> 523 </div> 524 525 <p>As a supplement to traditional "back" navigation—which takes the user to the previous 526 screen in the task history—you can enable the action bar icon to offer "up" 527 navigation, which should take the user one step up in your application's structural hierarchy. For 528 instance, if the current screen is somewhere deep in the hierarchy of the application, touching the 529 app icon should navigate upward one level, to the parent of the current screen.</p> 530 531 <p>For example, figure 5 illustrates how the BACK button behaves when the user navigates from one 532 application to an activity belonging to a different application (specifically, when composing an 533 email to a person selected from the People app).</p> 534 535 <img src="{@docRoot}images/ui/actionbar-navigate-back.png" alt="" /> 536 <p class="img-caption"><strong>Figure 5.</strong> The BACK button behavior 537 after entering the Email app from the People (or Contacts) app.</p> 538 539 <p>However, if the user wants to stay within the email application after composing the email, 540 up navigation allows the user to navigate upward in the email application, rather than go back 541 to the previous activity. Figure 6 illustrates this scenario, in which the user again comes into 542 the email application, but presses the action bar icon to navigate up, rather than back.</p> 543 544 <img src="{@docRoot}images/ui/actionbar-navigate-up.png" alt="" /> 545 <p class="img-caption"><strong>Figure 6.</strong> Example behavior for UP navigation after 546 entering the Email app from the People app.</p> 547 548 <div class="note design"> 549 <p><strong>Navigation Design</strong></p> 550 <p>For more about how <em>Up</em> and <em>Back</em> navigation differ, read Android Design's <a 551 href="{@docRoot}design/patterns/navigation.html">Navigation</a> guide.</p> 552 </div> 553 554 <p>To enable the icon for up navigation (which displays the "up" indicator next to the icon), call 555 {@link android.app.ActionBar#setDisplayHomeAsUpEnabled setDisplayHomeAsUpEnabled(true)} on your 556 {@link android.app.ActionBar}:</p> 557 558 <pre> 559 protected void onCreate(Bundle savedInstanceState) { 560 super.onCreate(savedInstanceState); 561 562 setContentView(R.layout.main); 563 ActionBar actionBar = getActionBar(); 564 actionBar.setDisplayHomeAsUpEnabled(true); 565 ... 566 } 567 </pre> 568 569 <p>When the user touches the icon, the system calls your activity's {@link 570 android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} method with the {@code 571 android.R.id.home} ID, as shown in the above section about <a href="#Home">Using the App Icon 572 for Navigation</a>.</p> 573 574 <p>Remember to use the {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} flag in the {@link 575 android.content.Intent}, so that you don't create a new instance of the parent activity if one 576 already exists. For instance, if you don't use the {@link 577 android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} flag, then after navigating up, the BACK button will 578 actually take the user "forward", with respect to the application structure, which would be 579 strange.</p> 580 581 <p class="note"><strong>Note:</strong> If there are many paths that the user could have taken to 582 reach the current activity within your application, the up icon should navigate backward along the 583 path the user actually followed to get to the current activity.</p> 584 585 586 587 588 <h2 id="ActionView">Adding an Action View</h2> 589 590 <div class="figure" style="width:300px;margin-top:-1em"> 591 <img src="/images/ui/actionbar-searchview.png" alt="" /> 592 <p class="img-caption"><strong>Figure 7.</strong> An action bar with a collapsed action 593 view for Search (top), then expanded action view with the <code><a 594 href="/reference/android/widget/SearchView.html">SearchView</a></code> widget (bottom).</p> 595 </div> 596 597 598 <p>An action view is a widget that appears in the action bar as a substitute for an action item's 599 button. For example, if you have an item in the options menu for "Search," you can add an action 600 view that replaces the button with a {@link android.widget.SearchView} widget, as shown in figure 601 7.</p> 602 603 <p>To declare an action view for an item in your <a 604 href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>, use either the {@code 605 android:actionLayout} or {@code android:actionViewClass} attribute to specify either a layout 606 resource or widget class to use, respectively. For example:</p> 607 608 <pre> 609 <?xml version="1.0" encoding="utf-8"?> 610 <menu xmlns:android="http://schemas.android.com/apk/res/android"> 611 <item android:id="@+id/menu_search" 612 android:title="@string/menu_search" 613 android:icon="@drawable/ic_menu_search" 614 android:showAsAction="ifRoom|collapseActionView" 615 <b>android:actionViewClass="android.widget.SearchView"</b> /> 616 </menu> 617 </pre> 618 619 <p>Notice that the {@code android:showAsAction} attribute also includes {@code 620 "collapseActionView"}. This is optional and declares that the action view should be collapsed into a 621 button. When the user selects the button, the action view expands. Otherwise, the action view is 622 visible by default and might consume valuable action bar space even when the user is not using it. 623 For more information, see the next section about <a href="#ActionViewCollapsing">Handling 624 collapsible action views</a>.</p> 625 626 <p>If you need to add some event hooks to your action view, you can do so during the {@link 627 android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()} callback. You can acquire elements 628 in an action view by calling {@link android.view.Menu#findItem findItem()} with the ID of the menu 629 item, then call {@link android.view.MenuItem#getActionView}. For 630 example, the search widget from the above sample is acquired like this:</p> 631 632 <pre> 633 @Override 634 public boolean onCreateOptionsMenu(Menu menu) { 635 getMenuInflater().inflate(R.menu.options, menu); 636 SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView(); 637 // Configure the search info and add any event listeners 638 ... 639 return super.onCreateOptionsMenu(menu); 640 } 641 </pre> 642 643 <p>For more information about using the search widget, see <a 644 href="{@docRoot}guide/topics/search/search-dialog.html">Creating a Search Interface</a>.</p> 645 646 647 <h3 id="ActionViewCollapsing">Handling collapsible action views</h3> 648 649 <div class="sidebox-wrapper"> 650 <div class="sidebox"> 651 <h3>Supporting Android 3.0 with an action view</h3> 652 <p>The {@code "collapseActionView"} option was added with Android 4.0 (API level 14). However, if 653 your application supports older versions, you should 654 still declare {@code "collapseActionView"} in order to better support smaller screens. 655 Devices running Android 4.0 and higher will show the action view collapsed, while older versions 656 work as designed otherwise.</p> 657 <p>Adding this value requires that you set your build target to Android 4.0 or higher in order to 658 compile. Older versions of Android ignore the {@code "collapseActionView"} value because they don't 659 understand it. Just be sure not to use other APIs in your source code that are not supported in the 660 version declared by your <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code 661 minSdkVersion}</a>, unless you add the appropriate version check at runtime.</p> 662 </div> 663 </div> 664 665 666 <p>Action views allow you to provide fast access to rich actions without changing activities or 667 fragments, or replacing the action bar. However, it might not be appropriate to make an action view 668 visible by default. To preserve the action bar space (especially when running on smaller screens), 669 you can collapse your action view into an action item button. When the user selects the 670 button, the action view appears in the action bar. When collapsed, the system might place the item 671 into the overflow menu if you've defined {@code android:showAsAction} with {@code "ifRoom"}, but the 672 action view still appears in the action bar when the user selects the item. You can make your action 673 view collapsible by adding {@code "collapseActionView"} to the {@code android:showAsAction} 674 attribute, as shown in the XML above.</p> 675 676 <p>Because the system will expand the action view when the user selects the item, so you 677 <em>do not</em> need to respond to the item in the {@link 678 android.app.Activity#onOptionsItemSelected onOptionsItemSelected} callback. The system still calls 679 {@link android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} when the user selects it, 680 but the system will always expand the action view unless you return {@code true} (indicating 681 you've handled the event instead).</p> 682 683 <p>The system also collapses your action view when the user selects the "up" icon in the action 684 bar or presses the BACK button.</p> 685 686 <p>If necessary, you can expand or collapse the action view in your own code by calling {@link 687 android.view.MenuItem#expandActionView()} and {@link android.view.MenuItem#collapseActionView()} on 688 the {@link android.view.MenuItem}.</p> 689 690 <p class="note"><strong>Note:</strong> Although collapsing your action view is optional, we 691 recommend that you always collapse your action view if it includes {@link 692 android.widget.SearchView}. Also be aware that some devices provide a dedicated SEARCH button and 693 you should expand your search action view if the user presses the SEARCH button. Simply override 694 your activity's {@link android.app.Activity#onKeyUp onKeyUp()} callback method, listen for the 695 {@link android.view.KeyEvent#KEYCODE_SEARCH} event, then call {@link 696 android.view.MenuItem#expandActionView()}.</p> 697 698 <p>If you need to update your activity based on the visibility of your action view, you can receive 699 callbacks when it's expanded and collapsed by defining an {@link 700 android.view.MenuItem.OnActionExpandListener OnActionExpandListener} and registering it with {@link 701 android.view.MenuItem#setOnActionExpandListener setOnActionExpandListener()}. For example:</p> 702 703 <pre> 704 @Override 705 public boolean onCreateOptionsMenu(Menu menu) { 706 getMenuInflater().inflate(R.menu.options, menu); 707 MenuItem menuItem = menu.findItem(R.id.actionItem); 708 ... 709 710 menuItem.setOnActionExpandListener(new OnActionExpandListener() { 711 @Override 712 public boolean onMenuItemActionCollapse(MenuItem item) { 713 // Do something when collapsed 714 return true; // Return true to collapse action view 715 } 716 717 @Override 718 public boolean onMenuItemActionExpand(MenuItem item) { 719 // Do something when expanded 720 return true; // Return true to expand action view 721 } 722 }); 723 } 724 </pre> 725 726 727 728 729 <h2 id="ActionProvider">Adding an Action Provider</h2> 730 731 <div class="figure" style="width:200px"> 732 <img src="{@docRoot}images/ui/actionbar-shareaction.png" alt="" /> 733 <p class="img-caption"><strong>Figure 8.</strong> Screenshot from the Gallery app, with the 734 {@link android.widget.ShareActionProvider} submenu expanded to show share targets.</p> 735 </div> 736 737 <p>Similar to an <a href="#ActionView">action view</a>, an action provider (defined by the {@link 738 android.view.ActionProvider} class) replaces an action item with a customized layout, but it also 739 takes control of all the item's behaviors. When you declare an action provider for a menu 740 item in the action bar, it not only controls the appearance of the item in the action bar with a 741 custom layout, but also handles the default event for the menu item when it appears in the overflow 742 menu. It can also provide a submenu from either the action bar or the overflow menu.</p> 743 744 <p>For example, the {@link android.widget.ShareActionProvider} is an extension of {@link 745 android.view.ActionProvider} that facilitates a share" action by showing a list of available share 746 targets from the action bar. Instead of using a 747 traditional action item that invokes the {@link android.content.Intent#ACTION_SEND} intent, you can 748 declare an instance of {@link android.widget.ShareActionProvider} to handle an action item. This 749 action provider presents an action view with a drop-down list of applications that handle 750 the {@link android.content.Intent#ACTION_SEND} intent, even when the menu item appears in the 751 overflow menu. Hence, when you use an action provider such as this one, you don't 752 have to handle user events on the menu item.</p> 753 754 <p>To declare an action provider for an action item, define the {@code android:actionProviderClass} 755 attribute for the appropriate the {@code <item>} element in your <a 756 href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>, using the 757 fully-qualified class name of the action provider. For example:</p> 758 759 <pre> 760 <?xml version="1.0" encoding="utf-8"?> 761 <menu xmlns:android="http://schemas.android.com/apk/res/android"> 762 <item android:id="@+id/menu_share" 763 android:title="@string/share" 764 android:showAsAction="ifRoom" 765 <strong>android:actionProviderClass="android.widget.ShareActionProvider"</strong> /> 766 ... 767 </menu> 768 </pre> 769 770 <p>In this example, the {@link android.widget.ShareActionProvider} is used as the action provider. 771 At this point, the action provider officially takes control of the menu item and handles both 772 its appearance and behavior in the action bar and its behavior in the overflow menu. You must 773 still provide a text title for the item to be used in the overflow menu.</p> 774 775 <p>Although the action provider can perform the default action for the menu item when it appears in 776 the overflow menu, your activity (or fragment) can override that behavior by 777 also handling the click event from the {@link android.app.Activity#onOptionsItemSelected 778 onOptionsItemSelected()} callback method. If you do not handle the event in that callback, then 779 the action provider receives the {@link android.view.ActionProvider#onPerformDefaultAction()} 780 callback to handle the event. However, if the action provider provides a submenu, then your 781 activity will not receive the {@link android.app.Activity#onOptionsItemSelected 782 onOptionsItemSelected()} callback, because the submenu is shown instead of invoking the default 783 menu item behavior when selected.</p> 784 785 786 787 <h3 id="ShareActionProvider">Using the ShareActionProvider</h3> 788 789 <p>If you want to provide a "share" action in your action bar by leveraging other applications 790 installed on the device (for example, to share a photo using a messaging or social app), then using 791 {@link android.widget.ShareActionProvider} is an effective way to do so, rather than adding an 792 action item that invokes the {@link android.content.Intent#ACTION_SEND} intent. When 793 you use {@link android.widget.ShareActionProvider} for an action item, it presents an action view 794 with a drop-down list of applications that handle the {@link android.content.Intent#ACTION_SEND} 795 intent (as shown in figure 8).</p> 796 797 <p>All the logic for creating the submenu, populating it with share targets, and handling click 798 events (including when the item appears in the overflow menu) is implemented by the {@link 799 android.widget.ShareActionProvider}—the only code you need to write is to declare the action 800 provider for the menu item and specify the share intent.</p> 801 802 <p>By default, the {@link android.widget.ShareActionProvider} retains a ranking for each 803 share target based on how often the user selects each one. The share targets used more frequently 804 appear at the top of the drop-down list and the target used most often appears directly in the 805 action bar as the default share target. By default, the ranking information is 806 saved in a private file with a name specified by {@link 807 android.widget.ShareActionProvider#DEFAULT_SHARE_HISTORY_FILE_NAME}. If you use the {@link 808 android.widget.ShareActionProvider} or an extension of it for only one type of action, then you 809 should continue to use this default history file and there's nothing you need to do. However, if you 810 use {@link android.widget.ShareActionProvider} or an extension of it for multiple actions with 811 semantically different meanings, then each {@link android.widget.ShareActionProvider} should specify 812 its own history file in order to maintain its own history. To specify a 813 different history file for the {@link android.widget.ShareActionProvider}, call {@link 814 android.widget.ShareActionProvider#setShareHistoryFileName setShareHistoryFileName()} and provide 815 an XML file name (for example, {@code "custom_share_history.xml"}).</p> 816 817 <p class="note"><strong>Note:</strong> Although the {@link android.widget.ShareActionProvider} ranks 818 share targets based on frequency of use, the behavior is extensible and extensions of {@link 819 android.widget.ShareActionProvider} can perform different behaviors and ranking based on the history 820 file (if appropriate).</p> 821 822 <p>To add {@link android.widget.ShareActionProvider}, simply define the {@code 823 android:actionProviderClass} attribute with {@code "android.widget.ShareActionProvider"}, as shown 824 in the XML example above. The only thing left to do is define 825 the {@link android.content.Intent} you want to use for sharing. To do so, you must call {@link 826 android.view.MenuItem#getActionProvider} to retrieve the {@link android.widget.ShareActionProvider} 827 that's associated with a {@link android.view.MenuItem}, then call {@link 828 android.widget.ShareActionProvider#setShareIntent setShareIntent()}.</p> 829 830 <p>If the format for the share intent depends on the selected item or other variables that change 831 during the activity lifecycle, you should save the {@link android.widget.ShareActionProvider} in a 832 member field and update it by calling {@link android.widget.ShareActionProvider#setShareIntent 833 setShareIntent()} as necessary. For example:</p> 834 835 <pre> 836 private ShareActionProvider mShareActionProvider; 837 ... 838 839 @Override 840 public boolean onCreateOptionsMenu(Menu menu) { 841 mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.menu_share).getActionProvider(); 842 843 // If you use more than one ShareActionProvider, each for a different action, 844 // use the following line to specify a unique history file for each one. 845 // mShareActionProvider.setShareHistoryFileName("custom_share_history.xml"); 846 847 // Set the default share intent 848 mShareActionProvider.setShareIntent(getDefaultShareIntent()); 849 850 return true; 851 } 852 // When you need to update the share intent somewhere else in the app, call 853 // mShareActionProvider.{@link android.widget.ShareActionProvider#setShareIntent setShareIntent()} 854 </pre> 855 856 <p>The {@link android.widget.ShareActionProvider} now handles all user interaction with the item and 857 you <em>do not</em> need to handle click events from the {@link 858 android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} callback method.</p> 859 860 <p>For a sample using the share action provider, see 861 <a href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/ActionBarShareActionProviderActivity.html" 862 >ActionBarShareActionProviderActivity</a>. 863 864 865 866 <h3 id="CreatingActionProvider">Creating a custom action provider</h3> 867 868 <p>When you want to create an action view that has dynamic behaviors and a default action in the 869 overflow menu, extending {@link android.view.ActionProvider} to define those behaviors is a good 870 solution. Creating your own action provider offers you an organized and reusable component, rather 871 than handling the various action item transformations and behaviors in your fragment or activity 872 code. As shown in the previous section, Android provides one implementation of {@link 873 android.view.ActionProvider} for share actions: the {@link android.widget.ShareActionProvider}.</p> 874 875 <p>To create your own, simply extend the {@link android.view.ActionProvider} class and implement 876 its callback methods as appropriate. Most importantly, you should implement the following:</p> 877 878 <dl> 879 <dt>{@link android.view.ActionProvider#ActionProvider ActionProvider()}</dt> 880 <dd>This constructor passes you the application {@link android.content.Context}, which you 881 should save in a member field to use in the other callback methods.</dd> 882 883 <dt>{@link android.view.ActionProvider#onCreateActionView()}</dt> 884 <dd>This is where you define the action view for the item. Use the {@link 885 android.content.Context} acquired from the constructor to instantiate a {@link 886 android.view.LayoutInflater} and inflate your action view layout from an XML resource, then hook 887 up event listeners. For example: 888 <pre> 889 public View onCreateActionView() { 890 // Inflate the action view to be shown on the action bar. 891 LayoutInflater layoutInflater = LayoutInflater.from(mContext); 892 View view = layoutInflater.inflate(R.layout.action_provider, null); 893 ImageButton button = (ImageButton) view.findViewById(R.id.button); 894 button.setOnClickListener(new View.OnClickListener() { 895 @Override 896 public void onClick(View v) { 897 // Do something... 898 } 899 }); 900 return view; 901 } 902 </pre> 903 </dd> 904 905 <dt>{@link android.view.ActionProvider#onPerformDefaultAction()}</dt> 906 <dd>The system calls this when the menu item is selected from the overflow menu and the 907 action provider should perform a default action for the menu item. 908 <p>However, if your action provider provides a submenu, through the {@link 909 android.view.ActionProvider#onPrepareSubMenu onPrepareSubMenu()} callback, then the submenu 910 appears even when the menu item is in the overflow menu. Thus, {@link 911 android.view.ActionProvider#onPerformDefaultAction()} is never called when there is a 912 submenu.</p> 913 <p class="note"><strong>Note:</strong> An activity or a fragment that implements {@link 914 android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} can override the action 915 provider's default behavior by handling the item-selected event (and returning true), in which 916 case, the system does not call {@link android.view.ActionProvider#onPerformDefaultAction()}.</p> 917 </dd> 918 </dl> 919 920 <p>For an example extension of {@link android.view.ActionProvider}, see <a 921 href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/ActionBarSettingsActionProviderActivity.html" 922 >ActionBarSettingsActionProviderActivity</a>.</p> 923 924 925 926 927 <h2 id="Tabs">Adding Navigation Tabs</h2> 928 929 930 <div class="figure" style="width:450px"> 931 <img src="{@docRoot}images/ui/actionbar.png" alt="" /> 932 <p class="img-caption"><strong>Figure 9.</strong> Screenshot of action bar tabs from the <a 933 href="{@docRoot}resources/samples/HoneycombGallery/index.html">Honeycomb Gallery</a> app.</p> 934 </div> 935 936 <div class="figure" style="width:250px"> 937 <img src="{@docRoot}images/ui/actionbar-stacked.png" alt="" /> 938 <p class="img-caption"><strong>Figure 10.</strong> Screenshot of tabs in the stacked action 939 bar on a narrow screen.</p> 940 </div> 941 942 <p>When you want to provide navigation tabs in an activity, using the action bar's 943 tabs is a great option (instead of using {@link android.widget.TabWidget}), because the 944 system adapts the action bar tabs for different screen sizes—placing them in the main action 945 bar when the screen is sufficiently wide, or in a separate bar (known as the "stacked action bar") 946 when the screen is too narrow, as shown in figures 9 and 10.</p> 947 948 <p>To switch between fragments using the tabs, you must perform a fragment 949 transaction each time a tab is selected. If you're not familiar with how to change fragments 950 using {@link android.app.FragmentTransaction}, first read the <a 951 href="{@docRoot}guide/components/fragments.html">Fragments</a> developer guide.</p> 952 953 <p>To get started, your layout must include a {@link android.view.ViewGroup} in which you place each 954 {@link android.app.Fragment} associated with a tab. Be sure the {@link android.view.ViewGroup} has a 955 resource ID so you can reference it from your tab-swapping code. Alternatively, if the tab content 956 will fill the activity layout (excluding the action bar), then your activity doesn't need a layout 957 at all (you don't even need to call {@link android.app.Activity#setContentView 958 setContentView()}). Instead, you can place each fragment in the default root {@link 959 android.view.ViewGroup}, which you can refer to with the {@code android.R.id.content} ID (you can 960 see this ID used in the sample code below, during fragment transactions).</p> 961 962 <p>Once you determine where the fragments appear in the layout, the basic procedure to add tabs 963 is:</p> 964 <ol> 965 <li>Implement the {@link android.app.ActionBar.TabListener} interface. Callbacks in this 966 interface respond to user events on the tabs so you can swap fragments.</li> 967 <li>For each tab you want to add, instantiate an {@link android.app.ActionBar.Tab} and set the 968 {@link android.app.ActionBar.TabListener} by calling {@link android.app.ActionBar.Tab#setTabListener 969 setTabListener()}. Also set the tab's title and/or icon with {@link 970 android.app.ActionBar.Tab#setText setText()} and/or {@link android.app.ActionBar.Tab#setIcon 971 setIcon()}.</li> 972 <li>Add each tab to the action bar by calling {@link android.app.ActionBar#addTab addTab()}.</li> 973 </ol> 974 975 <p>When looking at the {@link android.app.ActionBar.TabListener} interface, notice that the 976 callback methods provide only the {@link android.app.ActionBar.Tab} that was selected and a {@link 977 android.app.FragmentTransaction} for you to perform fragment transactions—it doesn't say 978 anything about what fragment you should swap in or out. Thus, you must define your own association 979 between each {@link android.app.ActionBar.Tab} and the appropriate {@link android.app.Fragment} that 980 it represents (in order to perform the appropriate fragment transaction). There are several ways you 981 can define the association, depending on your design. In the example below, the {@link 982 android.app.ActionBar.TabListener} implementation provides a constructor such that each new tab uses 983 its own instance of the listener. Each instance of the listener defines several fields that are 984 necessary to later perform a transaction on the appropriate fragment.</p> 985 986 <p>For example, here's how you might implement the {@link android.app.ActionBar.TabListener} 987 such that each tab uses its own instance of the listener:</p> 988 <pre> 989 public static class TabListener<T extends Fragment> implements ActionBar.TabListener { 990 private Fragment mFragment; 991 private final Activity mActivity; 992 private final String mTag; 993 private final Class<T> mClass; 994 995 /** Constructor used each time a new tab is created. 996 * @param activity The host Activity, used to instantiate the fragment 997 * @param tag The identifier tag for the fragment 998 * @param clz The fragment's Class, used to instantiate the fragment 999 */ 1000 public TabListener(Activity activity, String tag, Class<T> clz) { 1001 mActivity = activity; 1002 mTag = tag; 1003 mClass = clz; 1004 } 1005 1006 /* The following are each of the {@link android.app.ActionBar.TabListener} callbacks */ 1007 1008 public void onTabSelected(Tab tab, FragmentTransaction ft) { 1009 // Check if the fragment is already initialized 1010 if (mFragment == null) { 1011 // If not, instantiate and add it to the activity 1012 mFragment = Fragment.instantiate(mActivity, mClass.getName()); 1013 ft.add(android.R.id.content, mFragment, mTag); 1014 } else { 1015 // If it exists, simply attach it in order to show it 1016 ft.attach(mFragment); 1017 } 1018 } 1019 1020 public void onTabUnselected(Tab tab, FragmentTransaction ft) { 1021 if (mFragment != null) { 1022 // Detach the fragment, because another one is being attached 1023 ft.detach(mFragment); 1024 } 1025 } 1026 1027 public void onTabReselected(Tab tab, FragmentTransaction ft) { 1028 // User selected the already selected tab. Usually do nothing. 1029 } 1030 } 1031 </pre> 1032 1033 <p class="caution"><strong>Caution:</strong> You <strong>must not</strong> call {@link 1034 android.app.FragmentTransaction#commit} for the fragment transaction in each of these 1035 callbacks—the system calls it for you and it may throw an exception if you call it yourself. 1036 You also <strong>cannot</strong> add these fragment transactions to the back stack.</p> 1037 1038 <p>In this example, the listener simply attaches ({@link android.app.FragmentTransaction#attach 1039 attach()}) a fragment to the activity layout—or if not instantiated, creates the fragment and 1040 adds ({@link android.app.FragmentTransaction#add add()}) it to the layout (as a child of the {@code 1041 android.R.id.content} view group)—when the respective tab is selected, and detaches ({@link 1042 android.app.FragmentTransaction#detach detach()}) it when the tab is unselected.</p> 1043 1044 <p>The {@link android.app.ActionBar.TabListener} implementation is the bulk of the work. All that 1045 remains is to create each {@link android.app.ActionBar.Tab} and add it to the {@link 1046 android.app.ActionBar}. Additionally, you must call {@link 1047 android.app.ActionBar#setNavigationMode(int) setNavigationMode(NAVIGATION_MODE_TABS)} to make the 1048 tabs visible. You might also want to disable the activity title by calling {@link 1049 android.app.ActionBar#setDisplayShowTitleEnabled setDisplayShowTitleEnabled(false)} if the tab 1050 titles actually indicate the current view.</p> 1051 1052 <p>For example, the following code adds two tabs using the listener defined above:</p> 1053 1054 <pre> 1055 @Override 1056 protected void onCreate(Bundle savedInstanceState) { 1057 super.onCreate(savedInstanceState); 1058 // Notice that setContentView() is not used, because we use the root 1059 // android.R.id.content as the container for each fragment 1060 1061 // setup action bar for tabs 1062 ActionBar actionBar = getActionBar(); 1063 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); 1064 actionBar.setDisplayShowTitleEnabled(false); 1065 1066 Tab tab = actionBar.newTab() 1067 .setText(R.string.artist) 1068 .setTabListener(new TabListener<ArtistFragment>( 1069 this, "artist", ArtistFragment.class)); 1070 actionBar.addTab(tab); 1071 1072 tab = actionBar.newTab() 1073 .setText(R.string.album) 1074 .setTabListener(new TabListener<AlbumFragment>( 1075 this, "album", AlbumFragment.class)); 1076 actionBar.addTab(tab); 1077 } 1078 </pre> 1079 1080 <p class="note"><strong>Note:</strong> The above implementation for {@link 1081 android.app.ActionBar.TabListener} is one of several possible techniques. You can see more of 1082 this style in the <a 1083 href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/FragmentTabs.html" 1084 >API Demos</a> app.</p> 1085 1086 1087 <p>If your activity stops, you should retain the currently selected tab with the <a 1088 href="{@docRoot}guide/components/activities.html#SavingActivityState">saved instance 1089 state</a> so you can open the appropriate tab when the user returns. When it's time to save the 1090 state, you can query the currently selected tab with {@link 1091 android.app.ActionBar#getSelectedNavigationIndex()}. This returns the index position of the selected 1092 tab.</p> 1093 1094 <p class="caution"><strong>Caution:</strong> It's important that you save the state of each fragment 1095 as necessary, so that when users switch fragments with the tabs and then return to a previous 1096 fragment, it looks the way it did when they left. For information about saving the state of your 1097 fragment, see the <a href="{@docRoot}guide/components/fragments.html">Fragments</a> 1098 developer guide.</p> 1099 1100 1101 <p class="note"><strong>Note:</strong> In some cases, the Android system will show your action 1102 bar tabs as a drop-down list in order to ensure the best fit in the action bar.</p> 1103 1104 1105 <h2 id="Dropdown">Adding Drop-down Navigation</h2> 1106 1107 <p>As another mode of navigation (or filtering) within your activity, the action bar offers a 1108 built in drop-down list. For example, the drop-down list can offer different modes by which content 1109 in the activity is sorted.</p> 1110 1111 <!-- 1112 <div class="figure" style="width:135px"> 1113 <img src="{@docRoot}images/ui/actionbar-dropdown.png" alt="" /> 1114 <p class="img-caption"><strong>Figure 5.</strong> Screenshot of a drop-down navigation list in the 1115 action bar.</p> 1116 </div> 1117 --> 1118 1119 <p>The basic procedure to enable drop-down navigation is:</p> 1120 1121 <ol> 1122 <li>Create a {@link android.widget.SpinnerAdapter} that provides the 1123 list of selectable items for the drop-down and the layout to use when drawing each item in the 1124 list.</li> 1125 <li>Implement {@link android.app.ActionBar.OnNavigationListener} to define the behavior that 1126 occurs when the user selects an item from the list.</li> 1127 <li>Enable navigation mode for the action bar with {@link 1128 android.app.ActionBar#setNavigationMode setNavigationMode()}. For example: 1129 <pre> 1130 ActionBar actionBar = getActionBar(); 1131 actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); 1132 </pre> 1133 <p class="note"><strong>Note:</strong> You should perform this during your activity's {@link 1134 android.app.Activity#onCreate 1135 onCreate()} method.</p> 1136 </li> 1137 <li>Set the callback for the drop-down list with {@link 1138 android.app.ActionBar#setListNavigationCallbacks setListNavigationCallbacks()}. For example: 1139 <pre> 1140 actionBar.setListNavigationCallbacks(mSpinnerAdapter, mNavigationCallback); 1141 </pre> 1142 <p>This method takes your {@link android.widget.SpinnerAdapter} and {@link 1143 android.app.ActionBar.OnNavigationListener}.</p> 1144 </li> 1145 </ol> 1146 1147 <p>That's the basic setup. However, implementing the {@link android.widget.SpinnerAdapter} and 1148 {@link android.app.ActionBar.OnNavigationListener} is where most of the work is done. There are many 1149 ways you can implement these to define the functionality for your drop-down navigation and 1150 implementing various types of {@link android.widget.SpinnerAdapter} is beyond the scope of this 1151 document (you should refer to the {@link android.widget.SpinnerAdapter} class reference for more 1152 information). However, below is a simple example for a {@link android.widget.SpinnerAdapter} and 1153 {@link android.app.ActionBar.OnNavigationListener} to get you started (click the title to 1154 reveal the sample).</p> 1155 1156 1157 1158 <div class="toggle-content closed"> 1159 1160 <h3 id="Spinner"><a href="#" onclick="return toggleContent(this)"> 1161 <img src="{@docRoot}assets/images/triangle-closed.png" class="toggle-content-img" alt="" /> 1162 Example SpinnerAdapter and OnNavigationListener 1163 </a></h3> 1164 1165 <div class="toggle-content-toggleme"> 1166 1167 <p>{@link android.widget.SpinnerAdapter} is an adapter that provides data for a spinner widget, 1168 such as the drop-down list in the action bar. {@link android.widget.SpinnerAdapter} is an interface 1169 that you can implement, but Android includes some useful implementations that you can extend, such 1170 as {@link android.widget.ArrayAdapter} and {@link 1171 android.widget.SimpleCursorAdapter}. For example, here's an easy way to create a {@link 1172 android.widget.SpinnerAdapter} by using {@link android.widget.ArrayAdapter} implementation, which 1173 uses a string array as the data source:</p> 1174 1175 <pre> 1176 SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.action_list, 1177 android.R.layout.simple_spinner_dropdown_item); 1178 </pre> 1179 1180 <p>The {@link android.widget.ArrayAdapter#createFromResource createFromResource()} method takes 1181 three parameters: the application {@link android.content.Context}, the resource ID for the string 1182 array, and the layout to use for each list item.</p> 1183 1184 <p>A <a href="{@docRoot}guide/topics/resources/string-resource.html#StringArray">string array</a> 1185 defined in a resource looks like this:</p> 1186 1187 <pre> 1188 <?xml version="1.0" encoding="utf-8"?> 1189 <resources> 1190 <string-array name="action_list"> 1191 <item>Mercury</item> 1192 <item>Venus</item> 1193 <item>Earth</item> 1194 </string-array> 1195 </pre> 1196 </pre> 1197 1198 <p>The {@link android.widget.ArrayAdapter} returned by {@link 1199 android.widget.ArrayAdapter#createFromResource createFromResource()} is complete and ready for you 1200 to pass it to {@link android.app.ActionBar#setListNavigationCallbacks setListNavigationCallbacks()} 1201 (in step 4 from above). Before you do, though, you need to create the {@link 1202 android.app.ActionBar.OnNavigationListener OnNavigationListener}.</p> 1203 1204 1205 <p>Your implementation of {@link android.app.ActionBar.OnNavigationListener} is where you handle 1206 fragment changes or other modifications to your activity when the user selects an item from the 1207 drop-down list. There's only one callback method to implement in the listener: {@link 1208 android.app.ActionBar.OnNavigationListener#onNavigationItemSelected onNavigationItemSelected()}.</p> 1209 1210 <p>The {@link 1211 android.app.ActionBar.OnNavigationListener#onNavigationItemSelected onNavigationItemSelected()} 1212 method receives the position of the item in the list and a unique item ID provided by the {@link 1213 android.widget.SpinnerAdapter}.</p> 1214 1215 <p>Here's an example that instantiates an anonymous implementation of {@link 1216 android.app.ActionBar.OnNavigationListener OnNavigationListener}, which inserts a {@link 1217 android.app.Fragment} into the 1218 layout container identified by {@code R.id.fragment_container}:</p> 1219 1220 <pre> 1221 mOnNavigationListener = new OnNavigationListener() { 1222 // Get the same strings provided for the drop-down's ArrayAdapter 1223 String[] strings = getResources().getStringArray(R.array.action_list); 1224 1225 @Override 1226 public boolean onNavigationItemSelected(int position, long itemId) { 1227 // Create new fragment from our own Fragment class 1228 ListContentFragment newFragment = new ListContentFragment(); 1229 FragmentTransaction ft = openFragmentTransaction(); 1230 // Replace whatever is in the fragment container with this fragment 1231 // and give the fragment a tag name equal to the string at the position selected 1232 ft.replace(R.id.fragment_container, newFragment, strings[position]); 1233 // Apply changes 1234 ft.commit(); 1235 return true; 1236 } 1237 }; 1238 </pre> 1239 1240 <p>This instance of {@link android.app.ActionBar.OnNavigationListener OnNavigationListener} is 1241 complete and you can now call {@link android.app.ActionBar#setListNavigationCallbacks 1242 setListNavigationCallbacks()} (in step 4), passing the {@link android.widget.ArrayAdapter} and this 1243 {@link android.app.ActionBar.OnNavigationListener OnNavigationListener}.</p> 1244 1245 <p>In this example, when the user selects an item from the drop-down list, a fragment is added to 1246 the layout (replacing the current fragment in the {@code R.id.fragment_container} view). The 1247 fragment added is given a tag that uniquely identifies it, which is the same string used to 1248 identify the fragment in the drop-down list.</p> 1249 1250 <p>Here's a look at the {@code ListContentFragment} class that defines each fragment in this 1251 example:</p> 1252 1253 <pre> 1254 public class ListContentFragment extends Fragment { 1255 private String mText; 1256 1257 @Override 1258 public void onAttach(Activity activity) { 1259 // This is the first callback received; here we can set the text for 1260 // the fragment as defined by the tag specified during the fragment transaction 1261 super.onAttach(activity); 1262 mText = getTag(); 1263 } 1264 1265 @Override 1266 public View onCreateView(LayoutInflater inflater, ViewGroup container, 1267 Bundle savedInstanceState) { 1268 // This is called to define the layout for the fragment; 1269 // we just create a TextView and set its text to be the fragment tag 1270 TextView text = new TextView(getActivity()); 1271 text.setText(mText); 1272 return text; 1273 } 1274 } 1275 </pre> 1276 1277 </div><!-- end toggle-content-toggleme --> 1278 1279 </div><!-- end toggle-content --> 1280 1281 1282 1283 1284 1285 <h2 id="Style">Styling the Action Bar</h2> 1286 1287 <p>If you've implemented a custom design for the widgets in your application, you might 1288 also want to redesign some of the action bar to match your app design. To do so, you need to use 1289 Android's <a 1290 href="{@docRoot}guide/topics/ui/themes.html">style and theme</a> framework to restyle the action 1291 bar using special style properties.</p> 1292 1293 1294 <p class="note"><strong>Note:</strong> In order for background images to change appearance 1295 depending on the current button state (selected, pressed, unselected), the drawable resource you use 1296 must be a <a href="{@docRoot}guide/topics/resources/drawable-resource.html#StateList">state 1297 list drawable</a>.</p> 1298 1299 <p class="caution"><strong>Caution:</strong> For all background drawables you provide, be sure to use <a 1300 href="{@docRoot}guide/topics/graphics/2d-graphics.html#nine-patch">Nine-Patch drawables</a> to allow 1301 stretching. The Nine-Patch image should be <em>smaller</em> than 40px tall and 30px wide (for the mdpi asset).</p> 1302 1303 1304 <h3 id="GeneralStyles">General appearance</h3> 1305 1306 <dl> 1307 1308 <dt>{@link android.R.attr#windowActionBarOverlay 1309 android:windowActionBarOverlay}</dt> 1310 <dd>Declares whether the action bar should overlay the activity layout rather than offset the 1311 activity's layout position (for example, the Gallery app uses overlay mode). This is 1312 {@code false} by default. 1313 <p>Normally, the action bar requires its own space on the screen and your activity layout fills in 1314 what's left over. When the action bar is in overlay mode, your activity layout uses all the 1315 available space and the system draws the action bar on top. Overlay mode can be useful if you want 1316 your content to keep a fixed size and position when the action bar is hidden and shown. You might 1317 also like to use it purely as a visual effect, because you can use a semi-transparent background 1318 for the action bar so the user can still see some of your activity layout behind the action 1319 bar.</p> 1320 <p class="note"><strong>Note:</strong> The {@link android.R.style#Theme_Holo Holo} theme families 1321 draw the action bar with a semi-transparent background by default. However, you can modify it with 1322 your own styles and the {@link android.R.style#Theme_DeviceDefault DeviceDefault} theme on 1323 different devices might use an opaque background by default.</p> 1324 <p>When overlay mode is enabled, your activity layout has no awareness of the action bar laying on 1325 top of it. So, you must be careful not to place any important information or UI components in the 1326 area overlayed by the action bar. If appropriate, you can refer to the platform's value for {@link 1327 android.R.attr#actionBarSize} to determine the height of the action bar, by referencing it 1328 in your XML layout. For example:</p> 1329 <pre> 1330 <SomeView 1331 ... 1332 android:layout_marginTop="?android:attr/actionBarSize" /> 1333 </pre> 1334 <p>You can also retrieve the action bar height at runtime with {@link 1335 android.app.ActionBar#getHeight()}. This reflects the height of the action bar at the time it's 1336 called, which might not include the stacked action bar (due to navigation tabs) if called during early 1337 activity lifecycle methods. To see how you can determine the total height at runtime, including the 1338 stacked action bar, see the <a 1339 href="{@docRoot}resources/samples/HoneycombGallery/src/com/example/android/hcgallery/TitlesFragment.html" 1340 >{@code TitlesFragment}</a> class in the <a 1341 href="{@docRoot}resources/samples/HoneycombGallery/index.html" 1342 >Honeycomb Gallery</a> sample app.</p> 1343 </dd> 1344 1345 </dl> 1346 1347 1348 <h3 id="ActionItemStyles">Action items</h3> 1349 1350 <dl> 1351 <dt>{@link android.R.attr#actionButtonStyle 1352 android:actionButtonStyle}</dt> 1353 <dd>Defines a style resource for the action item buttons.</dd> 1354 1355 <dt>{@link android.R.attr#actionBarItemBackground 1356 android:actionBarItemBackground}</dt> 1357 <dd>Defines a drawable resource for each action item's background. (Added in API level 14.)</dd> 1358 1359 <dt>{@link android.R.attr#itemBackground 1360 android:itemBackground}</dt> 1361 <dd>Defines a drawable resource for each overflow menu item's background.</dd> 1362 1363 <dt>{@link android.R.attr#actionBarDivider 1364 android:actionBarDivider}</dt> 1365 <dd>Defines a drawable resource for the divider between action items. (Added in API level 1366 14.)</dd> 1367 1368 <dt>{@link android.R.attr#actionMenuTextColor 1369 android:actionMenuTextColor}</dt> 1370 <dd>Defines a color for text that appears in an action item.</dd> 1371 1372 <dt>{@link android.R.attr#actionMenuTextAppearance 1373 android:actionMenuTextAppearance}</dt> 1374 <dd>Defines a style resource for text that appears in an action item.</dd> 1375 1376 <dt>{@link android.R.attr#actionBarWidgetTheme 1377 android:actionBarWidgetTheme}</dt> 1378 <dd>Defines a theme resource for widgets that are inflated into the action bar as <a 1379 href="#ActionView">action views</a>. (Added in API level 14.)</dd> 1380 </dl> 1381 1382 1383 <h3 id="NavigationStyles">Navigation tabs</h3> 1384 1385 <dl> 1386 <dt>{@link android.R.attr#actionBarTabStyle 1387 android:actionBarTabStyle}</dt> 1388 <dd>Defines a style resource for tabs in the action bar.</dd> 1389 1390 <dt>{@link android.R.attr#actionBarTabBarStyle 1391 android:actionBarTabBarStyle}</dt> 1392 <dd>Defines a style resource for the thin bar that appears below the navigation tabs.</dd> 1393 1394 <dt>{@link android.R.attr#actionBarTabTextStyle 1395 android:actionBarTabTextStyle}</dt> 1396 <dd>Defines a style resource for text in the navigation tabs.</dd> 1397 </dl> 1398 1399 1400 <h3 id="DropDownStyles">Drop-down lists</h3> 1401 1402 <dl> 1403 <dt>{@link android.R.attr#actionDropDownStyle 1404 android:actionDropDownStyle}</dt> 1405 <dd>Defines a style for the drop-down navigation (such as the background and text styles).</dd> 1406 </dl> 1407 1408 1409 1410 <p>For example, here's a file that defines a few custom styles for the action bar:</p> 1411 1412 <pre> 1413 <?xml version="1.0" encoding="utf-8"?> 1414 <resources> 1415 <!-- the theme applied to the application or activity --> 1416 <style name="CustomActivityTheme" parent="@android:style/Theme.Holo"> 1417 <item name="android:actionBarTabTextStyle">@style/CustomTabTextStyle</item> 1418 <item name="android:actionBarDivider">@drawable/ab_divider</item> 1419 <item name="android:actionBarItemBackground">@drawable/ab_item_background</item> 1420 </style> 1421 1422 <!-- style for the action bar tab text --> 1423 <style name="CustomTabTextStyle" parent="@android:style/TextAppearance.Holo"> 1424 <item name="android:textColor">#2456c2</item> 1425 </style> 1426 </resources> 1427 </pre> 1428 1429 <p class="note"><strong>Note:</strong> Be certain that your theme declares a parent theme in the 1430 {@code <style>} tag, from which it inherits all styles not explicitly declared by your theme. 1431 When modifying the action bar, using a parent theme is important so that you can simply override the 1432 action bar styles you want to change without re-implementing the styles you want to leave alone 1433 (such as text appearance or padding in action items).</p> 1434 1435 <p>You can apply your custom theme to the entire application or to individual activities in your 1436 manifest file like this:</p> 1437 1438 <pre> 1439 <application android:theme="@style/CustomActivityTheme" ... /> 1440 </pre> 1441 1442 <p>For more information about using style and theme resources in your application, read <a 1443 href="{@docRoot}guide/topics/ui/themes.html">Styles and Themes</a>.</p> 1444 1445 1446 <h3 id="AdvancedStyles">Advanced styling</h3> 1447 1448 <p>If you need more advanced styling for the action bar than is available with the 1449 properties above, you can include {@link android.R.attr#actionBarStyle android:actionBarStyle} and 1450 {@link android.R.attr#actionBarSplitStyle android:actionBarSplitStyle} in your activity's theme. 1451 Each of these specifies another style that can define various properties for the action bar, 1452 including different backgrounds with {@link android.R.attr#background android:background}, {@link 1453 android.R.attr#backgroundSplit android:backgroundSplit}, and {@link android.R.attr#backgroundStacked 1454 android:backgroundStacked}. If you override these action bar styles, be sure that you define a 1455 parent action bar style such as {@link android.R.style#Widget_Holo_ActionBar 1456 Widget.Holo.ActionBar}.</p> 1457 1458 <p>For example, if you want to change the action bar's background, you can use the following 1459 styles:</p> 1460 1461 <pre> 1462 <?xml version="1.0" encoding="utf-8"?> 1463 <resources> 1464 <!-- the theme applied to the application or activity --> 1465 <style name="CustomActivityTheme" parent="@android:style/Theme.Holo"> 1466 <item name="android:actionBarStyle">@style/MyActionBar</item> 1467 <!-- other activity and action bar styles here --> 1468 </style> 1469 1470 <!-- style for the action bar backgrounds --> 1471 <style name="MyActionBar" parent="@android:style/Widget.Holo.ActionBar"> 1472 <item name="android:background">@drawable/ab_background</item> 1473 <item name="android:backgroundStacked">@drawable/ab_background</item> 1474 <item name="android:backgroundSplit">@drawable/ab_split_background</item> 1475 </style> 1476 </resources> 1477 </pre> 1478 1479 1480 1481 1482 1483