这样,Android 4.4以上的手机就适配完毕了。
/ 特殊场景 /
现在来针对一些特殊场景进行适配,比如启动页、刘海屏和弹窗等等。
启动页
对于启动页,一般都会把状态栏收上去,这需要适配刘海屏,否则刘海区域会显示黑的一片。其实Android P以上提供了适配刘海屏的方法,在启动页Activity添加如下代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
StatusBarUtils.setTransparent(this);
// 适配刘海屏
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.layoutInDisplayCutoutMode =
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
getWindow().setAttributes(layoutParams);
}
}
但是一些手机厂商的刘海屏手机系统版本是低于Android P的,不过也都提供了适配的方法。适配方式是在AndroidManifest.xml文件里的application标签下添加如下代码:
<!-- 允许绘制到小米刘海屏机型的刘海区域 -->
<meta-data
android:name='notch.config'
android:value='portrait' />
<!-- 允许绘制到华为刘海屏机型的刘海区域 -->
<meta-data
android:name='android.notch_support'
android:value='true' />
<!-- 允许绘制到oppo、vivo刘海屏机型的刘海区域 -->
<meta-data
android:name='android.max_aspect'
android:value='2.2' />
<meta-data
android:name='notch.config'
android:value='portrait' />
<!-- 允许绘制到华为刘海屏机型的刘海区域 -->
<meta-data
android:name='android.notch_support'
android:value='true' />
<!-- 允许绘制到oppo、vivo刘海屏机型的刘海区域 -->
<meta-data
android:name='android.max_aspect'
android:value='2.2' />
另外,对于Android 5.0以下的手机,适配完刘海屏后会在顶部多一块黑色半透明的View,那我们将其改成全透明的,修改onCreate()方法如下:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
StatusBarUtils.setTransparent(this);
// 适配刘海屏
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
layoutParams.layoutInDisplayCutoutMode =
WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
getWindow().setAttributes(layoutParams);
}
// 适配Android 4.4
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
StatusBarUtils.setColor(getWindow(), Color.TRANSPARENT, true);
}
}
这样,启动页的效果就适配好了,效果如下:

弹窗
对于弹窗,只有全屏弹窗才能修改状态栏文字的颜色。详见:
https://jimmysun.blog.csdn.net/article/details/88892557
/ 总结 /
以上就是全部代码了,同时我也放在GitHub上了,详见:
https://github.com/jimmysuncpt/ImmersionStatusBar





































苏公安网备 32011402010933号