获取刘海信息:
在Android 9.0
及以上获取刘海信息:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
View decorView = getWindow().getDecorView();
decorView.post(() -> {
WindowInsets rootWindowInsets = decorView.getRootWindowInsets();
DisplayCutout displayCutout = rootWindowInsets.getDisplayCutout();
//获取安全区距离屏幕边缘的距离,安全区是屏幕上最大的完整矩形区域
displayCutout.getSafeInsetLeft();
displayCutout.getSafeInsetRight();
displayCutout.getSafeInsetTop();
displayCutout.getSafeInsetBottom();
//获取刘海位置信息,每个Rect代表一个刘海的位置,因为可能有多个刘海,所以返回一个列表
List<Rect> rects = displayCutout.getBoundingRects();
if (rects == null || rects.size() == 0) {
//不是刘海屏
} else {
for (Rect rect : rects) {
int left = rect.left; //获取刘海的左顶点
int top = rect.top; //获取刘海的上顶点
int right = rect.right; //获取刘海的右顶点
int bottom = rect.bottom; //获取刘海的下顶点
}
}
}
}
}
}
设置刘海模式:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER;
getWindow().setAttributes(lp);
}
这里有三种刘海模式:
LAYOUT_IN_DISPLAY_CUTOUT_MODE_DEFAULT
:
如果如果刘海高度小于等于状态栏高度,相当于SHORT_EDGES
模式
如果刘海高度大于状态栏高度,相当于MODE_NEVER
模式
一般情况下,刘海高度和状态栏高度相等,所以默认SHORT_EDGES
模式
LAYOUT_IN_DISPLAY_CUTOUT_MODE_NEVER
:布局不会显示在危险区域,刘海左右侧会留下空白区域
LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
:布局会显示在危险区域,刘海左右侧会显示布局
这三中模式一般在设置了沉浸式状态栏之后才生效,否则刘海两侧会始终显示状态栏的内容
适配刘海屏:
1.如果屏幕上状态栏存在,那么状态栏就会占据刘海两侧,布局内容会显示在刘海下方,不用适配
2.如果屏幕上状态栏存在,且采用沉浸式状态栏,那么布局要不要显示在刘海两侧由刘海模式决定
3.如果屏幕上状态栏不存在(采用了全屏模式)
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
这时刘海两侧会流出空白,无法实现真正的全屏模式,需要增加其他配置:
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
WindowManager.LayoutParams lp = getWindow().getAttributes();
//注意这里使用default不能使布局占用刘海两侧,必须使用MODE_SHORT_EDGES
lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
}