原文 -- StatusBarUtil 状态栏工具类(实现沉浸式状态栏/变色状态栏)
作者:写代码的猴子
这是一个为Android App 设置状态栏的工具类, 可以在4.4及其以上系统中实现 沉浸式状态栏/状态栏变色,支持设置状态栏透明度,满足你司设计师的各种要求(雾)。
特性:
1.设置状态栏颜色:
StatusBarUtil.setColor(Activity activity, int color)
2.设置状态栏半透明
StatusBarUtil.setTranslucent(Activity activity, int statusBarAlpha)
3.设置状态栏全透明
StatusBarUtil.setTransparent(Activity activity)
4.为包含 DrawerLayout
的界面设置状态栏颜色(也可以设置半透明和全透明)
StatusBarUtil.setColorForDrawerLayout(Activity activity, DrawerLayout drawerLayout, int color)
5.为使用 ImageView 作为头部的界面设置状态栏透明
StatusBarUtil.setTranslucentForImageView(Activity activity, int statusBarAlpha, View needOffsetView)
6.在 Fragment 中使用
7.为滑动返回界面设置状态栏颜色
推荐配合 bingoogolapple/BGASwipeBackLayout-Android: Android Activity 滑动返回 这个库一起使用。
StatusBarUtil.setColorForSwipeBack(Activity activity, @ColorInt int color, int statusBarAlpha)
8.通过传入 statusBarAlpha
参数,可以改变状态栏的透明度值,默认值是112。
使用
在 build.gradle 文件中添加依赖, StatusBarUtil 已经发布在 JCenter:
compile 'com.jaeger.statusbaruitl:library:1.3.5'
在
setContentView()
之后调用你需要的方法,例如:
setContentView(R.layout.main_activity);
...
StatusBarUtil.setColor(MainActivity.this, mColor);
DrawerLayout
的界面中使用, 你需要在布局文件中为
DrawerLayout
添加
android:fitsSystemWindows="true"
属性:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
...
</android.support.v4.widget.DrawerLayout>
在 Fragment 中的使用可以参照 UseInFragmentActivity.java 来实现
当你设置了 statusBarAlpha
值时,该值需要在 0 ~ 255 之间
华为荣耀 4A Android版本5.1.1 状态栏始终无法调节(微信也无法调节状态栏,是华为系统自己禁止了状态栏)。
小米4 可以调节。