多次尝试实现Android沉浸式状态栏,资料很多也很杂。并且有好几种实现方案,网上有好些资料把几种方案都混在一起,暂时把效果实现了,但是遇到问题后就蛋疼了。于是,这两天我就把从根源上把这几种方案的原理都整理了一下。主要有四种方案,有的方案还可以细分:
WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
Window.setStatusBarColor(int);
View.setSystemUiVisibility(visibility);
Window.setAttributes(params);
首先创建一个demo,在LinearLayout布局中显示一个全屏的ImageView:
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/blue"
android:orientation="vertical">
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="@drawable/bg"/>
为了让效果明显,将decorview的背景设置为黄色:
getWindow().getDecorView().setBackgroundColor(Color.YELLOW);
把主题背景设置为红色
@color/red
运行效果如下图:
这里写图片描述
方案一 FLAG_TRANSLUCENT_STATUS全屏布局
在values-v19目录下增加一个style:
true
true
@color/red
或者使用java代码实现:
// 在UI线程任何时候都可以调用
private void setTranslucentSystemUI() {
if (Build.VERSION.SDK_INT >= Build.