本文摘自:这里
在Android上,关于StatusBar的操作一直在不断的改善,并且表现得也越来越好,在Android4.4版本以前,我们可以通过StatusBar和NavigationBar进行显示和隐藏操作。但是直到Android4.4我们才能真正意义上的实现沉浸式状态栏。从Android4.4到现在(Android7.1),关于沉浸式大概可以分成三个阶段。
在 Android 中,页面默认非全屏(状态栏占空间),状态栏内容默认是浅色
-
Android4.4(API 19)----Android5.0(API21):
这个阶段可以实现沉浸式,但是,表现的不是很好,实现方式为:通过FLAG_TRANSLUCENT_STATUS设置状态栏为透明并且显示方式为全屏模式,然后通过添加一个与StatusBar一样大小的View,将View的背景色设置为我们想要的颜色,从而实现沉浸式。
-
Android5.0(API 21)以后版本:
在Android 5.0的时候,加入了一个重要的属性和方法 android:statusBarColor (对应方法为setStatusBarColor),通过这个方法我们就可以轻松实现沉浸式。也就是说,从Android 5.0开始,系统才真正支持沉浸式。
-
Android 6.0(API 23)以后版本:
其实Android6.0以后的版本实现方式跟Android5.0+是一样的,为什么要将其归为一个单独重要的阶段呢?是因为从Android6.0(API 23)开始,我们可以更改状态栏的绘制模式了,可以显示白色或浅黑色的内容和图标(除了魅族手机,魅族自家对源码有更改,6.0以前就可以实现)
基本上就是这三个阶段了,那么接下来我们看一下这三个阶段分别是如何来实现的。
Android4.4(API 19) - Android 5.0(API 21)实现沉浸式的方式
Android 4.4为什么可以实现沉浸式效果呢?因为在Android4.4中新增了一个重要的属性:FLAG_TRANSLUCENT_STATUS
/**
* Window flag: request a translucent status bar with minimal system-provided
* background protection.
*
* <p>This flag can be controlled in your theme through the
* {@link android.R.attr#windowTranslucentStatus} attribute; this attribute
* is automatically set for you in the standard translucent decor themes
* such as
* {@link android.R.style#Theme_Holo_NoActionBar_TranslucentDecor},
* {@link android.R.style#Theme_Holo_Light_NoActionBar_TranslucentDecor},
* {@link android.R.style#Theme_DeviceDefault_NoActionBar_TranslucentDecor}, and
* {@link android.R.style#Theme_DeviceDefault_Light_NoActionBar_TranslucentDecor}.</p>
*
* <p>When this flag is enabled for a window, it automatically sets
* the system UI visibility flags {@link View#SYSTEM_UI_FLAG_LAYOUT_STABLE} and
* {@link View#SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN}.</p>
*/
public static final int FLAG_TRANSLUCENT_STATUS = 0x04000000;
它的作用就是设置状态栏为透明并且变为全屏模式。上面也说的很清楚了,当windows的这个属性有效的时候,会自动设置system.ui.bisibility的标识SYSTEM_UI_FLAG_LAYOUT_STABLE和SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN。
有两种方式实现这个属性:
可以在代码中设置,如下:
activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);