Android 中带有方形项目的 GridView 具有自适应宽度/高度

2024-07-01

我有一个带有类似项目的自定义网格视图

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"
android:focusable="false"
android:focusableInTouchMode="false"
android:gravity="center"
android:longClickable="false"
android:orientation="vertical" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="false"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:longClickable="false"
    android:text="0"
    android:textSize="60sp" />

 </LinearLayout>

I want my items to be squares and I want gridview to stretch width to fill all all width of screen in portrait orientation and all height in landscape orientation. It should look like this layout

其中 A - 是正方形的边,B 是边距宽度(可以为零)。 我认为我应该重写 onMeasure 方法,但我到底应该做什么? 也许有人可以帮忙?

编辑 好吧,我尝试在适配器的 getView 方法中手动设置项目的宽度和高度,它更好,但仍然不是我想要的。如何消除列之间的间距?


首先,您想要创建一个可以使用的自定义 View 类,而不是您正在使用的默认 LinearLayout。然后你想覆盖视图的 onMeasure 调用,并强制它是方形的:

public class GridViewItem extends ImageView {

  public GridViewItem(Context context) {
      super(context);
  }

  public GridViewItem(Context context, AttributeSet attrs) {
      super(context, attrs);
  }

  public GridViewItem(Context context, AttributeSet attrs, int defStyle) {
      super(context, attrs, defStyle);
  }

  @Override
  public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
      super.onMeasure(widthMeasureSpec, widthMeasureSpec); // This is the   key that will make the height equivalent to its width
  }
}

然后您可以将 row_grid.xml 文件更改为:

<path.to.item.GridViewItem xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/item_image"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:scaleType="centerCrop"
   android:src="@drawable/ic_launcher" >
</path.to.item.GridViewItem>

只需确保将“path.to.item”更改为 GridViewItem.java 类所在的包。

Edit:

还将scaleType从fitXY更改为centerCrop,以便您的图像不会自行拉伸并保持其纵横比。而且,只要它是方形图像,无论如何都不应裁剪任何内容。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android 中带有方形项目的 GridView 具有自适应宽度/高度 的相关文章

随机推荐