前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Android AppBar

Android AppBar

作者头像
用户1172465
发布2018-01-08 13:31:38
8990
发布2018-01-08 13:31:38
举报
文章被收录于专栏:everhadeverhad

AppBar官方文档摘记 2016-6-12

本文摘自Android官方文档,为方便自己及其他开发者朋友阅读。 章节目录为“Develop > Training > Best Practices for User Interface > Adding the App Bar”。

Adding the App Bar

App Bar是谷歌推荐的为应用带来统一外观和一致导航的UI设计元素,已有的Action Bar就是早先SDK中引入的实现。但Action Bar的引入最初没有很好的考虑兼容问题,随着不同系统版本逐渐增加特性完善起来,在不同主题会有不同的显示效果。简而言之,就是兼容性不好,API的设计也比较散乱。而Tool Bar的推出,以独立纯净的支持库的形式提供了App Bar需要的所有特性,这样,可以在最大范围的设备上表现出这一最新的UI设计,API得到统一,而且提供更好的定制。

App Bar的UI表现
App Bar的UI表现

The app bar, also known as the action bar, is one of the most important design elements in your app's activities, because it provides a visual structure and interactive elements that are familiar to users. Using the app bar makes your app consistent with other Android apps, allowing users to quickly understand how to operate your app and have a great experience. The key functions of the app bar are as follows:

  • 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).

This class describes how to use the v7 appcompat support library's Toolbar widget as an app bar. There are other ways to implement an app bar—for example, some themes set up an ActionBar as an app bar by default—but using the appcompat Toolbar makes it easy to set up an app bar that works on the widest range of devices, and also gives you room to customize your app bar later on as your app develops.

You should also read 1.Implementing Effective Navigation 2.Material Design: App Bar

关于APPBar的使用,有4个课程:

  1. Setting Up the App Bar Learn how to add a Toolbar widget to your activity, and set it as the activity's app bar.
  2. Adding and Handling Actions Learn how to add actions to the app bar and its overflow menu, and how to respond when users choose those actions.
  3. Adding an Up Action Learn how to add an Up button to your app bar, so users can navigate back to the app's home screen.
  4. Action Views and Action Providers Learn how to use these widgets to provide advanced functionality in your app bar.

1. Setting Up the App Bar

Learn how to add a Toolbar widget to your activity, and set it as the activity's app bar.

In its most basic form, the action bar displays the title for the activity on one side and an overflow menu on the other. Even in this simple form, the app bar provides useful information to the users, and helps to give Android apps a consistent look and feel.

Figure 1. An app bar with the app title and overflow menu.
Figure 1. An app bar with the app title and overflow menu.

Beginning with Android 3.0 (API level 11), all activities that use the default theme have an ActionBar as an app bar. However, app bar features have gradually been added to the native ActionBar over various Android releases. As a result, the native ActionBar behaves differently depending on what version of the Android system a device may be using. By contrast, the most recent features are added to the support library's version of Toolbar, and they are available on any device that can use the support library.

For this reason, you should use the support library's Toolbar class to implement your activities' app bars. Using the support library's toolbar helps ensure that your app will have consistent behavior across the widest range of devices. For example, the Toolbar widget provides a material design experience on devices running Android 2.1 (API level 7) or later, but the native action bar doesn't support material design unless the device is running Android 5.0 (API level 21) or later.

1.1 Add a Toolbar to an Activity

These steps describe how to set up a Toolbar as your activity's app bar:

  1. Add the v7 appcompat support library to your project, as described in Support Library Setup.
  2. Make sure the activity extends AppCompatActivity:
代码语言:javascript
复制
public class MyActivity extends AppCompatActivity {
  // ...
}

Note: Make this change for every activity in your app that uses a Toolbar as an app bar.

  1. In the app manifest, set the <application> element to use one of appcompat's NoActionBar themes. Using one of these themes prevents the app from using the native ActionBar class to provide the app bar. For example:
代码语言:javascript
复制
<application
    android:theme="@style/Theme.AppCompat.Light.NoActionBar"
    />
  1. Add a Toolbar to the activity's layout. For example, the following layout code adds a Toolbar and gives it the appearance of floating above the activity: <android.support.v7.widget.Toolbar android:id="@+id/my_toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:elevation="4dp" android:theme="@style/ThemeOverlay.AppCompat.ActionBar" app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/> The Material Design specification recommends that app bars have an elevation of 4 dp. Position the toolbar at the top of the activity's layout, since you are using it as an app bar.
  2. In the activity's onCreate() method, call the activity's setSupportActionBar() method, and pass the activity's toolbar. This method sets the toolbar as the app bar for the activity. For example:
代码语言:javascript
复制
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);
    Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolbar);
    }

Your app now has a basic action bar. By default, the action bar contains just the name of the app and an overflow menu. The options menu initially contains just the Settings item. You can add more actions to the action bar and the overflow menu, as described in Adding and Handling Actions.

1.2 Use App Bar Utility Methods

Once you set the toolbar as an activity's app bar, you have access to the various utility methods provided by the v7 appcompat support library's ActionBar class. This approach lets you do a number of useful things, like hide and show the app bar.

To use the ActionBar utility methods, call the activity's getSupportActionBar() method. This method returns a reference to an appcompat ActionBar object. Once you have that reference, you can call any of the ActionBar methods to adjust the app bar. For example, to hide the app bar, call ActionBar.hide().

2. Adding and Handling Actions

The app bar allows you to add buttons for user actions. This feature lets you put the most important actions for the current context right at the top of the app. For example, a photo browsing app might show share and create album buttons at the top when the user is looking at their photo roll; when the user looks at an individual photo, the app might show crop and filter buttons.

Space in the app bar is limited. If an app declares more actions than can fit in the app bar, the app bar send the excess actions to an overflow menu. The app can also specify that an action should always be shown in the overflow menu, instead of being displayed on the app bar.

2.1 Add Action Buttons

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, as shown in this code example of a menu XML file:

代码语言:javascript
复制
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <!-- "Mark Favorite", should appear as action button if possible -->
    <item
        android:id="@+id/action_favorite"
        android:icon="@drawable/ic_favorite_black_48dp"
        android:title="@string/action_favorite"
        app:showAsAction="ifRoom"/>

    <!-- Settings, should always be in the overflow -->
    <item android:id="@+id/action_settings"
          android:title="@string/action_settings"
          app:showAsAction="never"/>

</menu>

The app:showAsAction attribute specifies whether the action should be shown as a button on the app bar. If you set app:showAsAction="ifRoom" (as in the example code's favorite action), the action is displayed as a button if there is room in the app bar for it; if there is not enough room, excess actions are sent to the overflow menu. If you set app:showAsAction="never" (as in the example code's settings action), the action is always listed in the overflow menu, not displayed in the app bar.

The system uses the action's icon as the action button if the action is displayed in the app bar. You can find many useful icons on the Material Icons page

2.2 Respond to Actions

When the user selects one of the app bar items, the system calls your activity's onOptionsItemSelected() callback method, and passes a MenuItem object to indicate which item was clicked. In your implementation of onOptionsItemSelected(), call the MenuItem.getItemId() method to determine which item was pressed. The ID returned matches the value you declared in the corresponding <item> element's android:id attribute.

For example, the following code checks to see which action the user selected. If the method does not recognize the user's action, it invokes the superclass method:

代码语言:javascript
复制
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.action_settings:
            // User chose the "Settings" item, show the app settings UI...
            return true;

        case R.id.action_favorite:
            // User chose the "Favorite" action, mark the current item
            // as a favorite...
            return true;

        default:
            // If we got here, the user's action was not recognized.
            // Invoke the superclass to handle it.
            return super.onOptionsItemSelected(item);

    }
}

3. Adding an Up Action

Your app should make it easy for users to find their way back to the app's main screen. One simple way to do this is to provide an Up button on the app bar for all activities except the main one. When the user selects the Up button, the app navigates to the parent activity.

This lesson shows you how to add an Up button to an activity by declaring the activity's parent in the manifest, and enabling the app bar's Up button.

3.1 Declare a Parent Activity

To support the up functionality in an activity, you need to declare the activity's parent. You can do this in the app manifest, by setting an android:parentActivityName attribute.

The android:parentActivityName attribute was introduced in Android 4.1 (API level 16). To support devices with older versions of Android, define a <meta-data> name-value pair, where the name is "android.support.PARENT_ACTIVITY" and the value is the name of the parent activity.

For example, suppose your app has a main activity named MainActivity and a single child activity. The following manifest code declares both activities, and specifies the parent/child relationship:

代码语言:javascript
复制
<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.MyChildActivity"
        android:label="@string/title_activity_child"
        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>

3.2 Enable the Up Button

To enable the Up button for an activity that has a parent activity, call the app bar's setDisplayHomeAsUpEnabled() method. Typically, you would do this when the activity is created. For example, the following onCreate() method sets a Toolbar as the app bar for MyChildActivity, then enables that app bar's Up button:

代码语言:javascript
复制
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_child);

    // my_child_toolbar is defined in the layout file
    Toolbar myChildToolbar =
        (Toolbar) findViewById(R.id.my_child_toolbar);
    setSupportActionBar(myChildToolbar);

    // Get a support ActionBar corresponding to this toolbar
    ActionBar ab = getSupportActionBar();

    // Enable the Up button
    ab.setDisplayHomeAsUpEnabled(true);
}

You do not need to catch the up action in the activity's onOptionsItemSelected() method. Instead, that method should call its superclass, as shown in Respond to Actions. The superclass method responds to the Up selection by navigating to the parent activity, as specified in the app manifest.

4. Action Views and Action Providers

对于App Bar,除了Up Button,Popup MenuItem和Action Button之外,ToolBar提供了2种额外途径来定制App Bar。Action View可以指定显示在App Bar中的View,处理View的展开和收起等逻辑。Action Provider更灵活些,允许自定义UI布局,处理所有点击事件,弹出的菜单列表等。可以使用它为整个app提供统一头布局,如顶部多级标题。可以结合android.support.v7.widget.SearchView和android.support.v7.widget.ShareActionProvider的源码来了解两者的不同。

The v7 appcompat support library Toolbar provides several different ways for users to interact with your app. Previous lessons described how to define an action, which can be either a button or a menu item. This lesson describes how to add two versatile components:

  • An action view is an action that provides rich functionality within the app bar. For example, a search action view allows the user to type their search text in the app bar, without having to change activities or fragments.
  • An action provider is an action with its own customized layout. The action initially appears as a button or menu item, but when the user clicks the action, the action provider controls the action's behavior in any way you want to define. For example, the action provider might respond to a click by displaying a menu.

The Android support libraries provide several specialized action view and action provider widgets. For example, the SearchView widget implements an action view for entering search queries, and the ShareActionProvider widget implements an action provider for sharing information with other apps. You can also define your own action views and action providers.

4.1 Add an Action View

To add an action view, create an element in the toolbar's menu resource, as Add Action Buttons describes. Add one of the following two attributes to the element:

  • actionViewClass: The class of a widget that implements the action.
  • actionLayout: A layout resource describing the action's components.

Set the showAsAction attribute to either "ifRoom|collapseActionView" or "never|collapseActionView". The collapseActionView flag indicates how to display the widget when the user is not interacting with it: If the widget is on the app bar, the app should display the widget as an icon. If the widget is in the overflow menu, the app should display the widget as a menu item. When the user interacts with the action view, it expands to fill the app bar.

For example, the following code adds a SearchView widget to the app bar:

代码语言:javascript
复制
<item android:id="@+id/action_search"
     android:title="@string/action_search"
     android:icon="@drawable/ic_search"
     app:showAsAction="ifRoom|collapseActionView"
     app:actionViewClass="android.support.v7.widget.SearchView" />

If the user is not interacting with the widget, the app displays the widget as the icon specified by android:icon. (If there is not enough room in the app bar, the app adds the action to the overflow menu.) When the user taps the icon or menu item, the widget expands to fill the toolbar, allowing the user to interact with it.

Figure 1. When the user clicks an action view's icon, the view's UI fills the toolbar.
Figure 1. When the user clicks an action view's icon, the view's UI fills the toolbar.

If you need to configure the action, do so in your activity's onCreateOptionsMenu() callback. You can get the action view's object reference by calling the static getActionView() method. For example, the following code gets the object reference for the SearchView widget defined in the previous code example:

代码语言:javascript
复制
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main_activity_actions, menu);

    MenuItem searchItem = menu.findItem(R.id.action_search);
    SearchView searchView =
            (SearchView) MenuItemCompat.getActionView(searchItem);

    // Configure the search info and add any event listeners...

    return super.onCreateOptionsMenu(menu);
}

4.2 Responding to action view expansion

If the action's <item> element has a collapseActionView flag, the app displays the action view as an icon until the user interacts with the action view. When the user clicks on the icon, the built-in handler for onOptionsItemSelected() expands the action view. If your activity subclass overrides the onOptionsItemSelected() method, your override method must call super.onOptionsItemSelected() so the superclass can expand the action view.

If you want to do something when the action is expanded or collapsed, you can define a class that implements MenuItem.OnActionExpandListener, and pass a member of that class to setOnActionExpandListener(). For example, you might want to update the activity based on whether an action view is expanded or collapsed. The following snippet shows how to define and pass a listener:

代码语言:javascript
复制
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.options, menu);
    // ...

    // Define the listener
    OnActionExpandListener expandListener = new OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            // Do something when action item collapses
            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
        }
    };

    // Get the MenuItem for the action item
    MenuItem actionMenuItem = menu.findItem(R.id.myActionItem);

    // Assign the listener to that action item
    MenuItemCompat.setOnActionExpandListener(actionMenuItem, expandListener);

    // Any other things you have to do when creating the options menu…

    return true;
}

4.3 Add an Action Provider

To declare an action provider, create an <item> element in the toolbar's menu resource, as described in Add Action Buttons. Add an actionProviderClass attribute, and set it to the fully qualified class name for the action provider class.

For example, the following code declares a ShareActionProvider, which is a widget defined in the support library that allows your app to share data with other apps:

代码语言:javascript
复制
<item android:id="@+id/action_share"
    android:title="@string/share"
    app:showAsAction="ifRoom"
    app:actionProviderClass="android.support.v7.widget.ShareActionProvider"/>

In this case, it is not necessary to declare an icon for the widget, since ShareActionProvider provides its own graphics. If you are using a custom action, declare an icon.

For information about creating a custom action provider, see the ActionProvider reference. For information about configuring a ShareActionProvider, see the reference for that class.

总结

文章简单的把Google官方的Android开发文档中的介绍App Bar的部分进行了摘取,整理为markdown文章。 以上4节对ToolBar的使用进行了入门级介绍。更多关于AppBar的高级话题,以后再继续整理。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-06-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • AppBar官方文档摘记 2016-6-12
  • Adding the App Bar
  • 1. Setting Up the App Bar
    • 1.1 Add a Toolbar to an Activity
      • 1.2 Use App Bar Utility Methods
      • 2. Adding and Handling Actions
        • 2.1 Add Action Buttons
          • 2.2 Respond to Actions
          • 3. Adding an Up Action
            • 3.1 Declare a Parent Activity
              • 3.2 Enable the Up Button
              • 4. Action Views and Action Providers
                • 4.1 Add an Action View
                  • 4.2 Responding to action view expansion
                    • 4.3 Add an Action Provider
                    • 总结
                    领券
                    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档