14年Android开发者大会提出了Android5.0 系统以及 材料设置 Material Design。在 材料设计中推出了大量的UI效果,其中某些功能 已添加进 兼容包,所以可以在低版本中来实现一些材料设计效果。今天主要介绍的就是 ActionBar的替代品 Toolbar。Toolbar 是在V7包兼容的,所以需要下载最新的V7包。
使用ToolBar主要从以下3个步骤开始:
- 样式定义显示效果,属性
- 在布局中使用ToolBar
- 在代码中设置属性
1. 首先,来看下如何设置样式。由于Toolbar是替代ActionBar的,还需要使用 ActionBar兼容的Theme,但是需要做一些简单修改。
a. 先把ActionBar隐藏,为了 方便修改可以將原本 AppTheme 的 parent 属性改为 AppTheme.Base,修改文件 res/values/styles.xml
<resources>
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
</style>
<style name="AppTheme" parent="AppTheme.Base"/>
</resources>
b. 同样,为统一风格,需要将 /res/values-v21/styles.xml 的样式 parent 属性设置为 AppTheme.Base
<resources>
<style name="AppTheme" parent="AppTheme.Base"></style>
</resources>
2. 在 Activity 布局中 加入 Toolbar 组件。注意:为了向下兼容,要使用 V7包下的 Toolbar,并且去掉最外层布局的padding属性。为了确保Toolbar的高度,需要设置 最小高度为ActionBar高度 android:minHeight="?attr/actionBarSize"。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="<span style="font-family: Arial, Helvetica, sans-serif;">?attr/actionBarSize</span><span style="font-family: Arial, Helvetica, sans-serif;">"</span>
android:id="@+id/toolbar" />
</RelativeLayout>
3. 在代码中设置Toolbar。需要Activity 继承 ActionBarActivity。通过setSupportActionBar()替代ActionBar,在OnCreate() 方法中加入以下代码。
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
完成之后,效果如下:
这个 效果不怎么好,需要对其进行简单的修改,改变一些颜色,修整修整就可以见人了。修改的颜色可以参见下图。
通过上图,不难发现,修改颜色主要从这几个方面开始:
- 状态栏背景色 colorPrimaryDark 属性
- 如果还是使用ActionBar,colorPrimary 属性设置背景 如果时Toolbar,布局中background 属性设置背景
- 导航栏背景色 navigationBarColor 属性 ,需要在 5.0 才可以使用,所以属性只可以在 /res/values-v21/styles.xml 设置
- 主界面背景色 windowBackground
<style name="AppTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="windowActionBar">false</item>
<item name="android:windowNoTitle">true</item>
<item name="colorPrimary">#66cc99</item>
<item name="colorPrimaryDark">#66cc99</item>
<item name="android:windowBackground">@color/back</item>
</style>
<style name="AppTheme" parent="AppTheme.Base">
<item name="android:navigationBarColor">#66cc99</item>
</style>
<android.support.v7.widget.Toolbar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/toolbar"
android:background="#339999"
android:minHeight="?attr/actionBarSize" />
设置完成后,效果如下: