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

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

当前回答

在Android中很容易获得:

int width  = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;

其他回答

使用这段代码,你可以得到运行时显示的宽度和高度:

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;

在视图中,你需要这样做:

((Activity) getContext()).getWindowManager()
                         .getDefaultDisplay()
                         .getMetrics(displayMetrics);

在某些情况下,设备有一个导航栏,你必须在运行时检查:

public boolean showNavigationBar(Resources resources)
{
    int id = resources.getIdentifier("config_showNavigationBar", "bool", "android");
    return id > 0 && resources.getBoolean(id);
}

如果设备有一个导航栏,那么计算它的高度:

private int getNavigationBarHeight() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int usableHeight = metrics.heightPixels;
        getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
        int realHeight = metrics.heightPixels;
        if (realHeight > usableHeight)
            return realHeight - usableHeight;
        else
            return 0;
    }
    return 0;
}

所以设备的最终高度是:

int height = displayMetrics.heightPixels + getNavigationBarHeight();

我建议您创建扩展函数。

/**
 * 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()

我发现weigan的答案最好的一个在这一页,这里是如何在Xamarin使用它。Android:

public int GetScreenWidth()
{
    return Resources.System.DisplayMetrics.WidthPixels;
}

public int GetScreenHeight()
{
    return Resources.System.DisplayMetrics.HeightPixels;
}

似乎所有这些答案都不适合我的Galaxy M51和Android 11。在做了一些研究之后,我发现了这个代码:

WindowMetrics windowmetrics = MainActivity.getWindowManager().getCurrentWindowMetrics();
Rect rect = windowmetrics.getBounds();
int width = rect.right;
int height =rect.bottom;

显示我的真实设备分辨率为1080x2400,其余只返回810x1800。

为什么不

DisplayMetrics displaymetrics = getResources().getDisplayMetrics();

然后使用

displayMetrics.widthPixels

and

displayMetrics.heightPixels