在Google上搜索时,我发现了多种获取屏幕尺寸的方法,这就是我得到的。
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
Log.i(TAG, "first way width = "+size.x);
Log.i(TAG, "first way height = "+size.y);
int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight();
Log.i(TAG, "second way width = "+width);
Log.i(TAG, "second way height = "+height);
int height2 = Resources.getSystem().getDisplayMetrics().heightPixels;
int width2 = Resources.getSystem().getDisplayMetrics().widthPixels;
Log.i(TAG, "third way width = "+width2);
Log.i(TAG, "third way height = "+height2);
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height3 = displaymetrics.heightPixels;
int width3 = displaymetrics.widthPixels;
Log.i(TAG, "fourth way width = "+width3);
Log.i(TAG, "fourth way height = "+height3);
在记录时,所有结果都相同。我想知道所有这些方法或特定用例之间是否有区别? 预先感谢。
答案 0 :(得分:0)
不要重新使用轮子,这是检查屏幕高度和宽度的代码:
/**
* Return the width of screen, in pixel.
*
* @return the width of screen, in pixel
*/
public static int getScreenWidth() {
WindowManager wm = (WindowManager) Utils.getApp().getSystemService(Context.WINDOW_SERVICE);
if (wm == null) {
return Utils.getApp().getResources().getDisplayMetrics().widthPixels;
}
Point point = new Point();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
wm.getDefaultDisplay().getRealSize(point);
} else {
wm.getDefaultDisplay().getSize(point);
}
return point.x;
}
/**
* Return the height of screen, in pixel.
*
* @return the height of screen, in pixel
*/
public static int getScreenHeight() {
WindowManager wm = (WindowManager) Utils.getApp().getSystemService(Context.WINDOW_SERVICE);
if (wm == null) {
return Utils.getApp().getResources().getDisplayMetrics().heightPixels;
}
Point point = new Point();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
wm.getDefaultDisplay().getRealSize(point);
} else {
wm.getDefaultDisplay().getSize(point);
}
return point.y;
}
由BlankJ从helper library中挑选
答案 1 :(得分:0)
这是另一种方式:
public static DisplayMetrics displayMetrics;
displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
对于屏幕的宽度:
float screenWidth = displayMetrics.widthPixels;
关于屏幕的高度:
float screenHeight = displayMetrics.heightPixels;