我如何获得屏幕的宽度和高度,并使用这个值在:
@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
Log.e(TAG, "onMeasure" + widthSpecId);
setMeasuredDimension(SCREEN_WIDTH, SCREEN_HEIGHT -
game.findViewById(R.id.flag).getHeight());
}
我如何获得屏幕的宽度和高度,并使用这个值在:
@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
Log.e(TAG, "onMeasure" + widthSpecId);
setMeasuredDimension(SCREEN_WIDTH, SCREEN_HEIGHT -
game.findViewById(R.id.flag).getHeight());
}
当前回答
我使用下面的代码来获取屏幕尺寸
getWindow().getDecorView().getWidth()
getWindow().getDecorView().getHeight()
其他回答
DisplayMetrics lDisplayMetrics = getResources().getDisplayMetrics();
int widthPixels = lDisplayMetrics.widthPixels;
int heightPixels = lDisplayMetrics.heightPixels;
只是通过parag和SpK更新答案,使其与当前SDK的向后兼容性保持一致:
int Measuredwidth = 0;
int Measuredheight = 0;
Point size = new Point();
WindowManager w = getWindowManager();
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
w.getDefaultDisplay().getSize(size);
Measuredwidth = size.x;
Measuredheight = size.y;
}else{
Display d = w.getDefaultDisplay();
Measuredwidth = d.getWidth();
Measuredheight = d.getHeight();
}
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
public static double getHeight() {
DisplayMetrics displayMetrics = new DisplayMetrics();
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
display.getRealMetrics(displayMetrics);
//int height = displayMetrics.heightPixels;
//int width = displayMetrics.widthPixels;
return displayMetrics.heightPixels;
}
使用这种方法你可以得到屏幕高度。 如果你想要宽度改变displayMetrics。hightpixels到displayMetrics.widthPixels。
它还包括所需的api构建版本。
在Android中很容易获得:
int width = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;
在尝试了上面的许多版本之后,我在Kotlin中找到了答案。它准确地返回为设备所宣传的分辨率。请让我知道,如果这不能在旧设备上工作-我目前只有相对较新的。
该解决方案没有使用废弃的函数(截至2023年1月)。
private fun getScreenHeight() : Int {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val windowMetrics = windowManager.currentWindowMetrics
val rect = windowMetrics.bounds
rect.bottom
} else {
resources.displayMetrics.heightPixels
}
}