Android设计和开发系列第二篇:Action Bar(Develop—Training)

时间:2021-07-15 05:05:57

Adding the Action Bar

DEPENDENCIES AND PREREQUISITES

  • Android 2.1 or higher

YOU SHOULD ALSO READ

DESIGN GUIDE

Action Bar

The action bar is one of the most important design elements you can implement for your app's activities. It provides several user interface features that make your app immediately familiar to users by offering consistency between other Android apps. Key functions include:

  • A dedicated space for giving your app an identity and indicating the user's location in the app.
  • Access to important actions in a predictable way (such as Search).
  • Support for navigation and view switching (with tabs or drop-down lists).

Android设计和开发系列第二篇:Action Bar(Develop—Training)Android设计和开发系列第二篇:Action Bar(Develop—Training)

This training class offers a quick guide to the action bar's basics. For more information about action bar's various features, see the Action Bar guide.

Lessons


Setting Up the Action Bar
Learn how to add a basic action bar to your activity, whether your app supports only Android 3.0 and higher or also supports versions as low as Android 2.1 (by using the Android Support Library).
Adding Action Buttons
Learn how to add and respond to user actions in the action bar.
Styling the Action Bar
Learn how to customize the appearance of your action bar.
Overlaying the Action Bar
Learn how to overlay the action bar in front of your layout, allowing for seamless transitions when hiding the action bar.

Setting Up the Action Bar

In its most basic form, the action bar displays the title for the activity and the app icon on the left. Even in this simple form, the action bar is useful for all activities to inform users about where they are and to maintain a consistent identity for your app.

Android设计和开发系列第二篇:Action Bar(Develop—Training)Android设计和开发系列第二篇:Action Bar(Develop—Training)

Figure 1. An action bar with the app icon and activity title.

Setting up a basic action bar requires that your app use an activity theme that enables the action bar. How to request such a theme depends on which version of Android is the lowest supported by your app. So this lesson is divided into two sections depending on which Android version is your lowest supported.

Support Android 3.0 and Above Only


Beginning with Android 3.0 (API level 11), the action bar is included in all activities that use the Theme.Holo theme (or one of its descendants), which is the default theme when either the targetSdkVersion or minSdkVersionattribute is set to "11" or greater.

So to add the action bar to your activities, simply set either attribute to 11 or higher. For example:

<manifest ... >
    <uses-sdk android:minSdkVersion="11" ... />
    ...
</manifest>

Note: If you've created a custom theme, be sure it uses one of the Theme.Holo themes as its parent. For details, see Styling the Action Bar.

Now the Theme.Holo theme is applied to your app and all activities show the action bar. That's it.

Support Android 2.1 and Above


Adding the action bar when running on versions older than Android 3.0 (down to Android 2.1) requires that you include the Android Support Library in your application.

To get started, read the Support Library Setup document and set up the v7 appcompat library (once you've downloaded the library package, follow the instructions for Adding libraries with resources).

Once you have the Support Library integrated with your app project:

  1. Update your activity so that it extends ActionBarActivity. For example:
    public class MainActivity extends ActionBarActivity { ... }
  2. In your manifest file, update either the <application> element or individual <activity> elements to use one of the Theme.AppCompat themes. For example:
    <activity android:theme="@style/Theme.AppCompat.Light" ... >

    Note: If you've created a custom theme, be sure it uses one of the Theme.AppCompat themes as its parent. For details, see Styling the Action Bar.

Now your activity includes the action bar when running on Android 2.1 (API level 7) or higher.

Remember to properly set your app's API level support in the manifest:

<manifest ... >
    <uses-sdk android:minSdkVersion="7"  android:targetSdkVersion="18" />
    ...
</manifest>

Adding Action Buttons

The action bar allows you to add buttons for the most important action items relating to the app's current context. Those that appear directly in the action bar with an icon and/or text are known as action buttons. Actions that can't fit in the action bar or aren't important enough are hidden in the action overflow.

Android设计和开发系列第二篇:Action Bar(Develop—Training)

Figure 1. An action bar with an action button for Search and the action overflow, which reveals additional actions.

Specify the Actions in XML


All action buttons and other items available in the action overflow are defined in an XML menu resource. To add actions to the action bar, create a new XML file in your project's res/menu/ directory.

Add an <item> element for each item you want to include in the action bar. For example:

res/menu/main_activity_actions.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- Search, should appear as action button -->
    <item android:id="@+id/action_search"
          android:icon="@drawable/ic_action_search"
          android:title="@string/action_search"
          android:showAsAction="ifRoom" />
    <!-- Settings, should always be in the overflow -->
    <item android:id="@+id/action_settings"
          android:title="@string/action_settings"
          android:showAsAction="never" />
</menu>

Download action bar icons

To best match the Android iconographyguidelines, you should use icons provided in the Action Bar Icon Pack.

This declares that the Search action should appear as an action button when room is available in the action bar, but the Settings action should always appear in the overflow. (By default, all actions appear in the overflow, but it's good practice to explicitly declare your design intentions for each action.)

The icon attribute requires a resource ID for an image. The name that follows @drawable/ must be the name of a bitmap image you've saved in your project's res/drawable/ directory. For example,"@drawable/ic_action_search" refers to ic_action_search.png. Likewise, the title attribute uses a string resource that's defined by an XML file in your project's res/values/ directory, as discussed in Building a Simple User Interface.

Note: When creating icons and other bitmap images for your app, it's important that you provide multiple versions that are each optimized for a different screen density. This is discussed more in the lesson aboutSupporting Different Screens.

If your app is using the Support Library for compatibility on versions as low as Android 2.1, the showAsActionattribute is not available from the android: namespace. Instead this attribute is provided by the Support Library and you must define your own XML namespace and use that namespace as the attribute prefix. (A custom XML namespace should be based on your app name, but it can be any name you want and is only accessible within the scope of the file in which you declare it.) For example:

res/menu/main_activity_actions.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
    <!-- Search, should appear as action button -->
    <item android:id="@+id/action_search"
          android:icon="@drawable/ic_action_search"
          android:title="@string/action_search"
          yourapp:showAsAction="ifRoom"  />
    ...
</menu>

Add the Actions to the Action Bar


To place the menu items into the action bar, implement the onCreateOptionsMenu() callback method in your activity to inflate the menu resource into the given Menu object. For example:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu items for use in the action bar
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_activity_actions, menu);
    return super.onCreateOptionsMenu(menu);
}

Respond to Action Buttons


When the user presses one of the action buttons or another item in the action overflow, the system calls your activity's onOptionsItemSelected() callback method. In your implementation of this method, call getItemId() on the given MenuItem to determine which item was pressed—the returned ID matches the value you declared in the corresponding <item> element's android:id attribute.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
        case R.id.action_search:
            openSearch();
            return true;
        case R.id.action_settings:
            openSettings();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Add Up Button for Low-level Activities


Android设计和开发系列第二篇:Action Bar(Develop—Training)

Figure 4. The Up button in Gmail.

All screens in your app that are not the main entrance to your app (activities that are not the "home" screen) should offer the user a way to navigate to the logical parent screen in the app's hierarchy by pressing the Up button in the action bar.

When running on Android 4.1 (API level 16) or higher, or when usingActionBarActivity from the Support Library, performing Up navigation simply requires that you declare the parent activity in the manifest file and enable the Up button for the action bar.

For example, here's how you can declare an activity's parent in the manifest:

<application ... >
    ...
    <!-- The main/home activity (it has no parent activity) -->
    <activity
        android:name="com.example.myfirstapp.MainActivity" ...>
        ...
    </activity>
    <!-- A child of the main activity -->
    <activity
        android:name="com.example.myfirstapp.DisplayMessageActivity"
        android:label="@string/title_activity_display_message"
        android:parentActivityName="com.example.myfirstapp.MainActivity" >
        <!-- Parent activity meta-data to support 4.0 and lower -->
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.example.myfirstapp.MainActivity" />
    </activity>
</application>

Then enable the app icon as the Up button by calling setDisplayHomeAsUpEnabled():

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_displaymessage);     getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    // If your minSdkVersion is 11 or higher, instead use:
    // getActionBar().setDisplayHomeAsUpEnabled(true);
}

Because the system now knows MainActivity is the parent activity for DisplayMessageActivity, when the user presses the Up button, the system navigates to the parent activity as appropriate—you do not need to handle theUp button's event.

For more information about up navigation, see Providing Up Navigation.

Styling the Action Bar

The action bar provides your users a familiar and predictable way to perform actions and navigate your app, but that doesn't mean it needs to look exactly the same as it does in other apps. If you want to style the action bar to better fit your product brand, you can easily do so using Android's style and theme resources.

Android includes a few built-in activity themes that include "dark" or "light" action bar styles. You can also extend these themes to further customize the look for your action bar.

Note: If you are using the Support Library APIs for the action bar, then you must use (or override) the Theme.AppCompatfamily of styles (rather than the Theme.Holo family, available in API level 11 and higher). In doing so, each style property that you declare must be declared twice: once using the platform's style properties (the android: properties) and once using the style properties included in the Support Library (theappcompat.R.attr properties—the context for these properties is actually your app). See the examples below for details.

Use an Android Theme


Android设计和开发系列第二篇:Action Bar(Develop—Training)
Android设计和开发系列第二篇:Action Bar(Develop—Training)

Android includes two baseline activity themes that dictate the color for the action bar:

You can apply these themes to your entire app or to individual activities by declaring them in your manifest file with the android:theme attribute for the <application> element or individual <activity> elements.

For example:

<application android:theme="@android:style/Theme.Holo.Light" ... />
Android设计和开发系列第二篇:Action Bar(Develop—Training)

You can also use a dark action bar while the rest of the activity uses the light color scheme by declaring theTheme.Holo.Light.DarkActionBar theme.

When using the Support Library, you must instead use the Theme.AppCompat themes:

Be sure that you use action bar icons that properly contrast with the color of your action bar. To help you, theAction Bar Icon Pack includes standard action icons for use with both the Holo light and Holo dark action bar.

Customize the Background


Android设计和开发系列第二篇:Action Bar(Develop—Training)

To change the action bar background, create a custom theme for your activity that overrides theactionBarStyle property. This property points to another style in which you can override the background property to specify a drawable resource for the action bar background.

If your app uses navigation tabs or the split action bar, then you can also specify the background for these bars using the backgroundStacked and backgroundSplit properties, respectively.

Caution: It's important that you declare an appropriate parent theme from which your custom theme and style inherit their styles. Without a parent style, your action bar will be without many style properties unless you explicitly declare them yourself.

For Android 3.0 and higher only

When supporting Android 3.0 and higher only, you can define the action bar's background like this:

res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@android:style/Theme.Holo.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
    </style>     <!-- ActionBar styles -->
    <style name="MyActionBar"
           parent="@android:style/Widget.Holo.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@drawable/actionbar_background</item>
    </style>
</resources>

Then apply your theme to your entire app or individual activities:

<application android:theme="@style/CustomActionBarTheme" ... />

For Android 2.1 and higher

When using the Support Library, the same theme as above must instead look like this:

res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@style/Theme.AppCompat.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/MyActionBar</item>         <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/MyActionBar</item>
    </style>     <!-- ActionBar styles -->
    <style name="MyActionBar"
           parent="@style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="android:background">@drawable/actionbar_background</item>         <!-- Support library compatibility -->
        <item name="background">@drawable/actionbar_background</item>
    </style>
</resources>

Then apply your theme to your entire app or individual activities:

<application android:theme="@style/CustomActionBarTheme" ... />

Customize the Text Color


To modify the color of text in the action bar, you need to override separate properties for each text element:

For Android 3.0 and higher only

When supporting Android 3.0 and higher only, your style XML file might look like this:

res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@style/Theme.Holo">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
        <item name="android:actionBarTabTextStyle">@style/MyActionBarTabText</item>
        <item name="android:actionMenuTextColor">@color/actionbar_text</item>
    </style>     <!-- ActionBar styles -->
    <style name="MyActionBar"
           parent="@style/Widget.Holo.ActionBar">
        <item name="android:titleTextStyle">@style/MyActionBarTitleText</item>
    </style>     <!-- ActionBar title text -->
    <style name="MyActionBarTitleText"
           parent="@style/TextAppearance.Holo.Widget.ActionBar.Title">
        <item name="android:textColor">@color/actionbar_text</item>
    </style>     <!-- ActionBar tabs text styles -->
    <style name="MyActionBarTabText"
           parent="@style/Widget.Holo.ActionBar.TabText">
        <item name="android:textColor">@color/actionbar_text</item>
    </style>
</resources>

For Android 2.1 and higher

When using the Support Library, your style XML file might look like this:

res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@style/Theme.AppCompat">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
        <item name="android:actionBarTabTextStyle">@style/MyActionBarTabText</item>
        <item name="android:actionMenuTextColor">@color/actionbar_text</item>         <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/MyActionBar</item>
        <item name="actionBarTabTextStyle">@style/MyActionBarTabText</item>
        <item name="actionMenuTextColor">@color/actionbar_text</item>
    </style>     <!-- ActionBar styles -->
    <style name="MyActionBar"
           parent="@style/Widget.AppCompat.ActionBar">
        <item name="android:titleTextStyle">@style/MyActionBarTitleText</item>         <!-- Support library compatibility -->
        <item name="titleTextStyle">@style/MyActionBarTitleText</item>
    </style>     <!-- ActionBar title text -->
    <style name="MyActionBarTitleText"
           parent="@style/TextAppearance.AppCompat.Widget.ActionBar.Title">
        <item name="android:textColor">@color/actionbar_text</item>
        <!-- The textColor property is backward compatible with the Support Library -->
    </style>     <!-- ActionBar tabs text -->
    <style name="MyActionBarTabText"
           parent="@style/Widget.AppCompat.ActionBar.TabText">
        <item name="android:textColor">@color/actionbar_text</item>
        <!-- The textColor property is backward compatible with the Support Library -->
    </style>
</resources>

Customize the Tab Indicator


Android设计和开发系列第二篇:Action Bar(Develop—Training)

To change the indicator used for the navigation tabs, create an activity theme that overrides theactionBarTabStyle property. This property points to another style resource in which you override the backgroundproperty that should specify a state-list drawable.

Note: A state-list drawable is important so that the tab currently selected indicates its state with a background different than the other tabs. For more information about how to create a drawable resource that handles multiple button states, read the State List documentation.

For example, here's a state-list drawable that declares a specific background image for several different states of an action bar tab:

res/drawable/actionbar_tab_indicator.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> <!-- STATES WHEN BUTTON IS NOT PRESSED -->     <!-- Non focused states -->
    <item android:state_focused="false" android:state_selected="false"
          android:state_pressed="false"
          android:drawable="@drawable/tab_unselected" />
    <item android:state_focused="false" android:state_selected="true"
          android:state_pressed="false"
          android:drawable="@drawable/tab_selected" />     <!-- Focused states (such as when focused with a d-pad or mouse hover) -->
    <item android:state_focused="true" android:state_selected="false"
          android:state_pressed="false"
          android:drawable="@drawable/tab_unselected_focused" />
    <item android:state_focused="true" android:state_selected="true"
          android:state_pressed="false"
          android:drawable="@drawable/tab_selected_focused" /> <!-- STATES WHEN BUTTON IS PRESSED -->     <!-- Non focused states -->
    <item android:state_focused="false" android:state_selected="false"
          android:state_pressed="true"
          android:drawable="@drawable/tab_unselected_pressed" />
    <item android:state_focused="false" android:state_selected="true"
        android:state_pressed="true"
        android:drawable="@drawable/tab_selected_pressed" />     <!-- Focused states (such as when focused with a d-pad or mouse hover) -->
    <item android:state_focused="true" android:state_selected="false"
          android:state_pressed="true"
          android:drawable="@drawable/tab_unselected_pressed" />
    <item android:state_focused="true" android:state_selected="true"
          android:state_pressed="true"
          android:drawable="@drawable/tab_selected_pressed" />
</selector>

For Android 3.0 and higher only

When supporting Android 3.0 and higher only, your style XML file might look like this:

res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@style/Theme.Holo">
        <item name="android:actionBarTabStyle">@style/MyActionBarTabs</item>
    </style>     <!-- ActionBar tabs styles -->
    <style name="MyActionBarTabs"
           parent="@style/Widget.Holo.ActionBar.TabView">
        <!-- tab indicator -->
        <item name="android:background">@drawable/actionbar_tab_indicator</item>
    </style>
</resources>

For Android 2.1 and higher

When using the Support Library, your style XML file might look like this:

res/values/themes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@style/Theme.AppCompat">
        <item name="android:actionBarTabStyle">@style/MyActionBarTabs</item>         <!-- Support library compatibility -->
        <item name="actionBarTabStyle">@style/MyActionBarTabs</item>
    </style>     <!-- ActionBar tabs styles -->
    <style name="MyActionBarTabs"
           parent="@style/Widget.AppCompat.ActionBar.TabView">
        <!-- tab indicator -->
        <item name="android:background">@drawable/actionbar_tab_indicator</item>         <!-- Support library compatibility -->
        <item name="background">@drawable/actionbar_tab_indicator</item>
    </style>
</resources>

More resources

Overlaying the Action Bar

By default, the action bar appears at the top of your activity window, slightly reducing the amount of space available for the rest of your activity's layout. If, during the course of user interaction, you want to hide and show the action bar, you can do so by calling hide() and show() on the ActionBar. However, this causes your activity to recompute and redraw the layout based on its new size.

Android设计和开发系列第二篇:Action Bar(Develop—Training)

Figure 1. Gallery's action bar in overlay mode.

To avoid resizing your layout when the action bar hides and shows, you can enable overlay mode for the action bar. When in overlay mode, your activity layout uses all the space available as if the action bar is not there and the system draws the action bar in front of your layout. This obscures some of the layout at the top, but now when the action bar hides or appears, the system does not need to resize your layout and the transition is seamless.

Tip: If you want your layout to be partially visible behind the action bar, create a custom style for the action bar with a partially transparent background, such as the one shown in figure 1. For information about how to define the action bar background, read Styling the Action Bar.

Enable Overlay Mode


To enable overlay mode for the action bar, you need to create a custom theme that extends an existing action bar theme and set the android:windowActionBarOverlay property to true.

For Android 3.0 and higher only

If your minSdkVersion is set to 11 or higher, your custom theme should use Theme.Holo theme (or one of its descendants) as your parent theme. For example:

<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@android:style/Theme.Holo">
        <item name="android:windowActionBarOverlay">true</item>
    </style>
</resources>

For Android 2.1 and higher

If your app is using the Support Library for compatibility on devices running versions lower than Android 3.0, your custom theme should use Theme.AppCompat theme (or one of its descendants) as your parent theme. For example:

<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActionBarTheme"
           parent="@android:style/Theme.AppCompat">
        <item name="android:windowActionBarOverlay">true</item>         <!-- Support library compatibility -->
        <item name="windowActionBarOverlay">true</item>
    </style>
</resources>

Also notice that this theme includes two definitions for the windowActionBarOverlay style: one with the android:prefix and one without. The one with the android: prefix is for versions of Android that include the style in the platform and the one without the prefix is for older versions that read the style from the Support Library.

Specify Layout Top-margin


When the action bar is in overlay mode, it might obscure some of your layout that should remain visible. To ensure that such items remain below the action bar at all times, add either margin or padding to the top of the view(s) using the height specified by actionBarSize. For example:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?android:attr/actionBarSize">
    ...
</RelativeLayout>

If you're using the Support Library for the action bar, you need to remove the android: prefix. For example:

<!-- Support library compatibility -->
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingTop="?attr/actionBarSize">
    ...
</RelativeLayout>

In this case, the ?attr/actionBarSize value without the prefix works on all versions, including Android 3.0 and higher.