安卓屏幕适配—刘海屏
2019-10-05 本文已影响0人
migill
1、安卓官方9.0刘海屏适配策略
- 如果非全屏模式(有状态栏),则app不受刘海屏的影响,刘海屏的高就是状态栏的高

- 如果是全屏模式,app未适配刘海屏,系统会对界面做特殊处理,竖屏向下移动,横屏向右移动

2、安卓官方9.0刘海屏适配-全屏模式下刘海屏黑边(内容区域下挫)的问题
//1.设置全屏
requestWindowFeature(Window.FEATURE_NO_TITLE);
Window window = getWindow();
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//2.让内容区域延伸进刘海
WindowManager.LayoutParams params = window.getAttributes();
/**
* * @see #LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT 全屏模式,内容下移,非全屏不受影响
* * @see #LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES 允许内容去延伸进刘海区
* * @see #LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER 不允许内容延伸进刘海区
*/
params.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
window.setAttributes(params);
全屏未设置成沉浸式的效果

//3.设置成沉浸式
int flags = View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN;
int visibility = window.getDecorView().getSystemUiVisibility();
visibility |= flags; //追加沉浸式设置
window.getDecorView().setSystemUiVisibility(visibility);
全屏设置成沉浸式的效果

在做刘海屏适配的时候,我们还需要判断是否是刘海屏
//Android P上判断是否刘海屏的方法
private boolean hasDisplayCutout(Window window) {
DisplayCutout displayCutout;
View rootView = window.getDecorView();
WindowInsets insets = rootView.getRootWindowInsets();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P && insets != null){
displayCutout = insets.getDisplayCutout();
if (displayCutout != null){
///通过判断是否存在rects来确定是否刘海屏手机,displayCutout.getSafeInsetTop()刘海的高度
if (displayCutout.getBoundingRects() != null && displayCutout.getBoundingRects().size() > 0 && displayCutout.getSafeInsetTop() > 0){
return true;
}
}
}
return false;
}
3、安卓官方9.0刘海屏适配-避开刘海区域
//获取刘海的高度,通常情况下刘海的高度不会超过状态栏的高度
int height = getStatusBarHeight();
Button button = findViewById(R.id.button);
RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) button.getLayoutParams();
//设置控件的margin
layoutParams.topMargin = height;
button.setLayoutParams(layoutParams);
//设置父容器的padding
RelativeLayout layout = findViewById(R.id.container);
layout.setPadding(layout.getPaddingLeft(), heightForDisplayCutout(), layout.getPaddingRight(), layout.getPaddingBottom());
//状态栏的高度,通常情况下,刘海的高就是状态栏的高
public int getStatusBarHeight(){
int resID = getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resID > 0){
return getResources().getDimensionPixelSize(resID);
}
return 96;
}

其他手机厂商(华为,小米,oppo,vivo)适配
华为:https://devcenter-test.huawei.com/consumer/cn/devservice/doc/50114
小米:https://dev.mi.com/console/doc/detail?pId=1293
Oppo:https://open.oppomobile.com/service/message/detail?id=61876
Vivo:https://dev.vivo.com.cn/documentCenter/doc/103