如何获得屏幕宽度和高度,并在以下情况下使用此值:

@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 = 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();

Android相关问答推荐

编写视觉转型

Android Jetpack Compose Material3主题配色方案

泛型类型lambda函数参数作为函数参数

Jetpack编写使用自定义主题覆盖库中主题部分

Android库中的kotlinCompilerExtensionVersion

我到底应该如何分享我的应用程序中的图片?

有人能帮我在应用程序上使用模拟位置时避免被发现吗?我已经反编译并粘贴了一个代码,S小文件

不能在LazyGrid-Jetpack Compose中使用填充最大宽度或填充父项最大宽度

将DiffUtils用于Android上的Recrecerview适配器

使用Kotline绑定时,ViewHolder无法识别文本视图

如何在android库中关联应用程序链接?

Hilt+Worker NoSuchMethodException:<;init>;[class android.content.Context,class androidx.work.WorkerParameters]

学习Kotlin问题.无法理解Modifier参数

Jetpack Compose 中的用户在线指示器

Jetpack Compose 重组竞争条件

组合 - 重新组合图像

这是 let 函数的正确用法吗?

使用 Room 在 SQLite 中保存复杂的 JSON 响应

如何根据加载图像的 colored颜色 绘制边框?

(Android) 如何在一对多关系中将子 ID 与父级匹配