译--ToolBar(二)

来源:互联网 发布:淘宝店铺如何排名靠前 编辑:程序博客网 时间:2024/06/14 23:25

增加Handing Actions

app bar 允许用户自己增加action,可以把比较重要的action放在app bar的右边,例如,一个相册应用可以在app bar上增加分享和创建相簿的
action,这样用户在浏览照片的时候就可以直接点击app bar上的按钮来对照片进行操作。

app bar的空间是有限的,如果定义的action超过了app bar可以容纳的最大数,这些action就会被放入overflow menu中,当然,action也可以
被设置为只在overflow中显示。


样例1.带有一个action和一个overflow的toolbar。

增加Action Buttons

不论是在app bar上直接显示的,还是在overflow中的action button都是在menu resource中定义的,想要创建一个action,
首先要在res/menu/目录下创建一个xml文件。

下面是一个xml例子:

<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>

app:showAsAction属性定义了action在app bar上的显示方式,如果设置为app:showAsAction="ifRoom",就代表如果app bar上面有空间,
就进行显示,如果没有空间,就放在overflow中显示(默认在overflow中只显示title);如果设置为app:showAsAction="never"
就表示此action将总是显示在overflow中。

系统使用action icon作为action button显示在app bar上,你可以在Material Icons
找到很多有用的icons.

对Actions做出响应

当用户点击app bar上的一个action的时候,系统会调用activity的onOptionsItemSelected()回调方法,并且通过MeunItem
对象来表明哪一个action被点击,在onOptionsItemSelected()中,调用MenuItem.getItemId()方法来确定被点击的action,
此方法返回的ID就是你在<item>中为android:id定义的值。

例如,下面的代码检查了哪一个action被点击,用过没有辨别出来用户点击的那个action,就会调用父类中的方法:

@Overridepublic 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);    }}

该文章翻译自android官方文档,绝对忠于原著,无删改,如有错误,敬请指正!

译–ToolBar(三)

0 0
原创粉丝点击