我如何获得屏幕的宽度和高度,并使用这个值在:

@Override protected void onMeasure(int widthSpecId, int heightSpecId) {
    Log.e(TAG, "onMeasure" + widthSpecId);
    setMeasuredDimension(SCREEN_WIDTH, SCREEN_HEIGHT - 
        game.findViewById(R.id.flag).getHeight());
}

当前回答

为什么不

DisplayMetrics displaymetrics = getResources().getDisplayMetrics();

然后使用

displayMetrics.widthPixels

and

displayMetrics.heightPixels

其他回答

这里显示的方法已弃用/过时,但仍然可以工作。需要API 13

看看吧

Display disp= getWindowManager().getDefaultDisplay();
Point dimensions = new Point();
disp.getSize(size);
int width = size.x;
int height = size.y;

由于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();
DisplayMetrics dimension = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dimension);
        int width = dimension.widthPixels;
        int height = dimension.heightPixels;

试试Kotlin的这段代码

 val display = windowManager.defaultDisplay
 val size = Point()
 display.getSize(size)
 var DEVICE_WIDTH = size.x
 var DEVICE_HEIGHT = size.y

在尝试了上面的许多版本之后,我在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
    }
}