Android grid view item 宽高比(使高度比宽度高一点)

标签 android

我想让我的 GridView 中的项目成为完美的正方形。我使用了 this answer 建议的方法效果很好。

代码如下(重写 GridView 项的onMeasure方法)

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, widthMeasureSpec);
}

现在我想让项目的高度比项目宽度大 1.2 倍。所以,我修改了如下代码。

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, (int) (widthMeasureSpec * 1.2));
}

但是,项目变得很长,甚至不能再适应屏幕。

令人惊讶的是,如果我将 heightMeasureSpec 设置为小于 widthMeasureSpec 的值,项目高度仍然会大于宽度。以下代码使项目更高。

@Override
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, (int) (widthMeasureSpec * 0.5));
}

有人可以解释这种行为吗?有什么方法可以实现我想要的吗?

最佳答案

我没有遇到您描述的行为,但通常我会使用 next onMeasure

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    int originalWidth = MeasureSpec.getSize(widthMeasureSpec);
    super.onMeasure(
            widthMeasureSpec,
            MeasureSpec.makeMeasureSpec((int) (originalWidth * 1.1f), MeasureSpec.EXACTLY)
    );
}

关于Android grid view item 宽高比(使高度比宽度高一点),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43610271/

相关文章:

javascript - 在启动时加载外部链接的 Phonegap 应用程序 - Android

android - 勺子 + TeamCity

android - 使用 SwipeActionAdapter 在 ListView 上获取特定的 TextView ID

java - 使用谷歌地图 V2 在多段线中绘制箭头

java - 在 Android 中使用 isReachable() 时出错

android - 将 Kotlin 运行时库添加到 android 中的 aar

android - 联系人选择器过滤

android - 如何解决 android api 30+ 中的 "Missing PendingIntent mutability flag"lint 警告?

java - 读取 CPU 使用率时出错 :/proc/stat (permission denied)

android - 在推送上运行一次性 GCM 网络管理器任务