Android - ToolBar详解

原码下载地址:

2014 的 google i/o 发表令多数人为之一亮的 material design,而 google 也从「google i/o 2014」 开始,
大家也陆陆续续地看到其更新的 android app 皆套用了这个设计介面。
当然,这个设计介面著实让大家感到惊艳外,更让 android 开发者开始担心未来 app 的界面处理了。

不过,所幸有着之前 actionbar 的经验后,android 也很快地在 support library 里面提供了相对应的 api 给开发者使用,
本篇就为各位介绍 – toolbar,这是用来取代过去 actionbar 的控件,而现在于 material design 中也对之有一个统一名称:app bar,
在未来的 android app 中,就以 toolbar 这个元件来实作之。

  1. 概述
    Android 3.0 Android 推了 ActionBar 这个控件,而到了2013 年 Google 开始大力地推动所谓的 android style,
    想要逐渐改善过去 android 纷乱的界面设计,希望让终端使用者尽可能在 android 手机有个一致的操作体验。
    ActionBar 过去最多人使用的两大套件就是 ActionBarSherlock 以及官方提供在 support library v 7 里的 AppCompat。

    既然会有本篇跟各位介绍的 Toolbar,也意味着官方在某些程度上认为 ActionBar 限制了 android app 的开发与设计的弹性,
    而在 material design 也对之做了名称的定义:App bar。
    接下来将为各位分成几个阶段进行说明,如何在 android app 中用 toolbar 这个控件来做出一个基本的 app bar 喽。
    总揽:
    这里写图片描述

2.基础套用
这个阶段分为3个部分:

风格 (style)
界面 (layout)
程序 (java)

2.1 风格(style)

风格要调整的地方有二

一在 res/values/styles.xml中

二在 /res/values-v21/styles.xml中 (API >=21 也就是5.0及以上)

为了之后设定方便,我们先在 res/values/styles.xml 里增加一个名为 AppTheme.Base的风格

res/values/styles.xml
<style name="AppTheme.Base" parent="Theme.AppCompat">
    <item name="windowActionBar">false</item>
    <item name="android:windowNoTitle">true</item>
</style>

因为此范例只使用 Toolbar,所以我们要将让原本的 ActionBar 隐藏起来,
然后将原本 AppTheme 的 parent 属性 改为上面的AppTheme.Base,代码如下:

res/values/styles.xml
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="AppTheme.Base">
    </style>

    <style name="AppTheme.Base" parent="Theme.AppCompat">
        <!--ActionBar隐藏,这里使用ToolBar-->
        <item name="windowActionBar">false</item>

        <del><item name="android:windowNoTitle">true</item></del>
        <!-- 使用 API Level 22 編譯的話,要拿掉前綴字 -->
        <item name="windowNoTitle">true</item>
    </style>
</resources>

再来调整Android 5.0的style: /res/values-v21/styles.xml,也将其 parent 属性改为 AppTheme.Base:

res/values-v21/styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
    </style>
</resources>

2.2界面(Layout)
在 activity_main.xml 里面添加 Toolbar 控件:

activity_main.xml
<!-- ?attr/actionBarSize -> toolbar的高度是原先的actionbar的高度 -->
<android.support.v7.widget.Toolbar
     android:id="@+id/toolbar"
     android:layout_height="?attr/actionBarSize"
     android:layout_width="match_parent" >  
</android.support.v7.widget.Toolbar>

(1)android.support.v7依赖 moduled右击/open module setting/Dependencies/右边+号/library dependencies/选择v7
(2)请记得用 support v7 里的 toolbar,不然然只有 API Level 21 也就是 Android 5.0 以上的版本才能使用。
(3)这里需注意,要将 RelatvieLayout 里的四个方向的padding 属性去掉,并记得将原本的 Hello World 设为 layout_below=”@+id/toolbar” ,
否则会看到像下面这样的错误画面:
toobar.blog2 (后续贴上)

2.3 程序 (Java)
在 MainActivity.java 中加入 Toolbar 的声明:

MainActivity.java/onCreate()

mToolbar = (Toolbar) findViewById(R.id.toolbar);
// 取代原本的actionbar
// 使用该方法的时候MainActivity需要继承于AppCompatActivity
setSupportActionBar(toolbar);

声明后,再将之用 setSupportActionBar 设定,Toolbar即能取代原本的 actionbar 了,此阶段完成画面如下:
toolbar.blog3(后续补上)

  1. 自定义颜色(Customization color)

toolbar.blog4
上图是将本阶段要完成的结果画面做了标示,结合下面的描述希望大家能明白。

属性介绍:
(1)colorPrimaryDark(状态栏底色):在风格 (styles) 或是主题 (themes) 里进行设定。

(2)App bar底色 这个设定分为二,
1’若你的 android app 仍是使用 actionbar ,则直接在风格 (styles) 或是主题 (themes) 里进行设定 colorPrimary 参数即可;
2’若是采用 toolbar 的话,则要在界面 (layout) 里面设定 toolbar 控件的 background 属性。

(3)navigationBarColor(导航栏底色)
仅能在 API v21 也就是 Android 5 以后的版本中使用, 因此要将之设定在 res/values-v21/styles.xml 里面。

(4)windowBackground - 主视窗底色

因此这个阶段,我们需要做的设定有三个地方

res/values/styles.xml  (追加状态栏以及Window的底色)

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="AppTheme.Base">
    </style>

    <style name="AppTheme.Base" parent="Theme.AppCompat">
        <!-- 将ActionBar隐藏,这里使用ToolBar-->
        <item name="windowActionBar">false</item>

        <del><item name="android:windowNoTitle">true</item></del>
        <!-- 使用 API Level 22 編譯的話,要拿掉前綴字 -->
        <item name="windowNoTitle">true</item>

+       <!--Status bar color-->
+       <item name="colorPrimaryDark">@color/accent_material_light</item>

+       <!-- Actionbar color -->
+       <!-- 若是使用的是ActionBar,colorPrimary属性就够了;  但是若是ToolBar 还需要在toolbar 控件中设置background 属性 -->
+       <item name="colorPrimary">@color/accent_material_dark</item>

+       <!-- Window color-->
+       <item name="android:windowBackground">@color/dim_foreground_material_dark</item>
    </style>
</resources>
res/values-v21/styles.xml (追加底部导航栏底色)
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
+       <!-- Navigation bar color -->
+       <item name="android:navigationBarColor">@color/accent_material_light</item>
    </style>
</resources>
activity_main.xml (追加Toolbar底色)

<!-- ?attr/actionBarSize -> toolbar的高度是原先的actionbar的高度 -->
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_height="?attr/actionBarSize"
    android:layout_width="match_parent" 
+   android:background="?attr/colorPrimary" >
</android.support.v7.widget.Toolbar>

最后,再来看一下结果画面(只看颜色)

Toolbar.blog1

4.控件(component)

MainActivity.java/onCreat()

mToolbar = (Toolbar) findViewById(R.id.toolbar);
// App Logo
mToolbar.setLogo(R.drawable.ic_launcher);
// Title
mToolbar.setTitle("My Title");
// Sub Title
mToolbar.setSubtitle("Sub title");

// 取代原本的actionbar
// 使用该方法的时候MainActivity需要继承于AppCompatActivity
setSupportActionBar(mToolbar);

// Navigation Icon 要設定在 setSupoortActionBar(...) 后才有作用
// 否則會出現 back button,而不是预想设定的Icon
mToolbar.setNavigationIcon(R.drawable.ab_android);

这边要留意的是setNavigationIcon需要放在 setSupportActionBar之后才会生效

再来看菜单部分,需要先在res/menu/menu_main.xml左定义:

res/menu/menu_main.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <!--
        1.alaways:这个值会使菜单项一直显示在ActionBar上。
        2.ifRoom:如果有足够的空间,这个值会使菜单显示在ActionBar上。
        3.never:这个值菜单永远不会出现在ActionBar是。
        4.withText:这个值使菜单和它的图标,菜单文本一起显示。
     -->

    <!-- orderInCategory 决定item的顺序, 值越大,优先级越低-->

    <item android:id="@+id/action_edit"
        android:title="edit"
        android:orderInCategory="80"
        android:icon="@drawable/abc_ic_ab_back_mtrl_am_alpha"
        app:showAsAction="ifRoom" />

    <item android:id="@+id/action_share"
        android:title="edit"
        android:orderInCategory="90"
        android:icon="@drawable/abc_ic_menu_share_mtrl_alpha"
        app:showAsAction="ifRoom" />

    <item android:id="@+id/action_settings"
        android:title="@string/action_settings"
        android:orderInCategory="100"
        app:showAsAction="never"/>
    <item android:id="@+id/action_1"
        android:title="action_1"
        android:orderInCategory="70"
        app:showAsAction="never"/>
    <item android:id="@+id/action_2"
        android:title="action_2"
        android:orderInCategory="40"
        app:showAsAction="never"/>
    <item android:id="@+id/action_overflow"
        android:title="action_overflow"
        android:orderInCategory="10"
        app:showAsAction="never"/>
</menu>

再回到MainActivity.java 中加入OnMenuItemClickListener 的监听者:

//设置toolBar上的MenuItem点击事件
mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_edit:
                mToast.setText("click edit");
                break;
            case R.id.action_share:
            mToast.setText("click share");
                break;
            case R.id.action_settings:
            mToast.setText("seting");
                break;
            case R.id.action_1:
            mToast.setText("1");
                break;
            case R.id.action_2:
            mToast.setText("2");
                break;
            case R.id.action_overflow:
            //弹出自定义overflow
            popUpMyOverflow();
            return true;
        }
        mToast.show();
        return true;
    }
});


注意拉:
这个时候的按钮响应都必须在setOnMenuItemClickListener写,不可以在重载的onOptionsItemSelected中进行相应了

此外增加了点击action_overflow,弹出自定义的popWindow
/**
* 弹出自定义的popWindow
* 并且popwindow是贴着状态栏的底部的
*/

public void popUpMyOverflow() {
    //获取状态栏高度
    Rect frame = new Rect();
    getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
    //状态栏高度+toolbar的高度
    int yOffset = frame.top + mToolbar.getHeight();
    if (null == mPopupWindow) {
        //初始化PopupWindow的布局
        View popView = getLayoutInflater().inflate(R.layout.action_overflow_popwindow, null);
        //popView即popupWindow的布局,ture设置focusAble.
        mPopupWindow = new PopupWindow(popView,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT, true);
        //必须设置BackgroundDrawable后setOutsideTouchable(true)才会有效
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        //点击外部关闭。
        mPopupWindow.setOutsideTouchable(true);
        //设置一个动画。
        mPopupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
        //设置Gravity,让它显示在右上角。
        mPopupWindow.showAtLocation(mToolbar, Gravity.RIGHT | Gravity.TOP, 0, yOffset);
        //设置item的点击监听
        popView.findViewById(R.id.ll_item1).setOnClickListener(this);
        popView.findViewById(R.id.ll_item2).setOnClickListener(this);
        popView.findViewById(R.id.ll_item3).setOnClickListener(this);
    } else {
        mPopupWindow.showAtLocation(mToolbar, Gravity.RIGHT | Gravity.TOP, 0, yOffset);
    }
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.ll_item1:
    mToast.setText("哈哈");
    break;
    case R.id.ll_item2:
    mToast.setText("呵呵");
    break;
    case R.id.ll_item3:
    mToast.setText("嘻嘻");
    break;
    }
    //点击PopWindow的item后,关闭此PopWindow
    if (null != mPopupWindow && mPopupWindow.isShowing()) {
        mPopupWindow.dismiss();
    }
    mToast.show();
}

popWindow布局如下
res/layout/action_overflow_popwindow.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#274B5E"
    android:orientation="vertical"
    android:padding="10dp">

    <LinearLayout
        android:id="@+id/ll_item1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/abc_ic_menu_share_mtrl_alpha" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="哈哈"
            android:textColor="#ffffff"
            android:textSize="20sp" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_item2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/abc_ic_menu_share_mtrl_alpha" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="呵呵"
            android:textColor="#ffffff"
            android:textSize="20sp" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/ll_item3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/abc_ic_menu_share_mtrl_alpha" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="嘻嘻"
            android:textColor="#ffffff"
            android:textSize="20sp" />
    </LinearLayout>
</LinearLayout>

5.总结
(1)colorPrimaryDark
状态栏背景色。
在 style 的属性中设置。

(2)textColorPrimary
App bar 上的标题与更多菜单中的文字颜色。

(3)App bar 的背景色
Actionbar 的背景色设定在 style 中的 colorPrimary。
Toolbar 的背景色在layout文件中设置background属性。

(4)colorAccent
各控制元件(如:check box、switch 或是 radoi) 被勾选 (checked) 或是选定 (selected) 的颜色。

(5)colorControlNormal
各控制元件的预设颜色。
在 style 的属性中设置

(6)windowBackground
App 的背景色。

(7)navigationBarColor
导航栏的背景色,但只能用在 API Level 21 (Android 5) 以上的版本
在 style 的属性中设置

最后需要注意的是:使用material主题的时候,必须设定targetSdkVersion = 21,否则界面看起来是模糊的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值