上一篇写完8.0的四大厂商,现在补上9.0的获取刘海屏的方法。
需要把TargetVersion提到28,miniVersion提到23,或者使用反射的方法来获取
1.在Manifest.xml上的application下,添加标签
<meta-data
android:name="android.vendor.full_screen"
android:value="true" />
2.首先要判断api版本
if ((Build.VERSION.SDK_INT >= 28)) {
// 使用官方api判断
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.layoutInDisplayCutoutMode = 1;
getWindow().setAttributes(lp);
//不显示状态栏
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
//初始化时先写适配刘海屏的方法,再判断是否有刘海屏
getCutoutLengthAndroidP(context,window);
return;
}else{
//低于api28,使用四大厂商的适配
}
3. 然后getCutoutLengthAndroidP()方法的具体实现如下
private void getCutoutLengthAndroidP(final Context context,Window window) {
final View decorView = window.getDecorView();
if (decorView != null) {
decorView.post(new Runnable() {
@Override
public void run() {
View windowInsetsObj=decorView.getRootWindowInsets();
if (windowInsetsObj != null) {
WindowInsets displayCutoutObj=windowInsetsObj.getDisplayCutout();
if (displayCutoutObj != null) {
List<Rect> rects = displayCutout.getBoundingRects();
//有刘海,上面的List代表可能存在下刘海,这里只讨论获取上刘海的情况
if (rect != null && rect.size() > 0) {
for(Rect rec:rect){
//此处获取的是刘海屏高度
int notchHeight=rec.height();
return;
}
}
}
}
}
});
}