懒筋发作太久,博客文章一直难产。今天硬着头皮都要发出来。
----------------------------------------------此处是碎碎念的华丽分割线-------------------------------------------------
很多开发者朋友都在问,怎样做到支持安卓4.4和4.4以上的状态栏颜色的定制。很多文章都提到的一种方案是在java代码中直接硬编码进行设置。本文提供一种比较简洁有效的方式。
首先是app的主题。在values-->style.xml里面这样定义主题:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <!-- Customize your theme here. --> <item name="colorPrimary">@color/colorPrimary</item> <item name="colorPrimaryDark">@color/colorPrimaryDark</item> <item name="colorAccent">@color/colorAccent</item> </style> <style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style><pre name="code" class="html">
其中的colorPrimary,colorPrimaryDark和colorAccent三个颜色随你需要自己定义。
如果仅仅是要支持5.0和以上系统,那么这样就可以了。
假如还要支持4.4,那么除了上面的,还需要做以下工作:
在res目录下,新建一个values-v19文件夹,在里面创建一个文件style.xml,重新定义AppTheme.NoActionBar主题:
最后,在你的activity布局文件的根节点处,加上一句:<style name="AppTheme.NoActionBar"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> <item name="android:windowTranslucentStatus">true</item> <item name="android:fitsSystemWindows">true</item> </style>
有人问了,那要是fragment呢?不要紧,fragment不需要另外设置。只需要加在Fragment所在的Activity布局文件的根节点就可以了。android:fitsSystemWindows="true"
现在,你只要在Acitivity的根节点上定义背景颜色。
这里可以是colorPrimaryDark,或者你任意定义的其他颜色。如此,这个布局文件所在的Activity头顶状态栏就会被设置成对应的颜色。android:background="@color/colorPrimaryDark" android:fitsSystemWindows="true"
当然别忘了,在定义activity时,应用主题:
android:theme="@style/AppTheme.NoActionBar"
当然,跟这个主题对应,你的Activity要继承自
AppCompatActivity,并且要引入对应的支持包。build.gradle中引入:
compile 'com.android.support:appcompat-v7:24.2.1' compile 'com.android.support:design:24.2.1'
OK,就酱紫。