import android.os.Build;
static int screenTopMargin = 0; static int screenBottomMargin = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
.......
if (Build.VERSION.SDK_INT >= 28) {
getWindow().getDecorView().setOnApplyWindowInsetsListener(new View.OnApplyWindowInsetsListener() {
@Override
public WindowInsets onApplyWindowInsets(View view, WindowInsets windowInsets) {
Log.e("notch", "onApplyWindowInsets");
if(windowInsets == null){
return windowInsets;
}
DisplayCutout cutout = windowInsets.getDisplayCutout();
if (cutout == null) {
Log.e("notch", "cutout==null, is not notch screen");//通过cutout是否为null判断是否刘海屏手机
} else {
List<Rect> rects = cutout.getBoundingRects();
if (rects == null || rects.size() == 0) {
Log.e("notch", "rects==null || rects.size()==0, is not notch screen");
} else {
Log.e("notch", "rect size:" + rects.size());//注意:刘海的数量可以是多个
for (Rect rect : rects) {
Log.e("notch", "cutout.getSafeInsetTop():" + cutout.getSafeInsetTop()
+ ", cutout.getSafeInsetBottom():" + cutout.getSafeInsetBottom()
+ ", cutout.getSafeInsetLeft():" + cutout.getSafeInsetLeft()
+ ", cutout.getSafeInsetRight():" + cutout.getSafeInsetRight()
+ ", cutout.rects:" + rect
);
}
screenTopMargin = cutout.getSafeInsetTop();
screenBottomMargin = cutout.getSafeInsetBottom();
}
}
return windowInsets;
}
});
}else {
screenTopMargin = this.getStatusBarHeight(this.getResources());
screenBottomMargin = 0;
}
}
public static int getStatusBarHeight(Resources resources) {
int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
int height = resources.getDimensionPixelSize(resourceId);
return height;
}
public static int getScreenTopMargin() {
return screenTopMargin;
}
public static int getScreenBottomMargin() {
return screenBottomMargin;
}
本文介绍了一种在Android应用中适配带有刘海屏设备的方法,并提供了获取状态栏高度的实用代码。通过检查Android版本并利用DisplayCutout API,能够准确获取屏幕顶部刘海区域的安全内边距,确保应用在不同设备上的一致性和美观性。
587





