我如何获得屏幕的宽度和高度,并使用这个值在:
@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());
}
当前回答
由于getMetrics和getRealMetrics已弃用,谷歌建议按如下方式确定屏幕宽度和高度:
WindowMetrics windowMetrics = getActivity().getWindowManager().getMaximumWindowMetrics();
Rect bounds = windowMetrics.getBounds();
int widthPixels = bounds.width();
int heightPixels = bounds.height();
然而,我想出了另一种方法,给我同样的结果:
Configuration configuration = mContext.getResources().getConfiguration();
Display.Mode mode = display.getMode();
int widthPixels = mode.getPhysicalWidth();
int heightPixels = mode.getPhysicalHeight();
其他回答
在Android中很容易获得:
int width = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;
我使用下面的代码来获取屏幕尺寸
getWindow().getDecorView().getWidth()
getWindow().getDecorView().getHeight()
我建议您创建扩展函数。
/**
* Return the width and height of the screen
*/
val Context.screenWidth: Int
get() = resources.displayMetrics.widthPixels
val Context.screenHeight: Int
get() = resources.displayMetrics.heightPixels
/**
* Pixel and Dp Conversion
*/
val Float.toPx get() = this * Resources.getSystem().displayMetrics.density
val Float.toDp get() = this / Resources.getSystem().displayMetrics.density
val Int.toPx get() = (this * Resources.getSystem().displayMetrics.density).toInt()
val Int.toDp get() = (this / Resources.getSystem().displayMetrics.density).toInt()
public class DisplayInfo {
int screen_height=0, screen_width=0;
WindowManager wm;
DisplayMetrics displaymetrics;
DisplayInfo(Context context) {
getdisplayheightWidth(context);
}
void getdisplayheightWidth(Context context) {
wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
displaymetrics = new DisplayMetrics();
wm.getDefaultDisplay().getMetrics(displaymetrics);
screen_height = displaymetrics.heightPixels;
screen_width = displaymetrics.widthPixels;
}
public int getScreen_height() {
return screen_height;
}
public int getScreen_width() {
return screen_width;
}
}
在尝试了上面的许多版本之后,我在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
}
}