- 我的需求是挖孔屏弥锄、橫屏全屏顯示狀態(tài)下獲取屏幕的寬度(即正常情況下的屏幕高度)
-
嘗試了以下方法
方法一(無(wú)效炉旷,沒有獲取到導(dǎo)航欄的高度)
public static int getScreenWidth() {
WindowManager wm = (WindowManager) MyApplication.getContext().getSystemService(Context.WINDOW_SERVICE);
return wm.getDefaultDisplay().getWidth();
}
方法二(無(wú)效,沒有獲取到導(dǎo)航欄的高度)
public static int getScreenWidth1() {
//獲取減去系統(tǒng)欄的屏幕的高度和寬度
DisplayMetrics displayMetrics = MyApplication.getContext().getResources().getDisplayMetrics();
int width = displayMetrics.widthPixels;
return width;
}
方法三(無(wú)效叉讥,手機(jī)API版本等于30窘行,待驗(yàn)證)
public static int getRealScreenWidth() {
int width;
WindowManager wm = (WindowManager) MyApplication.getContext().getSystemService(Context.WINDOW_SERVICE);
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
//獲取的是實(shí)際顯示區(qū)域指定包含系統(tǒng)裝飾的內(nèi)容的顯示部分
width = wm.getCurrentWindowMetrics().getBounds().width();
int height = wm.getCurrentWindowMetrics().getBounds().height();
Insets insets = wm.getCurrentWindowMetrics().getWindowInsets()
.getInsetsIgnoringVisibility(WindowInsets.Type.systemBars());
Log.e(TAG, "去掉任何系統(tǒng)欄的寬度:" + (width - insets.right - insets.left) + ",去掉任何系統(tǒng)欄的高度:" + (height - insets.bottom - insets.top));
} else {
//獲取減去系統(tǒng)欄的屏幕的高度和寬度
DisplayMetrics displayMetrics = MyApplication.getContext().getResources().getDisplayMetrics();
width = displayMetrics.widthPixels;
int height = displayMetrics.heightPixels;
Log.e(TAG, "width: " + width + ",height:" + height); //720,1491
}
return width;
}
既然獲取到的屏幕寬度不包含導(dǎo)航欄高度,那么就自己獲取導(dǎo)航欄高度图仓,然后加上去(在設(shè)置導(dǎo)航模式為手勢(shì)模式/導(dǎo)航鍵模式罐盔,獲取到的導(dǎo)航欄高度值是一樣的!>却蕖惶看!無(wú)效)
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;
}
最后發(fā)現(xiàn)這種方式是可以獲取到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;
});