五步修改状态栏颜色
标签(空格分隔): 状态栏颜色变化 Android开发
一直以来对 安卓 系统的状态栏都不大满意,在4.4以前只能选择隐藏或者显示,而不能够改变其颜色以适应我们自己APP的整体风格。在安卓5.0发布以后,界面实在美到爆,状态栏的颜色也可以自定义了。于是乎我就有想法将这一特性引入到我自己的APP中。查了很多资料,为了让5.0以前版本的系统享受到material design,google自然会推出相应的兼容包:即appcompathttps://www.zybuluo.com v21,这个兼容包里面有很多有意思的东西,不是这篇文章的重点,以后再讲。在官方文档 https://chris.banes.me/2014/10/17/appcompat-v21/ 中介绍了可以引用这个包,然后在样式中配置如下主题样式就可以达到我们的目的
>colorPrimaryDark 就是用于设定状态栏颜色的。但坑爹的是我按照文档写了一个demo后状态栏颜色就是不改变,一度以为是我demo写的有问题。上stackoverflow查了很久后发现不仅仅是我才遇到这个问题,这个可能是个小bug。总之想要现在通过v21这个包来实现在5.0以前的版本状态栏颜色变化是不可能的了。于是乎我google了好久,好消息是这个特性可以实现,坏消息是只能在4.4版本中实现。我总结了一下,只需要以下五步就可以改变状态栏颜色
第一步:导入支持包到工程[^code]
说明:这个支持包是我从github上的开源项目上脱下来的,就是一个java文件,方便我们自己修改。
第二步:修改主题文件
首先你需要在你工程的res目录下新建个Values-V19的包,然后再建个styles.xml,如下所示:
这个样式文件的目的在于当系统版本大于19时,即安卓4.4,就会首先使用这里面的主题样式。
说明下,**colorPrimary** 是toolbar的颜色,toolbar在上面的那篇博客中有详细的介绍,这里就不在介绍了。**colorPrimaryDark**是状态栏的颜色。颜色的选取可以参考这个网站 http://www.materialpalette.com/purple/orange 。**android:windowTranslucentNavigation**,**android:windowTranslucentStatus** 这两个属性是必须有的,也可以在代码中设置。样式要使用NoActionBar的,这里我们是用toolbar来取代actionbar。
第三步:清单文件中应用主题
**注意**:Demo中使用了toolbar,所以Activity的样式必须继承于Theme.AppCompat,Activity也必须继承自 ActionBarActivity,不然会报错的。这里最好的方式是在application节点下配置默认的样式,这样配置一次就可以了。
第四步:修改布局文件
首先我们把toolbar单独创建出来,这样方便复用。如下在layout中创建toobar.xml
接着将toobar添加到我们的布局文件中。如下main.xml
注意:android:fitsSystemWindows,如果置为true时,作用是空出状态栏的位置,以免我们的的toolbar直接顶到屏幕的顶部。
第五步修改代码
在onCreate中添加一下代码
添加对toobar的支持