最近项目有用到状态栏着色,之前一直都有参考Android 状态栏着色实践一文,挺好的。今天抽空自己写一点关于状态栏着色的笔记,方便日后查阅。
这里只记录第一种方式。大概可以分为两个步骤,一是将状态栏透明化,二是将布局的最顶部View延伸到状态栏再对其做一些小小的paddingTop调整就可以啦。
一、状态栏透明化
1 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { |
二、修改布局文件
将最外层ViewGroup的android:fitsSystemWindows=”false”,让布局延伸至状态栏。1
2
3
4
5
6<com.lcgao.widget.SlideRight xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/id_activity_slide_right"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="false"
android:scrollbars="none">
再将Toolbar的paddingTop设置为状态栏的高度,如果在布局顶部使用了Toolbar,记得要把Toolbar的layout_height属性设置为wrap_content:1
2
3
4
5
6
7
8
9
10
11
12<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="@+id/id_layout_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="@color/switch_track_disabled_dark"
android:paddingTop="@dimen/padding_top" />
</android.support.design.widget.AppBarLayout>
这里因为只有在Android 4.4(API19)以后的版本才可以对状态栏进行着色,所以只对API19以后的设置paddingTop为25dp,否则在API19以前的设备上会看到25dp的多余部分,这时候就要通过在不同的values文件里面写相关的padding_top了:1
2
3
4
5//values
<dimen name="padding_top">0dp</dimen>
//values-v19
<dimen name="padding_top">25dp</dimen>
这样一来只会在API19以后的设备才会多增加25dp的高度至状态栏,而API19以前的设备就不会增加了,最终效果如下,设备为Android4.4版本:
另外,最近在做Cordova的混合开发,发现一个小问题,在继承CordovaActivity的Activity中,状态栏透明化部分的代码(本文第一段代码)要在loadUrl(launchUrl)之后写,不然在一些设备上会透明化失败,达不到想要的效果。