一. 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_第1张图片

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 theTheme.Holotheme (or one of its descendants), which is the default theme when either thetargetSdkVersionorminSdkVersionattribute is set to"11"or greater.

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

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

Note:If you've created a custom theme, be sure it uses one of theTheme.Holothemes as its parent. For details, seeStyling the Action Bar.

Now theTheme.Holotheme 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 theSupport Library Setupdocument and set up thev7 appcompatlibrary (once you've downloaded the library package, follow the instructions forAdding libraries with resources).

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

  1. Update your activity so that it extendsActionBarActivity. 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 theTheme.AppCompatthemes. For example:
    <activity android:theme="@style/Theme.AppCompat.Light" ... >

    Note:If you've created a custom theme, be sure it uses one of theTheme.AppCompatthemes as its parent. For details, seeStyling 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 asaction buttons. Actions that can't fit in the action bar or aren't important enough are hidden in the action overflow.

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 XMLmenu resource. To add actions to the action bar, create a new XML file in your project'sres/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 Androidiconographyguidelines, you should use icons provided in theAction 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.)

Theiconattribute 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'sres/drawable/directory. For example,"@drawable/ic_action_search"refers toic_action_search.png. Likewise, thetitleattribute uses a string resource that's defined by an XML file in your project'sres/values/directory, as discussed inBuilding 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 Libraryfor compatibility on versions as low as Android 2.1, theshowAsActionattribute is not available from theandroid: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 theonCreateOptionsMenu()callback method in your activity to inflate the menu resource into the givenMenuobject. 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'sonOptionsItemSelected()callback method. In your implementation of this method, callgetItemId()on the givenMenuItemto determine which item was pressed—the returned ID matches the value you declared in the corresponding<item>element'sandroid:idattribute.

@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


Figure 4.TheUpbutton 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 theUpbutton in the action bar.

When running on Android 4.1 (API level 16) or higher, or when usingActionBarActivityfrom the Support Library, performingUpnavigation simply requires that you declare the parent activity in the manifest file and enable theUpbutton 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 theUpbutton by callingsetDisplayHomeAsUpEnabled():

@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 knowsMainActivityis the parent activity forDisplayMessageActivity, when the user presses theUpbutton, the system navigates to the parent activity as appropriate—youdo notneed to handle theUpbutton's event.

For more information about up navigation, seeProviding 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'sstyle and themeresources.

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) theTheme.AppCompatfamily of styles (rather than theTheme.Holofamily, 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 (theandroid:properties) and once using the style properties included in the Support Library (theappcompat.R.attrproperties—the context for these properties is actuallyyour app). See the examples below for details.

Use an Android Theme

Android Action Bar_第2张图片

Android Action Bar_第3张图片

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

  • Theme.Holofor a "dark" theme.
  • Theme.Holo.Lightfor a "light" theme.

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

For example:

<application android:theme="@android:style/Theme.Holo.Light" ... />
Android Action Bar_第4张图片

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

When using the Support Library, you must instead use theTheme.AppCompatthemes:

  • Theme.AppCompatfor the "dark" theme.
  • Theme.AppCompat.Lightfor the "light" theme.
  • Theme.AppCompat.Light.DarkActionBarfor the light theme with a dark action bar.

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

Customize the Background

Android Action Bar_第5张图片

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

If your app usesnavigation tabsor thesplit action bar, then you can also specify the background for these bars using thebackgroundStackedandbackgroundSplitproperties, 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:

  • Action bar title: Create a custom style that specifies thetextColorproperty and specify that style for thetitleTextStyleproperty in your customactionBarStyle.

    Note:The custom style applied totitleTextStyleshould useTextAppearance.Holo.Widget.ActionBar.Titleas the parent style.

  • Action bar tabs: OverrideactionBarTabTextStylein your activity theme.
  • Action buttons: OverrideactionMenuTextColorin your activity theme.

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_第6张图片

To change the indicator used for thenavigation tabs, create an activity theme that overrides theactionBarTabStyleproperty. This property points to another style resource in which you override thebackgroundproperty 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 theState Listdocumentation.

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>

四. 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 callinghide()andshow()on theActionBar. However, this causes your activity to recompute and redraw the layout based on its new size.

Android Action Bar_第7张图片

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

To avoid resizing your layout when the action bar hides and shows, you can enableoverlay modefor 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, readStyling 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 theandroid:windowActionBarOverlayproperty totrue.

For Android 3.0 and higher only

If yourminSdkVersionis set to11or higher, your custom theme should useTheme.Holotheme (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 useTheme.AppCompattheme (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 thewindowActionBarOverlaystyle: one with theandroid:prefix and one without. The one with theandroid: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 byactionBarSize. 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 theandroid: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/actionBarSizevalue without the prefix works on all versions, including Android 3.0 and higher.


更多相关文章

  1. Android三种方法设置ImageView的图片
  2. Android 如何加载大图片
  3. Android 图片加载库Glide
  4. android 自定义图片剪裁
  5. Android——ImageButton【图片按钮】的点击事件与属性
  6. android 选择本地图片并预览
  7. Android 实现文件(图片)上传
  8. Android对话框图片全屏

随机推荐

  1. linux下使用共享存储编程初试 (转载)
  2. 【Linxu内核设计与实现】-第7章 中断和中
  3. Linux下Rsync+Inotify-tools实现数据实时
  4. linux系统编程之进程(八):守护进程详解及创
  5. 利用ssh-copy-id复制公钥到多台服务器
  6. 获取网卡名称 linux c
  7. Emacs 快速参考 c-c++ 模式
  8. Linux零散知识点笔记
  9. socket的长连接、短连接、半包、粘包与分
  10. 如何更改提示颜色?