• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1page.title=Action Bar
2parent.title=User Interface
3parent.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
61href="{@docRoot}resources/samples/HoneycombGallery/index.html">Honeycomb Gallery</a></li>
62    <li><a
63href="{@docRoot}resources/samples/ActionBarCompat/index.html">Action Bar Compatibility</a></li>
64    <li><a
65href="{@docRoot}resources/samples/ApiDemos/src/com/example/android/apis/app/index.html#ActionBar">
66API Demos</a></li>
67  </ol>
68
69  <h2>See also</h2>
70  <ol>
71    <li><a
72href="{@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
75and 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
81provides user actions and navigation modes. You should use the action bar in most activities that
82need to prominently present user actions or global navigation, because the action bar offers users a
83consistent interface across applications and the system gracefully adapts the action bar's
84appearance for different screen configurations. You can control the behaviors and visibility of the
85action bar with the {@link android.app.ActionBar} APIs, which were added in Android 3.0 (API level
8611).</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.
93You might choose to remove the activity title, however, if the current view is identified by a
94navigation 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
98href="{@docRoot}guide/components/fragments.html">fragments</a>. It also offers a drop-down
99list you can use as an alternative navigation mode or to refine the current view (such as to sort
100a list by different criteria).</p>
101  </li>
102
103  <li>Make key actions for the activity (such as "search", "create", "share", etc.) prominent and
104accessible to the user in a predictable way.
105    <p>You can provide instant access to key user actions by placing items from the <a
106href="{@docRoot}guide/topics/ui/menus.html#OptionsMenu">options menu</a> directly in the action bar,
107as "action items." Action items can also provide an "action view," which provides an embedded
108widget for even more immediate action behaviors. Menu items that are not promoted
109to an action item are available in the overflow menu, revealed by either the device <em>Menu</em>
110button
111(when available) or by an "overflow menu" button in the action bar (when the device does not
112include 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
118href="{@docRoot}resources/samples/HoneycombGallery/index.html">Honeycomb Gallery</a> app (on a
119landscape handset), showing the logo on the left, navigation tabs, and an action item on the
120right (plus the overflow menu button).</p>
121
122<p class="note"><strong>Note:</strong> If you're looking for information about the contextual
123action bar for displaying contextual action items, see the <a
124href="{@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
130href="{@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
139versions of Android older than 3.0, you need to create the action bar in your
140activity's layout (because the {@link android.app.ActionBar} class is not available on older
141versions).</p>
142<p>To help you, the <a
143href="{@docRoot}resources/samples/ActionBarCompat/index.html">Action Bar Compatibility</a> sample
144app provides an API layer and action bar layout that allows your app to use some of the {@link
145android.app.ActionBar} APIs and also support older versions of Android by replacing the traditional
146title 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
154activities that use the {@link android.R.style#Theme_Holo Theme.Holo} theme (or one of its
155descendants), which is the default theme when either the <a
156href="{@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>
158attribute is set to {@code "11"} or greater. For example:</p>
159
160<pre>
161&lt;manifest ... &gt;
162    &lt;uses-sdk android:minSdkVersion="4"
163              <b>android:targetSdkVersion="11"</b> /&gt;
164    ...
165&lt;/manifest&gt;
166</pre>
167
168<p>In this example, the application requires a minimum version of API Level 4 (Android 1.6), but it
169also targets API level 11 (Android 3.0). This way, when the application runs on Android 3.0 or
170greater, the system applies the holographic theme to each activity, and thus, each activity includes
171the action bar.</p>
172
173<p>If you want to use {@link android.app.ActionBar} APIs, such as to add navigation modes and modify
174action bar styles, you should set the <a
175href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a> to {@code
176"11"} or greater. If you want your app
177to support older versions of Android, there are ways to use a limited set of {@link
178android.app.ActionBar} APIs on devices that support API level 11 or higher, while still running
179on 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&lt;activity android:theme="&#64;android:style/Theme.Holo.NoActionBar"&gt;
189</pre>
190
191<p>You can also hide the action bar at runtime by calling {@link android.app.ActionBar#hide}. For
192example:</p>
193
194<pre>
195ActionBar actionBar = {@link android.app.Activity#getActionBar()};
196actionBar.hide();
197</pre>
198
199<p>When the action bar hides, the system adjusts your activity layout to fill all the
200screen space now available. You can bring the action bar back with {@link
201android.app.ActionBar#show()}.</p>
202
203<p>Beware that hiding and removing the action bar causes your activity to re-layout in order to
204account for the space consumed by the action bar. If your activity regularly hides and shows the
205action bar (such as in the Android Gallery app), you might want to use overlay mode. Overlay mode
206draws the action bar on top of your activity layout rather than in its own area of the screen. This
207way, your layout remains fixed when the action bar hides and re-appears. To enable overlay mode,
208create a theme for your activity and set {@link android.R.attr#windowActionBarOverlay
209android:windowActionBarOverlay} to {@code true}. For more information, see the section about <a
210href="#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
213remove the action bar, set the {@link android.R.styleable#Theme_windowActionBar
214android:windowActionBar} style property to {@code false}. However, if you remove the action bar
215using a theme, then the window will not allow the action bar at all, so you cannot add it
216later&mdash;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
223href="{@docRoot}guide/topics/ui/menus.html#OptionsMenu">options menu</a>. To do this, you can
224declare that the menu item should appear in the action bar as an "action item." An action item can
225include an icon and/or a text title. If a menu item does not appear as an action item, then the
226system places it in the overflow menu. The overflow menu is revealed either by the device
227<em>Menu</em>
228button (if provided by the device) or an additional button in the action bar (if the device does not
229provide 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
234the 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
239discussed in the <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide, it's in
240this callback method that you should inflate an XML <a
241href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a> that defines the
242menu items. For example:</p>
243
244<pre>
245&#64;Override
246public 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
254android:showAsAction="ifRoom"} for the {@code &lt;item&gt;} element. This way, the menu item appears
255in the action bar for quick access only <em>if there is room</em> available. If there's not
256enough room, the item appears in the overflow menu.</p>
257
258<p>If your menu item supplies both a title and an icon&mdash;with the {@code android:title} and
259{@code android:icon} attributes&mdash;then the action item shows only the icon by default. If you
260want to display the text title, add {@code "withText"} to the {@code android:showAsAction}
261attribute. For example:</p>
262
263<pre>
264&lt;?xml version="1.0" encoding="utf-8"?&gt;
265&lt;menu xmlns:android="http://schemas.android.com/apk/res/android">
266    &lt;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> /&gt;
270&lt;/menu&gt;
271</pre>
272
273<p class="note"><strong>Note:</strong> The {@code "withText"} value is a <em>hint</em> to the
274action bar that the text title should appear. The action bar will show the title when possible, but
275might 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)
279onOptionsItemSelected()}, passing the ID supplied by the {@code android:id} attribute&mdash;the same
280callback 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&mdash;even if you
283don't declare that the title appear with the action item&mdash;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
286in 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
289tool-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,
293see the <a href="{@docRoot}guide/practices/ui_guidelines/icon_design_action_bar.html">Action Bar
294Icon</a> design guidelines.</p>
295
296<p class="note"><strong>Note:</strong> If you added the menu item from a fragment, via the {@link
297android.app.Fragment} class's {@link android.app.Fragment#onCreateOptionsMenu onCreateOptionsMenu}
298callback, then the system calls the respective {@link
299android.app.Fragment#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} method for that
300fragment when the user selects one of the fragment's items. However the activity gets a chance to
301handle the event first, so the system calls {@link
302android.app.Activity#onOptionsItemSelected(MenuItem) onOptionsItemSelected()} on the activity before
303calling 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
306placed in the overflow menu when space is limited. In most cases, you <strong>should not</strong>
307force an item to appear in the action bar by using the {@code "always"} value. However, you might
308need an item to always appear when it provides an <a href="#ActionView">action view</a> that does
309not offer a default action for the overflow menu. Beware that too
310many action items can create a cluttered UI and cause layout problems on devices with a narrow
311screen. It's best to instead use {@code "ifRoom"} to request that an item appear in the action
312bar, 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
315href="{@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
325href="{@docRoot}guide/topics/ui/menus.html#OptionsMenu">options menu</a> (let alone action items)
326should have a global impact on the app, rather than affect only a small portion of the interface.
327For example, if you have a multi-pane layout and one pane shows a video while another lists all
328videos, the video player controls should appear within the pane containing the video (not in the
329action bar), while the action bar might provide action items to share the video or save the video to
330a favorites list.</p>
331  <p>So, even before deciding whether a menu item should appear as an action item, be sure that
332the item has a global scope for the current activity. If it doesn't, then you should place it
333as 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
338assessing a few key traits. In general, each action item should be <em>at least one</em>
339of 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
343or 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
349not frequently used, it's important that it be effortless to perform in the few cases that users do
350need it.
351    <p>Example important actions: "Add network" in Wi-Fi settings and "Switch to camera" in the
352Gallery app.</p>
353  </li>
354
355  <li><strong>Typical</strong>: It's an action that is typically provided in the action bar in
356similar 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
358People 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
362should carefully consider their relative level of importance and try to set no more than four as
363action items (and do so using the {@code "ifRoom"} value to allow the system to put some back in the
364overflow menu when space is limited on smaller screens). Even if space is available on a wide
365screen, you should not create a long stream of action items that clutter the UI and appear like a
366desktop 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,
369Feedback, 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
372button for Search, so if it's an important feature in your app, it should always appear as an
373action item (and usually as the first item, especially if you offer it with an <a
374href="#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
381available for the action bar called "split action bar." When you enable split action bar, a separate
382bar appears at the bottom of the screen to display all action items when the activity is running on
383a narrow screen (such as a portrait-oriented handset). Splitting the action bar to separate
384the action items ensures that a reasonable amount of space is available to display all your action
385items 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 &lt;activity&gt;}</a> or
389<a href="{@docRoot}guide/topics/manifest/application-element.html">{@code &lt;application&gt;}</a>
390manifest element.</p>
391
392<p>Be aware that Android adjusts the action bar's appearance in a variety of ways, based on the
393current screen size. Using split action bar is just one option that you can enable to allow the
394action bar to further optimize the user experience for different screen sizes. In doing so, you
395may also allow the action bar to collapse navigation tabs into the main action bar. That is, if you
396use <a href="#Tabs">navigation tabs</a> in your action bar, once the action items are
397separated on a narrow screen, the navigation tabs may be able to fit into the main action bar rather
398than be separated into the "stacked action bar." Specifically, if you've disabled the action bar
399icon and title (with {@link android.app.ActionBar#setDisplayShowHomeEnabled
400setDisplayShowHomeEnabled(false)} and {@link android.app.ActionBar#setDisplayShowTitleEnabled
401setDisplayShowTitleEnabled(false)}), then the navigation tabs collapse into the main action bar, as
402shown 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
406on 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
409android:uiOptions} attribute was added in Android 4.0 (API level 14), you can safely include it in
410your application even if your <a
411href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a> is set to
412a value lower than {@code "14"} to remain compatible with older versions of Android. When running on
413older versions, the system simply ignores the XML attribute because it doesn't understand it. The
414only condition to including it in your manifest is that you must compile your application against a
415platform version that supports API level 14 or higher. Just be sure that you don't openly use other
416APIs in your application code that aren't supported by the version declared by your <a
417href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code minSdkVersion}</a>
418attribute&mdash;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
430href="{@docRoot}guide/topics/manifest/application-element.html#icon">{@code android:icon}</a>
431attribute in the <a href="{@docRoot}guide/topics/manifest/application-element.html">{@code
432&lt;application&gt;}</a> or <a
433href="{@docRoot}guide/topics/manifest/activity-element.html">{@code
434&lt;activity&gt;}</a> element. However, if you also specify the <a
435href="{@docRoot}guide/topics/manifest/application-element.html#logo">{@code android:logo}</a>
436attribute, 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
438should generally use a logo only when it represents your brand in a traditional format that users
439recognize. A good example is the YouTube app's logo&mdash;the logo represents the expected user
440brand, 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,
446you can enable the icon to behave as an action item. In response to user action on the icon, your
447application 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
455android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} method with the  {@code
456android.R.id.home} ID. In response, you should either start the home activity or
457take 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
460the {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} flag in the {@link
461android.content.Intent}. With this flag, if the activity you're starting already exists in the
462current task, then all activities on top of it are destroyed and it is brought to the front.
463Adding this flag is often important because going "home" is an action that's equivalent to "going
464back" and you should usually not create a new instance of the home activity. Otherwise, you
465might end up with a long stack of activities in the current task with multiple instances of the
466home activity.</p>
467
468<p>For example, here's an implementation of {@link android.app.Activity#onOptionsItemSelected
469onOptionsItemSelected()} that returns to the application's "home" activity:</p>
470
471<pre>
472&#64;Override
473public 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
488add the {@link android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag. This flag ensures that, when the
489user navigates either "home" or "up", the new activity is <strong>not</strong> added to the current
490task, but instead started in a task that belongs to your application. For example, if the user
491starts an activity in your application through an intent invoked by another application, then
492selects the action bar icon to navigate home or up, the {@link
493android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} flag starts the activity in a task that belongs to
494your application (not the current task). The system either starts a new task with your new activity
495as the root activity or, if an existing task exists in the background with an instance of that
496activity, then that task is brought forward and the target activity receives {@link
497android.app.Activity#onNewIntent onNewIntent()}. So if your activity accepts intents from other
498applications (it declares any generic intent filters), you should usually add the {@link
499android.content.Intent#FLAG_ACTIVITY_NEW_TASK} flag to the intent:</p>
500
501<pre>
502intent.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
506href="{@docRoot}guide/components/tasks-and-back-stack.html">Tasks and Back Stack</a>
507developer guide.</p>
508
509<p class="note"><strong>Note:</strong> If you're using the icon to navigate to the home
510activity, beware that beginning with Android 4.0 (API level 14), you must explicitly enable the
511icon as an action item by calling {@link android.app.ActionBar#setHomeButtonEnabled
512setHomeButtonEnabled(true)} (in previous versions, the icon was enabled as an action item by
513default).</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&mdash;which takes the user to the previous
526screen in the task history&mdash;you can enable the action bar icon to offer "up"
527navigation, which should take the user one step up in your application's structural hierarchy. For
528instance, if the current screen is somewhere deep in the hierarchy of the application, touching the
529app 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
532application to an activity belonging to a different application (specifically, when composing an
533email 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
537after 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,
540up navigation allows the user to navigate upward in the email application, rather than go back
541to the previous activity. Figure 6 illustrates this scenario, in which the user again comes into
542the 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
546entering 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
551href="{@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>
559protected 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
570android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} method with the {@code
571android.R.id.home} ID, as shown in the above section about <a href="#Home">Using the App Icon
572for Navigation</a>.</p>
573
574<p>Remember to use the {@link android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} flag in the {@link
575android.content.Intent}, so that you don't create a new instance of the parent activity if one
576already exists. For instance, if you don't use the {@link
577android.content.Intent#FLAG_ACTIVITY_CLEAR_TOP} flag, then after navigating up, the BACK button will
578actually take the user "forward", with respect to the application structure, which would be
579strange.</p>
580
581<p class="note"><strong>Note:</strong> If there are many paths that the user could have taken to
582reach the current activity within your application, the up icon should navigate backward along the
583path 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
593view for Search (top), then expanded action view with the <code><a
594href="/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
599button. For example, if you have an item in the options menu for "Search," you can add an action
600view that replaces the button with a {@link android.widget.SearchView} widget, as shown in figure
6017.</p>
602
603<p>To declare an action view for an item in your <a
604href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>, use either the {@code
605android:actionLayout} or {@code android:actionViewClass} attribute to specify either a layout
606resource or widget class to use, respectively. For example:</p>
607
608<pre>
609&lt;?xml version="1.0" encoding="utf-8"?>
610&lt;menu xmlns:android="http://schemas.android.com/apk/res/android">
611    &lt;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> /&gt;
616&lt;/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
621button. When the user selects the button, the action view expands. Otherwise, the action view is
622visible by default and might consume valuable action bar space even when the user is not using it.
623For more information, see the next section about <a href="#ActionViewCollapsing">Handling
624collapsible 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
627android.app.Activity#onCreateOptionsMenu onCreateOptionsMenu()} callback. You can acquire elements
628in an action view by calling {@link android.view.Menu#findItem findItem()} with the ID of the menu
629item, then call {@link android.view.MenuItem#getActionView}. For
630example, the search widget from the above sample is acquired like this:</p>
631
632<pre>
633&#64;Override
634public 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
644href="{@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
653your application supports older versions, you should
654still declare {@code "collapseActionView"} in order to better support smaller screens.
655Devices running Android 4.0 and higher will show the action view collapsed, while older versions
656work 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
658compile. Older versions of Android ignore the {@code "collapseActionView"} value because they don't
659understand it. Just be sure not to use other APIs in your source code that are not supported in the
660version declared by your <a href="{@docRoot}guide/topics/manifest/uses-sdk-element.html#min">{@code
661minSdkVersion}</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
667fragments, or replacing the action bar. However, it might not be appropriate to make an action view
668visible by default. To preserve the action bar space (especially when running on smaller screens),
669you can collapse your action view into an action item button. When the user selects the
670button, the action view appears in the action bar. When collapsed, the system might place the item
671into the overflow menu if you've defined {@code android:showAsAction} with {@code "ifRoom"}, but the
672action view still appears in the action bar when the user selects the item. You can make your action
673view collapsible by adding {@code "collapseActionView"} to the {@code android:showAsAction}
674attribute, 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
678android.app.Activity#onOptionsItemSelected onOptionsItemSelected} callback. The system still calls
679{@link android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} when the user selects it,
680but the system will always expand the action view unless you return {@code true} (indicating
681you'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
684bar 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
687android.view.MenuItem#expandActionView()} and {@link android.view.MenuItem#collapseActionView()} on
688the {@link android.view.MenuItem}.</p>
689
690<p class="note"><strong>Note:</strong> Although collapsing your action view is optional, we
691recommend that you always collapse your action view if it includes {@link
692android.widget.SearchView}. Also be aware that some devices provide a dedicated SEARCH button and
693you should expand your search action view if the user presses the SEARCH button. Simply override
694your activity's {@link android.app.Activity#onKeyUp onKeyUp()} callback method, listen for the
695{@link android.view.KeyEvent#KEYCODE_SEARCH} event, then call {@link
696android.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
699callbacks when it's expanded and collapsed by defining an {@link
700android.view.MenuItem.OnActionExpandListener OnActionExpandListener} and registering it with {@link
701android.view.MenuItem#setOnActionExpandListener setOnActionExpandListener()}. For example:</p>
702
703<pre>
704&#64;Override
705public 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        &#64;Override
712        public boolean onMenuItemActionCollapse(MenuItem item) {
713            // Do something when collapsed
714            return true;  // Return true to collapse action view
715        }
716
717        &#64;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
738android.view.ActionProvider} class) replaces an action item with a customized layout, but it also
739takes control of all the item's behaviors. When you declare an action provider for a menu
740item in the action bar, it not only controls the appearance of the item in the action bar with a
741custom layout, but also handles the default event for the menu item when it appears in the overflow
742menu. 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
745android.view.ActionProvider} that facilitates a “share" action by showing a list of available share
746targets from the action bar. Instead of using a
747traditional action item that invokes the {@link android.content.Intent#ACTION_SEND} intent, you can
748declare an instance of {@link android.widget.ShareActionProvider} to handle an action item. This
749action provider presents an action view with a drop-down list of applications that handle
750the {@link android.content.Intent#ACTION_SEND} intent, even when the menu item appears in the
751overflow menu. Hence, when you use an action provider such as this one, you don't
752have 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}
755attribute for the appropriate the {@code &lt;item&gt;} element in your <a
756href="{@docRoot}guide/topics/resources/menu-resource.html">menu resource</a>, using the
757fully-qualified class name of the action provider. For example:</p>
758
759<pre>
760&lt;?xml version="1.0" encoding="utf-8"?>
761&lt;menu xmlns:android="http://schemas.android.com/apk/res/android">
762    &lt;item android:id="@+id/menu_share"
763          android:title="@string/share"
764          android:showAsAction="ifRoom"
765          <strong>android:actionProviderClass="android.widget.ShareActionProvider"</strong> /&gt;
766    ...
767&lt;/menu>
768</pre>
769
770<p>In this example, the {@link android.widget.ShareActionProvider} is used as the action provider.
771At this point, the action provider officially takes control of the menu item and handles both
772its appearance and behavior in the action bar and its behavior in the overflow menu. You must
773still 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
776the overflow menu, your activity (or fragment) can override that behavior by
777also handling the click event from the {@link android.app.Activity#onOptionsItemSelected
778onOptionsItemSelected()} callback method. If you do not handle the event in that callback, then
779the action provider receives the {@link android.view.ActionProvider#onPerformDefaultAction()}
780callback to handle the event. However, if the action provider provides a submenu, then your
781activity will not receive the {@link android.app.Activity#onOptionsItemSelected
782onOptionsItemSelected()} callback, because the submenu is shown instead of invoking the default
783menu 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
790installed 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
792action item that invokes the {@link android.content.Intent#ACTION_SEND} intent. When
793you use {@link android.widget.ShareActionProvider} for an action item, it presents an action view
794with a drop-down list of applications that handle the {@link android.content.Intent#ACTION_SEND}
795intent (as shown in figure 8).</p>
796
797<p>All the logic for creating the submenu, populating it with share targets, and handling click
798events (including when the item appears in the overflow menu) is implemented by the {@link
799android.widget.ShareActionProvider}&mdash;the only code you need to write is to declare the action
800provider 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
803share target based on how often the user selects each one. The share targets used more frequently
804appear at the top of the drop-down list and the target used most often appears directly in the
805action bar as the default share target. By default, the ranking information is
806saved in a private file with a name specified by {@link
807android.widget.ShareActionProvider#DEFAULT_SHARE_HISTORY_FILE_NAME}. If you use the {@link
808android.widget.ShareActionProvider} or an extension of it for only one type of action, then you
809should continue to use this default history file and there's nothing you need to do. However, if you
810use {@link android.widget.ShareActionProvider} or an extension of it for multiple actions with
811semantically different meanings, then each {@link android.widget.ShareActionProvider} should specify
812its own history file in order to maintain its own history. To specify a
813different history file for the {@link android.widget.ShareActionProvider}, call {@link
814android.widget.ShareActionProvider#setShareHistoryFileName setShareHistoryFileName()} and provide
815an 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
818share targets based on frequency of use, the behavior is extensible and extensions of {@link
819android.widget.ShareActionProvider} can perform different behaviors and ranking based on the history
820file (if appropriate).</p>
821
822<p>To add {@link android.widget.ShareActionProvider}, simply define the {@code
823android:actionProviderClass} attribute with {@code "android.widget.ShareActionProvider"}, as shown
824in the XML example above. The only thing left to do is define
825the {@link android.content.Intent} you want to use for sharing. To do so, you must call {@link
826android.view.MenuItem#getActionProvider} to retrieve the {@link android.widget.ShareActionProvider}
827that's associated with a {@link android.view.MenuItem}, then call {@link
828android.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
831during the activity lifecycle, you should save the {@link android.widget.ShareActionProvider} in a
832member field and update it by calling {@link android.widget.ShareActionProvider#setShareIntent
833setShareIntent()} as necessary. For example:</p>
834
835<pre>
836private ShareActionProvider mShareActionProvider;
837...
838
839&#64;Override
840public 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
857you <em>do not</em> need to handle click events from the {@link
858android.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
869overflow menu, extending {@link android.view.ActionProvider} to define those behaviors is a good
870solution. Creating your own action provider offers you an organized and reusable component, rather
871than handling the various action item transformations and behaviors in your fragment or activity
872code. As shown in the previous section, Android provides one implementation of {@link
873android.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
876its 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
881should 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
885android.content.Context} acquired from the constructor to instantiate a {@link
886android.view.LayoutInflater} and inflate your action view layout from an XML resource, then hook
887up event listeners. For example:
888<pre>
889public 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        &#064;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
907action provider should perform a default action for the menu item.
908  <p>However, if your action provider provides a submenu, through the {@link
909android.view.ActionProvider#onPrepareSubMenu onPrepareSubMenu()} callback, then the submenu
910appears even when the menu item is in the overflow menu. Thus, {@link
911android.view.ActionProvider#onPerformDefaultAction()} is never called when there is a
912submenu.</p>
913  <p class="note"><strong>Note:</strong> An activity or a fragment that implements {@link
914android.app.Activity#onOptionsItemSelected onOptionsItemSelected()} can override the action
915provider's default behavior by handling the item-selected event (and returning true), in which
916case, 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
921href="{@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
933href="{@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
939bar 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
943tabs is a great option (instead of using {@link android.widget.TabWidget}), because the
944system adapts the action bar tabs for different screen sizes&mdash;placing them in the main action
945bar when the screen is sufficiently wide, or in a separate bar (known as the "stacked action bar")
946when 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
949transaction each time a tab is selected. If you're not familiar with how to change fragments
950using {@link android.app.FragmentTransaction}, first read the <a
951href="{@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
955resource ID so you can reference it from your tab-swapping code. Alternatively, if the tab content
956will fill the activity layout (excluding the action bar), then your activity doesn't need a layout
957at all (you don't even need to call {@link android.app.Activity#setContentView
958setContentView()}). Instead, you can place each fragment in the default root {@link
959android.view.ViewGroup}, which you can refer to with the {@code android.R.id.content} ID (you can
960see 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
963is:</p>
964<ol>
965  <li>Implement the {@link android.app.ActionBar.TabListener} interface. Callbacks in this
966interface 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
969setTabListener()}. Also set the tab's title and/or icon with {@link
970android.app.ActionBar.Tab#setText setText()} and/or {@link android.app.ActionBar.Tab#setIcon
971setIcon()}.</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
976callback methods provide only the {@link android.app.ActionBar.Tab} that was selected and a {@link
977android.app.FragmentTransaction} for you to perform fragment transactions&mdash;it doesn't say
978anything about what fragment you should swap in or out. Thus, you must define your own association
979between each {@link android.app.ActionBar.Tab} and the appropriate {@link android.app.Fragment} that
980it represents (in order to perform the appropriate fragment transaction). There are several ways you
981can define the association, depending on your design. In the example below, the {@link
982android.app.ActionBar.TabListener} implementation provides a constructor such that each new tab uses
983its own instance of the listener. Each instance of the listener defines several fields that are
984necessary 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}
987such that each tab uses its own instance of the listener:</p>
988<pre>
989public static class TabListener&lt;T extends Fragment> implements ActionBar.TabListener {
990    private Fragment mFragment;
991    private final Activity mActivity;
992    private final String mTag;
993    private final Class&lt;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&lt;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
1034android.app.FragmentTransaction#commit} for the fragment transaction in each of these
1035callbacks&mdash;the system calls it for you and it may throw an exception if you call it yourself.
1036You 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
1039attach()}) a fragment to the activity layout&mdash;or if not instantiated, creates the fragment and
1040adds ({@link android.app.FragmentTransaction#add add()}) it to the layout (as a child of the {@code
1041android.R.id.content} view group)&mdash;when the respective tab is selected, and detaches ({@link
1042android.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
1045remains is to create each {@link android.app.ActionBar.Tab} and add it to the {@link
1046android.app.ActionBar}. Additionally, you must call {@link
1047android.app.ActionBar#setNavigationMode(int) setNavigationMode(NAVIGATION_MODE_TABS)} to make the
1048tabs visible. You might also want to disable the activity title by calling {@link
1049android.app.ActionBar#setDisplayShowTitleEnabled setDisplayShowTitleEnabled(false)} if the tab
1050titles 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&#64;Override
1056protected 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&lt;ArtistFragment>(
1069                    this, "artist", ArtistFragment.class));
1070    actionBar.addTab(tab);
1071
1072    tab = actionBar.newTab()
1073        .setText(R.string.album)
1074        .setTabListener(new TabListener&lt;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
1081android.app.ActionBar.TabListener} is one of several possible techniques. You can see more of
1082this style in the <a
1083href="{@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
1088href="{@docRoot}guide/components/activities.html#SavingActivityState">saved instance
1089state</a> so you can open the appropriate tab when the user returns. When it's time to save the
1090state, you can query the currently selected tab with {@link
1091android.app.ActionBar#getSelectedNavigationIndex()}. This returns the index position of the selected
1092tab.</p>
1093
1094<p class="caution"><strong>Caution:</strong> It's important that you save the state of each fragment
1095as necessary, so that when users switch fragments with the tabs and then return to a previous
1096fragment, it looks the way it did when they left. For information about saving the state of your
1097fragment, see the <a href="{@docRoot}guide/components/fragments.html">Fragments</a>
1098developer guide.</p>
1099
1100
1101<p class="note"><strong>Note:</strong> In some cases, the Android system will show your action
1102bar 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
1108built in drop-down list. For example, the drop-down list can offer different modes by which content
1109in 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
1115action 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
1123list of selectable items for the drop-down and the layout to use when drawing each item in the
1124list.</li>
1125  <li>Implement {@link android.app.ActionBar.OnNavigationListener} to define the behavior that
1126occurs when the user selects an item from the list.</li>
1127  <li>Enable navigation mode for the action bar with {@link
1128android.app.ActionBar#setNavigationMode setNavigationMode()}. For example:
1129<pre>
1130ActionBar actionBar = getActionBar();
1131actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
1132</pre>
1133  <p class="note"><strong>Note:</strong> You should perform this during your activity's {@link
1134android.app.Activity#onCreate
1135onCreate()} method.</p>
1136  </li>
1137  <li>Set the callback for the drop-down list with {@link
1138android.app.ActionBar#setListNavigationCallbacks setListNavigationCallbacks()}. For example:
1139<pre>
1140actionBar.setListNavigationCallbacks(mSpinnerAdapter, mNavigationCallback);
1141</pre>
1142<p>This method takes your {@link android.widget.SpinnerAdapter} and {@link
1143android.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
1149ways you can implement these to define the functionality for your drop-down navigation and
1150implementing various types of {@link android.widget.SpinnerAdapter} is beyond the scope of this
1151document (you should refer to the {@link android.widget.SpinnerAdapter} class reference for more
1152information). 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
1154reveal 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,
1168such as the drop-down list in the action bar. {@link android.widget.SpinnerAdapter} is an interface
1169that you can implement, but Android includes some useful implementations that you can extend, such
1170as {@link android.widget.ArrayAdapter} and {@link
1171android.widget.SimpleCursorAdapter}. For example, here's an easy way to create a {@link
1172android.widget.SpinnerAdapter} by using {@link android.widget.ArrayAdapter} implementation, which
1173uses a string array as the data source:</p>
1174
1175<pre>
1176SpinnerAdapter 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
1181three parameters: the application {@link android.content.Context}, the resource ID for the string
1182array, 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>
1185defined in a resource looks like this:</p>
1186
1187<pre>
1188&lt;?xml version="1.0" encoding="utf-8"?&gt;
1189&lt;resources&gt;
1190    &lt;string-array name="action_list"&gt;
1191        &lt;item&gt;Mercury&lt;/item&gt;
1192        &lt;item&gt;Venus&lt;/item&gt;
1193        &lt;item&gt;Earth&lt;/item&gt;
1194    &lt;/string-array&gt;
1195&lt;/pre&gt;
1196</pre>
1197
1198<p>The {@link android.widget.ArrayAdapter} returned by {@link
1199android.widget.ArrayAdapter#createFromResource createFromResource()} is complete and ready for you
1200to 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
1202android.app.ActionBar.OnNavigationListener OnNavigationListener}.</p>
1203
1204
1205<p>Your implementation of {@link android.app.ActionBar.OnNavigationListener} is where you handle
1206fragment changes or other modifications to your activity when the user selects an item from the
1207drop-down list. There's only one callback method to implement in the listener: {@link
1208android.app.ActionBar.OnNavigationListener#onNavigationItemSelected onNavigationItemSelected()}.</p>
1209
1210<p>The {@link
1211android.app.ActionBar.OnNavigationListener#onNavigationItemSelected onNavigationItemSelected()}
1212method receives the position of the item in the list and a unique item ID provided by the {@link
1213android.widget.SpinnerAdapter}.</p>
1214
1215<p>Here's an example that instantiates an anonymous implementation of {@link
1216android.app.ActionBar.OnNavigationListener OnNavigationListener}, which inserts a {@link
1217android.app.Fragment} into the
1218layout container identified by {@code R.id.fragment_container}:</p>
1219
1220<pre>
1221mOnNavigationListener = 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  &#64;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
1241complete and you can now call {@link android.app.ActionBar#setListNavigationCallbacks
1242setListNavigationCallbacks()} (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
1246the layout (replacing the current fragment in the {@code R.id.fragment_container} view). The
1247fragment added is given a tag that uniquely identifies it, which is the same string used to
1248identify 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
1251example:</p>
1252
1253<pre>
1254public class ListContentFragment extends Fragment {
1255    private String mText;
1256
1257    &#64;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    &#64;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
1288also want to redesign some of the action bar to match your app design. To do so, you need to use
1289Android's <a
1290href="{@docRoot}guide/topics/ui/themes.html">style and theme</a> framework to restyle the action
1291bar using special style properties.</p>
1292
1293
1294<p class="note"><strong>Note:</strong> In order for background images to change appearance
1295depending on the current button state (selected, pressed, unselected), the drawable resource you use
1296must be a <a href="{@docRoot}guide/topics/resources/drawable-resource.html#StateList">state
1297list drawable</a>.</p>
1298
1299<p class="caution"><strong>Caution:</strong> For all background drawables you provide, be sure to use <a
1300href="{@docRoot}guide/topics/graphics/2d-graphics.html#nine-patch">Nine-Patch drawables</a> to allow
1301stretching. 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
1311activity'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
1314what's left over. When the action bar is in overlay mode, your activity layout uses all the
1315available space and the system draws the action bar on top. Overlay mode can be useful if you want
1316your content to keep a fixed size and position when the action bar is hidden and shown. You might
1317also like to use it purely as a visual effect, because you can use a semi-transparent background
1318for the action bar so the user can still see some of your activity layout behind the action
1319bar.</p>
1320  <p class="note"><strong>Note:</strong> The {@link android.R.style#Theme_Holo Holo} theme families
1321draw the action bar with a semi-transparent background by default. However, you can modify it with
1322your own styles and the {@link android.R.style#Theme_DeviceDefault DeviceDefault} theme on
1323different 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
1325top of it. So, you must be careful not to place any important information or UI components in the
1326area overlayed by the action bar. If appropriate, you can refer to the platform's value for {@link
1327android.R.attr#actionBarSize} to determine the height of the action bar, by referencing it
1328in your XML layout. For example:</p>
1329<pre>
1330&lt;SomeView
1331    ...
1332    android:layout_marginTop="?android:attr/actionBarSize" /&gt;
1333</pre>
1334  <p>You can also retrieve the action bar height at runtime with {@link
1335android.app.ActionBar#getHeight()}. This reflects the height of the action bar at the time it's
1336called, which might not include the stacked action bar (due to navigation tabs) if called during early
1337activity lifecycle methods. To see how you can determine the total height at runtime, including the
1338stacked action bar, see the <a
1339href="{@docRoot}resources/samples/HoneycombGallery/src/com/example/android/hcgallery/TitlesFragment.html"
1340>{@code TitlesFragment}</a> class in the <a
1341href="{@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
136614.)</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
1379href="#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&lt;?xml version="1.0" encoding="utf-8"?>
1414&lt;resources>
1415    &lt;!-- the theme applied to the application or activity -->
1416    &lt;style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
1417        &lt;item name="android:actionBarTabTextStyle">@style/CustomTabTextStyle&lt;/item>
1418        &lt;item name="android:actionBarDivider">@drawable/ab_divider&lt;/item>
1419        &lt;item name="android:actionBarItemBackground">@drawable/ab_item_background&lt;/item>
1420    &lt;/style>
1421
1422    &lt;!-- style for the action bar tab text -->
1423    &lt;style name="CustomTabTextStyle" parent="@android:style/TextAppearance.Holo">
1424        &lt;item name="android:textColor">#2456c2&lt;/item>
1425    &lt;/style>
1426&lt;/resources>
1427</pre>
1428
1429<p class="note"><strong>Note:</strong> Be certain that your theme declares a parent theme in the
1430{@code &lt;style>} tag, from which it inherits all styles not explicitly declared by your theme.
1431When modifying the action bar, using a parent theme is important so that you can simply override the
1432action 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
1436manifest file like this:</p>
1437
1438<pre>
1439&lt;application android:theme="&#64;style/CustomActivityTheme" ... />
1440</pre>
1441
1442<p>For more information about using style and theme resources in your application, read <a
1443href="{@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
1449properties 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.
1451Each of these specifies another style that can define various properties for the action bar,
1452including different backgrounds with {@link android.R.attr#background android:background}, {@link
1453android.R.attr#backgroundSplit android:backgroundSplit}, and {@link android.R.attr#backgroundStacked
1454android:backgroundStacked}. If you override these action bar styles, be sure that you define a
1455parent action bar style such as {@link android.R.style#Widget_Holo_ActionBar
1456Widget.Holo.ActionBar}.</p>
1457
1458<p>For example, if you want to change the action bar's background, you can use the following
1459styles:</p>
1460
1461<pre>
1462&lt;?xml version="1.0" encoding="utf-8"?>
1463&lt;resources>
1464    &lt;!-- the theme applied to the application or activity -->
1465    &lt;style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
1466        &lt;item name="android:actionBarStyle">@style/MyActionBar&lt;/item>
1467        &lt;!-- other activity and action bar styles here -->
1468    &lt;/style>
1469
1470    &lt;!-- style for the action bar backgrounds -->
1471    &lt;style name="MyActionBar" parent="@android:style/Widget.Holo.ActionBar">
1472        &lt;item name="android:background">@drawable/ab_background&lt;/item>
1473        &lt;item name="android:backgroundStacked">@drawable/ab_background&lt;/item>
1474        &lt;item name="android:backgroundSplit">@drawable/ab_split_background&lt;/item>
1475    &lt;/style>
1476&lt;/resources>
1477</pre>
1478
1479
1480
1481
1482
1483