Android 開發指南 翻譯 User Interfaces -- Action Bar

Action bar 行動條

The action bar is a window feature that identifies the application and user location, and provides user actions and navigation modes. You should use the action bar in most activities that need to prominently present user actions or global navigation, because the action bar offers users a consistent interface across applications and the system gracefully adapts the action bar's appearance for different screen configurations. You can control the behaviors and visibility of the action bar with the ActionBarAPIs, which were added in Android 3.0 (API level 11).

Action bar 是以個window特性,它根據應用和用戶所在位置,提供用戶操作和導航。應該在絕大多數Acitvity中使用Action bar來明顯的提供用戶操作和全局導航,由於action bar提供整個應用的一致接口,而且系統爲不同的屏幕配置自動調整Action bar,你可以控制action bar的行爲和是否可見,action bar是Android3.0增加的特性。

The primary goals of the action bar are to:

action bar的主要目標:

  • Provide a dedicated space for identifying the application brand and user location.

    提供一個專用空間來標識應用商標和用戶位置。

    This is accomplished with the app icon or logo on the left side and the activity title. You might choose to remove the activity title, however, if the current view is identified by a navigation label, such as the currently selected tab.

    這是通過在activity的標題左側放置應用圖標來實現的。你可以去除activity的標題,然而,如果當前view可以通過導航標籤識別,例如當前選中的tab頁。

  • Provide consistent navigation and view refinement across different applications.

    跨不同應用,提供一致的導航和view

    The action bar provides built-in tab navigation for switching between fragments. It also offers a drop-down list you can use as an alternative navigation mode or to refine the current view (such as to sort a list by different criteria).

    action bar提供內置的標籤導航,用於切換不同的fragment. 提供下拉列表作爲可選的導航模式或優化當前view.

  • Make key actions for the activity (such as "search", "create", "share", etc.) prominent and accessible to the user in a predictable way.

    對於Activity的操作顯著和可用。

    You can provide instant access to key user actions by placing items from the options menu directly in the action bar, as "action items." Action items can also provide an "action view," which provides an embedded widget for even more immediate action behaviors. Menu items that are not promoted to an action item are available in the overflow menu, revealed by either the device Menu button (when available) or by an "overflow menu" button in the action bar (when the device does not include aMenu button).


Figure 1. Action bar from the Honeycomb Gallery app (on a landscape handset), showing the logo on the left, navigation tabs, and an action item on the right (plus the overflow menu button).

Note: If you're looking for information about the contextual action bar for displaying contextual action items, see the Menuguide.

Action Bar Design

For design guidelines, read Android Design's Action Bar guide.

Adding the Action Bar

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 minSdkVersion attribute is set to "11" or greater. For example:

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

In this example, the application requires a minimum version of API Level 4 (Android 1.6), but it also targets API level 11 (Android 3.0). This way, when the application runs on Android 3.0 or greater, the system applies the holographic theme to each activity, and thus, each activity includes the action bar.

If you want to use ActionBar APIs, such as to add navigation modes and modify action bar styles, you should set theminSdkVersion to "11" or greater. If you want your app to support older versions of Android, there are ways to use a limited set of ActionBar APIs on devices that support API level 11 or higher, while still running on older versions. See the sidebox for information about remaining backward-compatible.

Removing the action bar

If you don't want the action bar for a particular activity, set the activity theme to Theme.Holo.NoActionBar. For example:

<activity android:theme="@android:style/Theme.Holo.NoActionBar">

You can also hide the action bar at runtime by calling hide(). For example:

ActionBar actionBar = getActionBar();
actionBar.hide();

When the action bar hides, the system adjusts your activity layout to fill all the screen space now available. You can bring the action bar back with show().

Beware that hiding and removing the action bar causes your activity to re-layout in order to account for the space consumed by the action bar. If your activity regularly hides and shows the action bar (such as in the Android Gallery app), you might want to use overlay mode. Overlay mode draws the action bar on top of your activity layout rather than in its own area of the screen. This way, your layout remains fixed when the action bar hides and re-appears. To enable overlay mode, create a theme for your activity and set android:windowActionBarOverlayto true. For more information, see the section about Styling the Action Bar.

Tip: If you have a custom activity theme in which you'd like to remove the action bar, set the android:windowActionBar style property to false. However, if you remove the action bar using a theme, then the window will not allow the action bar at all, so you cannot add it later—calling getActionBar() will return null.

Adding Action Items 增加操作項

Sometimes you might want to give users immediate access to an item from the options menu. To do this, you can declare that the menu item should appear in the action bar as an "action item." An action item can include an icon and/or a text title. If a menu item does not appear as an action item, then the system places it in the overflow menu. The overflow menu is revealed either by the device Menu button (if provided by the device) or an additional button in the action bar (if the device does not provide the Menu button).

有時,你想通過可選菜單給用戶一些直接操作的操作項。你可以聲明菜單項作爲操作項顯示在action bar上。操作項包括一個圖標和一個文本標題。如果菜單項不能顯示在action bar上,系統會把它們放到溢出菜單中。溢出菜單可以通過菜單按鈕或action bar上一個附件按鈕調出。

Figure 2. Two action items with icon and text titles, and the overflow menu button.

When the activity first starts, the system populates the action bar and overflow menu by callingonCreateOptionsMenu() for your activity. As discussed in the Menus developer guide, it's in this callback method that you should inflate an XML menu resource that defines the menu items. For example:

當activity初次啓動,系統通過調用onCreateOptionMenu()生成action bar和溢出菜單。正如菜單開發指南中描述的,在該方法中可以由菜單資源生成菜單項。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main_activity, menu);
    return true;
}

In the XML file, you can request a menu item to appear as an action item by declaring android:showAsAction="ifRoom" for the <item> element. This way, the menu item appears in the action bar for quick access only if there is room available. If there's not enough room, the item appears in the overflow menu.

在xml文件中,你可以要求菜單項出現在action bar上,爲菜單<item>定義android:showAsAction ="ifRoom"即可。這樣如果有空間,菜單項將變成動作項。如果沒有空間,菜單項會出現在溢出菜單中。

If your menu item supplies both a title and an icon—with the android:title and android:icon attributes—then the action item shows only the icon by default. If you want to display the text title, add "withText" to the android:showAsAction attribute. For example:

如果菜單項支持標題和圖標--屬性android:title和android:icon,動作項缺省只顯示圖標,如果想顯示標題,需給android:showAsAction增加屬性withText.例如:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_save"
          android:icon="@drawable/ic_menu_save"
          android:title="@string/menu_save"
          android:showAsAction="ifRoom|withText" />
</menu>

Note: The "withText" value is a hint to the action bar that the text title should appear. The action bar will show the title when possible, but might not if an icon is available and the action bar is constrained for space.

When the user selects an action item, your activity receives a call to onOptionsItemSelected(), passing the ID supplied by the android:id attribute—the same callback received for all items in the options menu.

當用戶選擇了操作項,activity接收調用onOptionsItemSelected()傳遞菜單項的ID,和可選菜單一樣。

It's important that you always define android:title for each menu item—even if you don't declare that the title appear with the action item—for three reasons:

定義菜單項的android:title是重要的,即使你不把他們顯示在操作項上。三個理由:

  • If there's not enough room in the action bar for the action item, the menu item appears in the overflow menu and only the title appears.
  • 如果沒有操作項的空間,菜單項會出現在溢出菜單中,此時只顯示標題。
  • Screen readers for sight-impaired users read the menu item's title.
  • 屏幕閱讀器會閱讀菜單項標題。
  • If the action item appears with only the icon, a user can long-press the item to reveal a tool-tip that displays the action item's title.
  • 如果操作項只顯示圖標,用戶可以長按顯示菜單提示,這是顯示的是菜單標題。

The android:icon is always optional, but recommended. For icon design recommendations, see the Action Bar Icon design guidelines.

Note: If you added the menu item from a fragment, via the Fragment class's onCreateOptionsMenu callback, then the system calls the respective onOptionsItemSelected() method for that fragment when the user selects one of the fragment's items. However the activity gets a chance to handle the event first, so the system calls onOptionsItemSelected() on the activity before calling the same callback for the fragment.

You can also declare an item to "always" appear as an action item, instead of being placed in the overflow menu when space is limited. In most cases, you should not force an item to appear in the action bar by using the "always" value. However, you might need an item to always appear when it provides an action view that does not offer a default action for the overflow menu. Beware that too many action items can create a cluttered UI and cause layout problems on devices with a narrow screen. It's best to instead use "ifRoom" to request that an item appear in the action bar, but allow the system to move it into the overflow menu when there's not enough room.

你可以聲明菜單項爲“always”,使其出現在操作項上,而不是放到溢出菜單中。

For more information about creating the options menu that defines your action items, see the Menus developer guide.

Choosing your action items 改變操作項

You should carefully choose which items from your options menu should appear as action items by assessing a few key traits. In general, each action item should be at least one of the following:

你需要仔細選擇那些菜單項成爲操作項。一般,每個操作項應該具有下列特性:

  1. Frequently used: It's an action that your users need seven out of ten visits or they use it several times in a row.

    經常使用

    Example frequent actions: "New message" in the Messaging app and "Search" in Android Market.

  2. Important: It's an action that you need users to easily discover or, if it's not frequently used, it's important that it be effortless to perform in the few cases that users do need it.

    重要操作

    Example important actions: "Add network" in Wi-Fi settings and "Switch to camera" in the Gallery app.

  3. Typical: It's an action that is typically provided in the action bar in similar apps, so your users expect to find it in yours.

    典型操作

    Example typical actions: "Refresh" in an email or social app, and "New contact" in the People app.

If you believe that more than four of your menu items can be justified as action items, then you should carefully consider their relative level of importance and try to set no more than four as action items (and do so using the "ifRoom" value to allow the system to put some back in the overflow menu when space is limited on smaller screens). Even if space is available on a wide screen, you should not create a long stream of action items that clutter the UI and appear like a desktop toolbar, so keep the number of action items to a minimum.

Additionally, the following actions should never appear as action items: Settings, Help, Feedback, or similar. Always keep them in the overflow menu.

另外,下列操作不應該出現在操作項:設置、幫助、反饋等等。應該放到溢出菜單中。

Note: Remember that not all devices provide a dedicated hardware button for Search, so if it's an important feature in your app, it should always appear as an action item (and usually as the first item, especially if you offer it with an action view).

注意:不是搜有的設備都提供專用的搜索鍵,如果那時應用的重要特性,它應該出現在操作項。

Using split action bar 分離的操作條

When your application is running on Android 4.0 (API level 14) and higher, there's an extra mode available for the action bar called "split action bar." When you enable split action bar, a separate bar appears at the bottom of the screen to display all action items when the activity is running on a narrow screen (such as a portrait-oriented handset). Splitting the action bar to separate the action items ensures that a reasonable amount of space is available to display all your action items on a narrow screen, while leaving room for navigation and title elements at the top.

當你的應用運行在Android 4.0以上時,有一個action bar的附加模式--分離的操作條。當使用分離的操作條時,在屏幕下方出現獨立的操作條,顯示所有的操作項。

To enable split action bar, simply add uiOptions="splitActionBarWhenNarrow" to your <activity> or <application> manifest element.

通過給<activity>或<application>設置uiOptions="splitActionBarWhenNarrow",使用分離的操作條。

Be aware that Android adjusts the action bar's appearance in a variety of ways, based on the current screen size. Using split action bar is just one option that you can enable to allow the action bar to further optimize the user experience for different screen sizes. In doing so, you may also allow the action bar to collapse navigation tabs into the main action bar. That is, if you use navigation tabs in your action bar, once the action items are separated on a narrow screen, the navigation tabs may be able to fit into the main action bar rather than be separated into the "stacked action bar." Specifically, if you've disabled the action bar icon and title (with setDisplayShowHomeEnabled(false) and setDisplayShowTitleEnabled(false)), then the navigation tabs collapse into the main action bar, as shown by the second device in figure 3.

Figure 3. Mock-ups of split action bar with navigation tabs on the left; with the app icon and title disabled on the right.

Note: Although the android:uiOptions attribute was added in Android 4.0 (API level 14), you can safely include it in your application even if your minSdkVersion is set to a value lower than "14" to remain compatible with older versions of Android. When running on older versions, the system simply ignores the XML attribute because it doesn't understand it. The only condition to including it in your manifest is that you must compile your application against a platform version that supports API level 14 or higher. Just be sure that you don't openly use other APIs in your application code that aren't supported by the version declared by your minSdkVersion attribute—only XML attributes are safely ignored by older platforms.

Using the App Icon for Navigation 應用圖標做導骯

By default, your application icon appears in the action bar on the left side. If you'd like, you can enable the icon to behave as an action item. In response to user action on the icon, your application should do one of two things:

缺省情況下,應用圖標出現在action bar的左邊。它可以作爲操作項。在圖標上的操作,應該是2件事:

  • Go to the application "home" activity, or
  • 返回應用的主activity
  • Navigate "up" the application's structural hierarchy
  • 導航到應用程序結構的“返回”。

When the user touches the icon, the system calls your activity's onOptionsItemSelected() method with theandroid.R.id.home ID. In response, you should either start the home activity or take the user one step up in your application's structural hierarchy.

當用戶觸摸應用圖標,系統調用activity的onOptionsItemSelected()方法,此時傳遞android.R.id.home作爲參數。也可以用來返回主activity或程序的上一步。

If you respond to the application icon by returning to the home activity, you should include the FLAG_ACTIVITY_CLEAR_TOP flag in the Intent. With this flag, if the activity you're starting already exists in the current task, then all activities on top of it are destroyed and it is brought to the front. Adding this flag is often important because going "home" is an action that's equivalent to "going back" and you should usually not create a new instance of the home activity. Otherwise, you might end up with a long stack of activities in the current task with multiple instances of the home activity.

如果應用圖標是返回主activity,在intent中要包括FLAG_ACTIVITY_CLEAR_TOP標誌。如果當前任務中已經啓動了主activity,使用這個標誌可以銷燬所有主activity堆棧上面的activity。

For example, here's an implementation of onOptionsItemSelected() that returns to the application's "home" activity:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // app icon in action bar clicked; go home
            Intent intent = new Intent(this, HomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

In case the user can enter the current activity from another application, you might also want to add the FLAG_ACTIVITY_NEW_TASK flag. This flag ensures that, when the user navigates either "home" or "up", the new activity is not added to the current task, but instead started in a task that belongs to your application. For example, if the user starts an activity in your application through an intent invoked by another application, then selects the action bar icon to navigate home or up, the FLAG_ACTIVITY_CLEAR_TOP flag starts the activity in a task that belongs to your application (not the current task). The system either starts a new task with your new activity as the root activity or, if an existing task exists in the background with an instance of that activity, then that task is brought forward and the target activity receives onNewIntent(). So if your activity accepts intents from other applications (it declares any generic intent filters), you should usually add the FLAG_ACTIVITY_NEW_TASK flag to the intent:

使用FLAG_ACTIVITY_NEW_TASK標誌,當用戶導航到主acitivity或返回時,新的activity不添加到當前任務,而是開始一個屬於自己的應用。如果Activity接受其他應用發出的intent,應該增加FLAG_ACTIVITY_NEW_TASK標誌給intent:

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

For more information about these flags and other back stack behaviors, read the Tasks and Back Stack developer guide.

Note: If you're using the icon to navigate to the home activity, beware that beginning with Android 4.0 (API level 14), you must explicitly enable the icon as an action item by callingsetHomeButtonEnabled(true) (in previous versions, the icon was enabled as an action item by default).

注意:如果使用應用圖表導航到主activity,是從Android 4.0 開始的,你必須調用setHomeButtonEnabled(true)明確圖標作爲一個操作項。

Navigating up 導航

Figure 4. The Email app's standard icon (left) and the "navigate up" icon (right). The system automatically adds the "up" indicator.

As a supplement to traditional "back" navigation—which takes the user to the previous screen in the task history—you can enable the action bar icon to offer "up" navigation, which should take the user one step up in your application's structural hierarchy. For instance, if the current screen is somewhere deep in the hierarchy of the application, touching the app icon should navigate upward one level, to the parent of the current screen.

作爲傳統"back"鍵的補充,把用戶帶回到先前的屏幕。

For example, figure 5 illustrates how the BACK button behaves when the user navigates from one application to an activity belonging to a different application (specifically, when composing an email to a person selected from the People app).

Figure 5. The BACK button behavior after entering the Email app from the People (or Contacts) app.

However, if the user wants to stay within the email application after composing the email, up navigation allows the user to navigate upward in the email application, rather than go back to the previous activity. Figure 6 illustrates this scenario, in which the user again comes into the email application, but presses the action bar icon to navigate up, rather than back.


Figure 6. Example behavior for UP navigation after entering the Email app from the People app.

Navigation Design

For more about how Up and Back navigation differ, read Android Design's Navigation guide.

To enable the icon for up navigation (which displays the "up" indicator next to the icon), call setDisplayHomeAsUpEnabled(true) on your ActionBar:

使應用圖標當做返回導航,可以調用ActionBar的setDisplayHomeAsUpEnabled(true).

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);
    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    ...
}

When the user touches the icon, the system calls your activity's onOptionsItemSelected() method with the android.R.id.home ID, as shown in the above section about Using the App Icon for Navigation.


Remember to use the FLAG_ACTIVITY_CLEAR_TOP flag in the Intent, so that you don't create a new instance of the parent activity if one already exists. For instance, if you don't use theFLAG_ACTIVITY_CLEAR_TOP flag, then after navigating up, the BACK button will actually take the user "forward", with respect to the application structure, which would be strange.

Note: If there are many paths that the user could have taken to reach the current activity within your application, the up icon should navigate backward along the path the user actually followed to get to the current activity.

Adding an Action View 增加操作視圖

Figure 7. An action bar with a collapsed action view for Search (top), then expanded action view with the SearchView widget (bottom).

An action view is a widget that appears in the action bar as a substitute for an action item's button. For example, if you have an item in the options menu for "Search," you can add an action view that replaces the button with a SearchView widget, as shown in figure 7.

操作視圖是出現在action bar上代替操作項按鈕的控件。例如:有一個搜索的可選菜單,你可以增加的操作視圖來代替按鈕,如圖7所示。

To declare an action view for an item in your menu resource, use either the android:actionLayout or android:actionViewClassattribute to specify either a layout resource or widget class to use, respectively. For example:

在菜單資源文件中聲明操作視圖,使用android:actionLayout指定layout資源或android:actionViewClass指定控件類。

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_search"
          android:title="@string/menu_search"
          android:icon="@drawable/ic_menu_search"
          android:showAsAction="ifRoom|collapseActionView"
          android:actionViewClass="android.widget.SearchView" />
</menu>

Notice that the android:showAsAction attribute also includes "collapseActionView". This is optional and declares that the action view should be collapsed into a button. When the user selects the button, the action view expands. Otherwise, the action view is visible by default and might consume valuable action bar space even when the user is not using it. For more information, see the next section about Handling collapsible action views.

菜單項的android:shwoAsAction屬性可以包括collapseActionView。這個選項聲明操作視圖應該被壓縮成一個按鈕。當用戶選擇該按鈕時,操作視圖展開。否則,操作視圖會佔用大量的action bar空間。更多信息,在下一節。

If you need to add some event hooks to your action view, you can do so during the onCreateOptionsMenu() callback. You can acquire elements in an action view by calling findItem()with the ID of the menu item, then call getActionView(). For example, the search widget from the above sample is acquired like this:

如果要增加操作視圖的事件調用,可在onCreateOptionMenu()中實現。通過菜單的findItem(ID)獲取菜單項,然後調用getActionView()獲取操作視圖。例如:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.options, menu);
    SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
    // Configure the search info and add any event listeners
    ...
    return super.onCreateOptionsMenu(menu);
}

For more information about using the search widget, see Creating a Search Interface.

Handling collapsible action views 處理可摺疊操作視圖

Action views allow you to provide fast access to rich actions without changing activities or fragments, or replacing the action bar. However, it might not be appropriate to make an action view visible by default. To preserve the action bar space (especially when running on smaller screens), you can collapse your action view into an action item button. When the user selects the button, the action view appears in the action bar. When collapsed, the system might place the item into the overflow menu if you've definedandroid:showAsAction with "ifRoom", but the action view still appears in the action bar when the user selects the item. You can make your action view collapsible by adding "collapseActionView" to the android:showAsAction attribute, as shown in the XML above.

操作視圖在不跟更換activity或fragment的情況下,可以提供快速處理。然後,缺省情況下操作視圖可見也是不合適的。爲了節省action bar空間,可以把操作視圖縮成一個操作按鈕。當用戶選擇該按鈕時,操作視圖才展開。當處於收縮狀態時,如果定義了android:showAsAction="ifRoom"系統有可能把它放到溢出菜單中,然而如果用戶選擇給操作視圖它會顯示在action bar上。你可以給android:showAsAction增加collapseActionView來實現可收縮。

Because the system will expand the action view when the user selects the item, so you do not need to respond to the item in theonOptionsItemSelected callback. The system still calls onOptionsItemSelected() when the user selects it, but the system will always expand the action view unless you return true (indicating you've handled the event instead).

因爲當用戶選擇按鈕時,系統會擴展操作視圖,所以不必再處理onOptionsItemSelected事件。除非該時間飯不會true,否則系統總是展開操作視圖。

The system also collapses your action view when the user selects the "up" icon in the action bar or presses the BACK button.

當用戶選擇“up"圖標或按返回鍵,系統會收縮操作視圖。

If necessary, you can expand or collapse the action view in your own code by calling expandActionView() andcollapseActionView() on the MenuItem.

如果必要,可以通過代碼擴展或收縮操作視圖。在MenuItem上調用expandActionView()或collapseActionView().

Note: Although collapsing your action view is optional, we recommend that you always collapse your action view if it includesSearchView. Also be aware that some devices provide a dedicated SEARCH button and you should expand your search action view if the user presses the SEARCH button. Simply override your activity's onKeyUp() callback method, listen for theKEYCODE_SEARCH event, then call expandActionView().

If you need to update your activity based on the visibility of your action view, you can receive callbacks when it's expanded and collapsed by defining an OnActionExpandListener and registering it with setOnActionExpandListener(). For example:

如果在操作視圖可見或不可見時,需要更新activity,可以定義一個OnActionExpandListener並通過setOnActionExpandListener()來註冊。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.options, menu);
    MenuItem menuItem = menu.findItem(R.id.actionItem);
    ...

    menuItem.setOnActionExpandListener(new OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            // Do something when collapsed
            return true;  // Return true to collapse action view
        }

        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            // Do something when expanded
            return true;  // Return true to expand action view
        }
    });
}

Adding an Action Provider添加Action Provider

Figure 8. Screenshot from the Gallery app, with theShareActionProvider submenu expanded to show share targets.

Similar to an action view, an action provider (defined by the ActionProvider class) replaces an action item with a customized layout, but it also takes control of all the item's behaviors. When you declare an action provider for a menu item in the action bar, it not only controls the appearance of the item in the action bar with a custom layout, but also handles the default event for the menu item when it appears in the overflow menu. It can also provide a submenu from either the action bar or the overflow menu.

和操作視圖類似,一個action provider可以用自定義佈局替換操作項,同時負責控制所有項的行爲。

也可以爲action bar或溢出菜單提供子菜單。

For example, the ShareActionProvider is an extension of ActionProvider that facilitates a “share" action by showing a list of available share targets from the action bar. Instead of using a traditional action item that invokes the ACTION_SEND intent, you can declare an instance ofShareActionProvider to handle an action item. This action provider presents an action view with a drop-down list of applications that handle theACTION_SEND intent, even when the menu item appears in the overflow menu. Hence, when you use an action provider such as this one, you don't have to handle user events on the menu item.


To declare an action provider for an action item, define the android:actionProviderClass attribute for the appropriate the <item> element in yourmenu resource, using the fully-qualified class name of the action provider. For example:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/menu_share"
          android:title="@string/share"
          android:showAsAction="ifRoom"
          android:actionProviderClass="android.widget.ShareActionProvider" />
    ...
</menu>

In this example, the ShareActionProvider is used as the action provider. At this point, the action provider officially takes control of the menu item and handles both its appearance and behavior in the action bar and its behavior in the overflow menu. You must still provide a text title for the item to be used in the overflow menu.

Although the action provider can perform the default action for the menu item when it appears in the overflow menu, your activity (or fragment) can override that behavior by also handling the click event from the onOptionsItemSelected() callback method. If you do not handle the event in that callback, then the action provider receives the onPerformDefaultAction() callback to handle the event. However, if the action provider provides a submenu, then your activity will not receive the onOptionsItemSelected() callback, because the submenu is shown instead of invoking the default menu item behavior when selected.

Using the ShareActionProvider

If you want to provide a "share" action in your action bar by leveraging other applications installed on the device (for example, to share a photo using a messaging or social app), then usingShareActionProvider is an effective way to do so, rather than adding an action item that invokes the ACTION_SEND intent. When you use ShareActionProvider for an action item, it presents an action view with a drop-down list of applications that handle the ACTION_SEND intent (as shown in figure 8).

All the logic for creating the submenu, populating it with share targets, and handling click events (including when the item appears in the overflow menu) is implemented by theShareActionProvider—the only code you need to write is to declare the action provider for the menu item and specify the share intent.

By default, the ShareActionProvider retains a ranking for each share target based on how often the user selects each one. The share targets used more frequently appear at the top of the drop-down list and the target used most often appears directly in the action bar as the default share target. By default, the ranking information is saved in a private file with a name specified by DEFAULT_SHARE_HISTORY_FILE_NAME. If you use the ShareActionProvider or an extension of it for only one type of action, then you should continue to use this default history file and there's nothing you need to do. However, if you use ShareActionProvider or an extension of it for multiple actions with semantically different meanings, then each ShareActionProvidershould specify its own history file in order to maintain its own history. To specify a different history file for the ShareActionProvider, call setShareHistoryFileName() and provide an XML file name (for example, "custom_share_history.xml").

Note: Although the ShareActionProvider ranks share targets based on frequency of use, the behavior is extensible and extensions of ShareActionProvider can perform different behaviors and ranking based on the history file (if appropriate).

To add ShareActionProvider, simply define the android:actionProviderClass attribute with "android.widget.ShareActionProvider", as shown in the XML example above. The only thing left to do is define the Intent you want to use for sharing. To do so, you must call getActionProvider() to retrieve the ShareActionProvider that's associated with a MenuItem, then call setShareIntent().

If the format for the share intent depends on the selected item or other variables that change during the activity lifecycle, you should save the ShareActionProvider in a member field and update it by calling setShareIntent() as necessary. For example:

private ShareActionProvider mShareActionProvider;
...

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.menu_share).getActionProvider();

    // If you use more than one ShareActionProvider, each for a different action,
    // use the following line to specify a unique history file for each one.
    // mShareActionProvider.setShareHistoryFileName("custom_share_history.xml");

    // Set the default share intent
    mShareActionProvider.setShareIntent(getDefaultShareIntent());

    return true;
}
// When you need to update the share intent somewhere else in the app, call
// mShareActionProvider.setShareIntent()

The ShareActionProvider now handles all user interaction with the item and you do not need to handle click events from the onOptionsItemSelected() callback method.

For a sample using the share action provider, see ActionBarShareActionProviderActivity.

Creating a custom action provider

When you want to create an action view that has dynamic behaviors and a default action in the overflow menu, extending ActionProvider to define those behaviors is a good solution. Creating your own action provider offers you an organized and reusable component, rather than handling the various action item transformations and behaviors in your fragment or activity code. As shown in the previous section, Android provides one implementation of ActionProvider for share actions: the ShareActionProvider.

To create your own, simply extend the ActionProvider class and implement its callback methods as appropriate. Most importantly, you should implement the following:

ActionProvider()
This constructor passes you the application Context, which you should save in a member field to use in the other callback methods.
onCreateActionView()
This is where you define the action view for the item. Use the Context acquired from the constructor to instantiate a LayoutInflater and inflate your action view layout from an XML resource, then hook up event listeners. For example:
public View onCreateActionView() {
    // Inflate the action view to be shown on the action bar.
    LayoutInflater layoutInflater = LayoutInflater.from(mContext);
    View view = layoutInflater.inflate(R.layout.action_provider, null);
    ImageButton button = (ImageButton) view.findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // Do something...
        }
    });
    return view;
}
onPerformDefaultAction()
The system calls this when the menu item is selected from the overflow menu and the action provider should perform a default action for the menu item.

However, if your action provider provides a submenu, through the onPrepareSubMenu() callback, then the submenu appears even when the menu item is in the overflow menu. Thus,onPerformDefaultAction() is never called when there is a submenu.

Note: An activity or a fragment that implements onOptionsItemSelected() can override the action provider's default behavior by handling the item-selected event (and returning true), in which case, the system does not call onPerformDefaultAction().

For an example extension of ActionProvider, see ActionBarSettingsActionProviderActivity.

Adding Navigation Tabs 增加導航標籤

Figure 9. Screenshot of action bar tabs from the Honeycomb Gallery app.

Figure 10. Screenshot of tabs in the stacked action bar on a narrow screen.

When you want to provide navigation tabs in an activity, using the action bar's tabs is a great option (instead of using TabWidget), because the system adapts the action bar tabs for different screen sizes—placing them in the main action bar when the screen is sufficiently wide, or in a separate bar (known as the "stacked action bar") when the screen is too narrow, as shown in figures 9 and 10.

當想要在activity中提供導航標籤時,可以使用action bar的標籤,系統自動調整action bar標籤,屏幕足夠大時,放在主action bar上,屏幕太窄時,放到單獨的標籤行上。

To switch between fragments using the tabs, you must perform a fragment transaction each time a tab is selected. If you're not familiar with how to change fragments using FragmentTransaction, first read theFragments developer guide.

使用標籤切換不同的fragment,你每次選擇標籤時,必須執行fragement轉換。如果不熟悉使用FragmentTrasaction切換fragment,請先閱讀Fragments開發指南。

To get started, your layout must include a ViewGroup in which you place each Fragment associated with a tab. Be sure the ViewGrouphas a resource ID so you can reference it from your tab-swapping code. Alternatively, if the tab content will fill the activity layout (excluding the action bar), then your activity doesn't need a layout at all (you don't even need to call setContentView()). Instead, you can place each fragment in the default root ViewGroup, which you can refer to with the android.R.id.content ID (you can see this ID used in the sample code below, during fragment transactions).

首先,佈局文件必須包括ViewGroup,在其中放置每個標籤對應的Fragment。ViewGroup要有一個資源ID,可以在標籤切換時引用它。如果標籤內容充滿真個activity,activity不需要佈局文件。把每個fragment放到根ViewGroup,你可以使用android.R.id.content來引用ViewGroup.

Once you determine where the fragments appear in the layout, the basic procedure to add tabs is:

決定fragment出現在哪裏之後,添加標籤的步驟如下:

  1. Implement the ActionBar.TabListener interface. Callbacks in this interface respond to user events on the tabs so you can swap fragments.實現ActionBar.TabListener接口,對用戶在標籤上的操作做出反應,可以用來切換fragment.
  2. For each tab you want to add, instantiate an ActionBar.Tab and set the ActionBar.TabListener by calling setTabListener(). Also set the tab's title and/or icon with setText()and/or setIcon().每個要添加的頁籤,實例化ActionBar.Tab然後通過setTabListenter()設置ActionBar.TabListener.還要通過setText(),setIcon()設置標題和圖標。
  3. Add each tab to the action bar by calling addTab().通過addTab()將標籤添加到action bar.

When looking at the ActionBar.TabListener interface, notice that the callback methods provide only the ActionBar.Tab that was selected and a FragmentTransaction for you to perform fragment transactions—it doesn't say anything about what fragment you should swap in or out. Thus, you must define your own association between each ActionBar.Tab and the appropriate Fragment that it represents (in order to perform the appropriate fragment transaction). There are several ways you can define the association, depending on your design. In the example below, the ActionBar.TabListener implementation provides a constructor such that each new tab uses its own instance of the listener. Each instance of the listener defines several fields that are necessary to later perform a transaction on the appropriate fragment.

觀察一下ActionBar.TabListener接口,你會注意到該方法只提供了選中的ActionBar.Tab和執行fragment轉換的FragmentTransaction兩個參數。FratmentTransaction沒有指明顯示和消失的Fragment,因此,必須自己定義ActionBar.Tab和Fragment之間的聯繫。有幾種定義的方法,可根據設計進行選擇。在下面的例子中,ActionBar.TabListener的實現提供了一個構造器,每個新標籤使用一個自己的監聽器實例。每個監聽器實例定義了幾個必須的屬性字段,在以後執行fragment轉換時使用。

For example, here's how you might implement the ActionBar.TabListener such that each tab uses its own instance of the listener:

例子,如何實現ActionBar.TabListener,每個標籤使用自己的監聽器實例:

public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
    private Fragment mFragment;
    private final Activity mActivity;
    private final String mTag;
    private final Class<T> mClass;

    /** Constructor used each time a new tab is created. 構造器
      * @param activity  The host Activity, used to instantiate the fragment 
      * @param tag  The identifier tag for the fragment 
      * @param clz  The fragment's Class, used to instantiate the fragment
      */
    public TabListener(Activity activity, String tag, Class<T> clz) {
        mActivity = activity;
        mTag = tag;
        mClass = clz;
    }

    /* The following are each of the ActionBar.TabListener callbacks */

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // Check if the fragment is already initialized
        if (mFragment == null) {
            // If not, instantiate and add it to the activity
            mFragment = Fragment.instantiate(mActivity, mClass.getName());
            ft.add(android.R.id.content, mFragment, mTag);
        } else {
            // If it exists, simply attach it in order to show it
            ft.attach(mFragment);
        }
    }

    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        if (mFragment != null) {
            // Detach the fragment, because another one is being attached
            ft.detach(mFragment);
        }
    }

    public void onTabReselected(Tab tab, FragmentTransaction ft) {
        // User selected the already selected tab. Usually do nothing.
    }
}

Caution: You must not call commit() for the fragment transaction in each of these callbacks—the system calls it for you and it may throw an exception if you call it yourself. You also cannot add these fragment transactions to the back stack.

In this example, the listener simply attaches (attach()) a fragment to the activity layout—or if not instantiated, creates the fragment and adds (add()) it to the layout (as a child of theandroid.R.id.content view group)—when the respective tab is selected, and detaches (detach()) it when the tab is unselected.

在這個例子中,當標籤選中時,監聽器簡單的添加fragment到activity--如果沒有實例化,創建一個fragment然後添加到佈局中(作爲android.R.id.content視圖組的一個子視圖)。當標籤未選中時拆卸。

The ActionBar.TabListener implementation is the bulk of the work. All that remains is to create each ActionBar.Tab and add it to the ActionBar. Additionally, you must callsetNavigationMode(NAVIGATION_MODE_TABS) to make the tabs visible. You might also want to disable the activity title by calling setDisplayShowTitleEnabled(false) if the tab titles actually indicate the current view.

ActionBar.TabListener實現是一大塊工作。需要創建每個ActionBar.Tab然後添加到ActionBar。另外,必須調用setNavigationMode(NAVIGRTION_MODE_TABS)使標籤可見。如果標籤標題已經指明當前視圖,也可以通過setDisplayShowTitleEnabled(false)隱藏activity標題。

For example, the following code adds two tabs using the listener defined above:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Notice that setContentView() is not used, because we use the root
    // android.R.id.content as the container for each fragment

    // setup action bar for tabs
    ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
    actionBar.setDisplayShowTitleEnabled(false);

    Tab tab = actionBar.newTab()
            .setText(R.string.artist)
            .setTabListener(new TabListener<ArtistFragment>(
                    this, "artist", ArtistFragment.class));
    actionBar.addTab(tab);

    tab = actionBar.newTab()
        .setText(R.string.album)
        .setTabListener(new TabListener<AlbumFragment>(
                this, "album", AlbumFragment.class));
    actionBar.addTab(tab);
}

Note: The above implementation for ActionBar.TabListener is one of several possible techniques. You can see more of this style in the API Demos app.

注意:上面個的ActionBar.TabListener的實現是幾種技術之一。你可以在API Demos中看到更多方法。

If your activity stops, you should retain the currently selected tab with the saved instance state so you can open the appropriate tab when the user returns. When it's time to save the state, you can query the currently selected tab with getSelectedNavigationIndex(). This returns the index position of the selected tab.

如果activity關閉,你應該保留當前選中的標籤,以便用戶回來時打開相應的標籤。在保存狀態時,可以通過getSelectedNavigationIndex()查詢當前選中的標籤,它返回選中標籤的索引號。

Caution: It's important that you save the state of each fragment as necessary, so that when users switch fragments with the tabs and then return to a previous fragment, it looks the way it did when they left. For information about saving the state of your fragment, see the Fragments developer guide.

Note: In some cases, the Android system will show your action bar tabs as a drop-down list in order to ensure the best fit in the action bar.

As another mode of navigation (or filtering) within your activity, the action bar offers a built in drop-down list. For example, the drop-down list can offer different modes by which content in the activity is sorted.

在Activity中另一種導航,ActionBar提供內置的下拉列表。例如,下拉列表可以提供不同的模式的排序。

The basic procedure to enable drop-down navigation is:

使用下拉導航的基本過程:

  1. Create a SpinnerAdapter that provides the list of selectable items for the drop-down and the layout to use when drawing each item in the list.  創建一個SpinnerAdapter,提供下拉可選項及列表佈局。
  2. Implement ActionBar.OnNavigationListener to define the behavior that occurs when the user selects an item from the list. 實現ActionBar.OnNavigationListener定義用戶選擇列表後的行爲。
  3. Enable navigation mode for the action bar with setNavigationMode(). For example: 使用setNavigationMode()設定ActionBar爲下拉模式。例如:
  4. ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

    Note: You should perform this during your activity's onCreate() method.

  5. Set the callback for the drop-down list with setListNavigationCallbacks(). For example: 調用setListNavigationCallbacks()設置下拉的回調方法。
    actionBar.setListNavigationCallbacks(mSpinnerAdapter, mNavigationCallback);

    This method takes your SpinnerAdapter and ActionBar.OnNavigationListener.

That's the basic setup. However, implementing the SpinnerAdapter and ActionBar.OnNavigationListener is where most of the work is done. There are many ways you can implement these to define the functionality for your drop-down navigation and implementing various types of SpinnerAdapter is beyond the scope of this document (you should refer to theSpinnerAdapter class reference for more information). However, below is a simple example for a SpinnerAdapter and ActionBar.OnNavigationListener to get you started (click the title to reveal the sample).

這是基本的設置。然而,實現SpinnerAdapter和ActionBar.OnNavigationListener有大量工作要做。下面是一個簡單的例子。

Styling the Action Bar 風格化ActionBar

If you've implemented a custom design for the widgets in your application, you might also want to redesign some of the action bar to match your app design. To do so, you need to use Android's style and theme framework to restyle the action bar using special style properties.

如果曾經客戶化控件,你也許想重新設計actionBar的一些屬性來適用自己的應用。你需要適用style和theme框架,風格化actionBar的一些屬性。

Note: In order for background images to change appearance depending on the current button state (selected, pressed, unselected), the drawable resource you use must be a state list drawable.

Caution: For all background drawables you provide, be sure to use Nine-Patch drawables to allow stretching. The Nine-Patch image should be smaller than 40px tall and 30px wide (for the mdpi asset).

General appearance 

android:windowActionBarOverlay
Declares whether the action bar should overlay the activity layout rather than offset the activity's layout position (for example, the Gallery app uses overlay mode). This is false by default.

Normally, the action bar requires its own space on the screen and your activity layout fills in what's left over. When the action bar is in overlay mode, your activity layout uses all the available space and the system draws the action bar on top. Overlay mode can be useful if you want your content to keep a fixed size and position when the action bar is hidden and shown. You might also like to use it purely as a visual effect, because you can use a semi-transparent background for the action bar so the user can still see some of your activity layout behind the action bar.

正常情況下,actionBar佔用自己的空間,Activity佔用剩餘的空間。當actionBar在overlay模式,activity使用所有可用空間,系統把actionBar畫在activity的上部。overlay模式可以是activity內容保持固定大小和位置,無論actionBar是隱藏還是顯示。也可以看做是一種視覺效果,可以使actionbar的背景半透明,用戶可以看到actionBar後面的窗體。

Note: The Holo theme families draw the action bar with a semi-transparent background by default. However, you can modify it with your own styles and the DeviceDefault theme on different devices might use an opaque background by default.

When overlay mode is enabled, your activity layout has no awareness of the action bar laying on top of it. So, you must be careful not to place any important information or UI components in the area overlayed by the action bar. If appropriate, you can refer to the platform's value for actionBarSize to determine the height of the action bar, by referencing it in your XML layout. For example:

使用overlay模式時,activity不會感知到actionBar的存在。所以,不要把重要的信息或UI控件放在actionBar區域。可以引用Android平臺的值actionBarSize來決定actionbar的高度,可以在xml佈局文件用引用。例如:

<SomeView
    ...
    android:layout_marginTop="?android:attr/actionBarSize" />

You can also retrieve the action bar height at runtime with getHeight(). This reflects the height of the action bar at the time it's called, which might not include the stacked action bar (due to navigation tabs) if called during early activity lifecycle methods. To see how you can determine the total height at runtime, including the stacked action bar, see theTitlesFragment class in the Honeycomb Gallery sample app.


Action items 操作項

android:actionButtonStyle
Defines a style resource for the action item buttons. 
android:actionBarItemBackground
Defines a drawable resource for each action item's background. (Added in API level 14.)
android:itemBackground
Defines a drawable resource for each overflow menu item's background.
android:actionBarDivider
Defines a drawable resource for the divider between action items. (Added in API level 14.)
android:actionMenuTextColor
Defines a color for text that appears in an action item.
android:actionMenuTextAppearance
Defines a style resource for text that appears in an action item.
android:actionBarWidgetTheme
Defines a theme resource for widgets that are inflated into the action bar as action views. (Added in API level 14.)
android:actionBarTabStyle
Defines a style resource for tabs in the action bar.
android:actionBarTabBarStyle
Defines a style resource for the thin bar that appears below the navigation tabs.
android:actionBarTabTextStyle
Defines a style resource for text in the navigation tabs.
android:actionDropDownStyle
Defines a style for the drop-down navigation (such as the background and text styles).

For example, here's a file that defines a few custom styles for the action bar:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
        <item name="android:actionBarTabTextStyle">@style/CustomTabTextStyle</item>
        <item name="android:actionBarDivider">@drawable/ab_divider</item>
        <item name="android:actionBarItemBackground">@drawable/ab_item_background</item>
    </style>

    <!-- style for the action bar tab text -->
    <style name="CustomTabTextStyle" parent="@android:style/TextAppearance.Holo">
        <item name="android:textColor">#2456c2</item>
    </style>
</resources>

Note: Be certain that your theme declares a parent theme in the <style> tag, from which it inherits all styles not explicitly declared by your theme. When modifying the action bar, using a parent theme is important so that you can simply override the action bar styles you want to change without re-implementing the styles you want to leave alone (such as text appearance or padding in action items).

You can apply your custom theme to the entire application or to individual activities in your manifest file like this:

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

For more information about using style and theme resources in your application, read Styles and Themes.

Advanced styling

If you need more advanced styling for the action bar than is available with the properties above, you can include android:actionBarStyle and android:actionBarSplitStyle in your activity's theme. Each of these specifies another style that can define various properties for the action bar, including different backgrounds with android:background,android:backgroundSplit, and android:backgroundStacked. If you override these action bar styles, be sure that you define a parent action bar style such as Widget.Holo.ActionBar.

For example, if you want to change the action bar's background, you can use the following styles:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- the theme applied to the application or activity -->
    <style name="CustomActivityTheme" parent="@android:style/Theme.Holo">
        <item name="android:actionBarStyle">@style/MyActionBar</item>
        <!-- other activity and action bar styles here -->
    </style>

    <!-- style for the action bar backgrounds -->
    <style name="MyActionBar" parent="@android:style/Widget.Holo.ActionBar">
        <item name="android:background">@drawable/ab_background</item>
        <item name="android:backgroundStacked">@drawable/ab_background</item>
        <item name="android:backgroundSplit">@drawable/ab_split_background</item>
    </style>
</resources>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章