- 我的需求是挖孔屏、横屏全屏显示状态下获取屏幕的宽度(即正常情况下的屏幕高度)
-
尝试了以下方法
方法一(无效,没有获取到导航栏的高度)
public static int getScreenWidth() {
WindowManager wm = (WindowManager) MyApplication.getContext().getSystemService(Context.WINDOW_SERVICE);
return wm.getDefaultDisplay().getWidth();
}
方法二(无效,没有获取到导航栏的高度)
public static int getScreenWidth1() {
//获取减去系统栏的屏幕的高度和宽度
DisplayMetrics displayMetrics = MyApplication.getContext().getResources().getDisplayMetrics();
int width = displayMetrics.widthPixels;
return width;
}
方法三(无效,手机API版本等于30,待验证)
public static int getRealScreenWidth() {
int width;
WindowManager wm = (WindowManager) MyApplication.getContext().getSystemService(Context.WINDOW_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
//获取的是实际显示区域指定包含系统装饰的内容的显示部分
width = wm.getCurrentWindowMetrics().getBounds().width();
int height = wm.getCurrentWindowMetrics().getBounds().height();
Insets insets = wm.getCurrentWindowMetrics().getWindowInsets()
.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars());
Log.e(TAG, "去掉任何系统栏的宽度:" + (width - insets.right - insets.left) + ",去掉任何系统栏的高度:" + (height - insets.bottom - insets.top));
} else {
//获取减去系统栏的屏幕的高度和宽度
DisplayMetrics displayMetrics = MyApplication.getContext().getResources().getDisplayMetrics();
width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
Log.e(TAG, "width: " + width + ",height:" + height); //720,1491
}
return width;
}
既然获取到的屏幕宽度不包含导航栏高度,那么就自己获取导航栏高度,然后加上去(在设置导航模式为手势模式/导航键模式,获取到的导航栏高度值是一样的!!!无效)
public static int getNavigationBarHeight() {
int height = 0;
Context context = MyApplication.getContext();
int rid = context.getResources().getIdentifier("config_showNavigationBar", "bool", "android");
if (rid != 0) {
int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
height = context.getResources().getDimensionPixelSize(resourceId);
}
return height;
}
最后发现这种方式是可以获取到window的上下左右边距,可以加以利用
getDialog().getWindow().getDecorView().setOnApplyWindowInsetsListener((v, insets) -> {
Log.i(TAG, "onTouch touch offsetX getStableInsetBottom = " +insets.getStableInsetBottom());
Log.i(TAG, "onTouch touch offsetX getStableInsetTop = " +insets.getStableInsetTop());
Log.i(TAG, "onTouch touch offsetX getStableInsetLeft = " +insets.getStableInsetLeft());
Log.i(TAG, "onTouch touch offsetX getStableInsetRight = " +insets.getStableInsetRight());
return insets;
});
网友评论