在新版的Android 5.0中,出现了一大波的新控件,以配合MD化的设计风格。最近在做一个项目,在使用toolbar的时候遇到了一些坑,记录下来分享。
1 toolbar自带一个方便的抽屉和返回图标
以及展开和收回的时候会有自带的很漂亮的动画
2 设置标题
toolbar_main = (Toolbar) findViewById(R.id.toolbar_main);
toolbar_main.setTitle("首页");
toolbar_main.setTitleTextColor(getResources().getColor(R.color.white));
setSupportActionBar(toolbar_main);
3 设置主题
一个普通的主题xml如下
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:popupTheme="@style/AppTheme.PopupOverlay"
app:theme="@style/AppTheme" />
4 设置菜单
使用
onCreateOptionsMenu
方法设置菜单。
5 主题内容详解
一个普通的主题xml如下
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="android:textColorPrimary">@android:color/white</item>
<item name="android:textColorSecondary">#FFFFFF</item>
<item name="android:windowBackground">@color/background_color</item>
<item name="android:actionMenuTextColor">@android:color/white</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:fitsSystemWindows">true</item>
</style>
前三项没什么好说的。
分别是toolbar的颜色
状态栏(也就是toolbar上面的那个黑色栏)的颜色
文字颜色
第四项:左边抽屉图标和右边三个点(英文叫做overflow)的颜色,如果不设置就是这样
第五项:下方主界面的颜色,如图
第六项:不知道,目前没有用到
第七项:各类控件的边框和底色,详见
http://blog.sina.com.cn/s/blog_6e334dc70102ve7d.html
第八项:一般必须设置为true,如果不设置就是这样
但是设置以后会出现toast错位的情况
此时在Toast的上下文应该使用application的context,就可恢复正常。
6 菜单注意事项
显示方式:默认是占满为止,也就是ifRoom。
如果只有一个图标需要使用 app:showAsAction="always"
注意不是 android:showAsAction="always"。
需要加上app的空间 xmlns:app="http://schemas.android.com/apk/res-auto"
此时右边的三个点(overflow)自动隐藏。