滚动时GridView的列不是直线

GridView's column is not a straight line when scrolling

我正在开发一个包含许多图像的 Android GridView。 滚动到列表底部后向上滚动时,列表的列不再是直线。

截图:

更奇怪的是,即使使用相同的适配器和 GridView,另一个列表(在屏幕截图的残奥会选项卡中)也不会发生反应。但是其他页面的项目较少。所以我认为是否在项目计数上存在差异。 (只是我的猜测)问题列表中有 40 个项目。

代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    android:background="@color/white">

    <GridView
        android:id="@+id/sports_gridView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="4dp"
        android:columnWidth="80dp"
        android:gravity="center"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"/>

</LinearLayout>

适配器

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingLeft="5dp"
    android:paddingRight="5dp"
    android:paddingTop="10dp"
    android:paddingBottom="20dp"
    android:background="@color/white">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/sports_iv_item_icon"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_marginRight="10dp"
            android:layout_centerHorizontal="true"/>

    </RelativeLayout>


    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/sports_tv_item_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="5dp"
            android:gravity="center"
            android:textSize="12dp"
            android:textColor="@color/black"
            android:layout_centerHorizontal="true"/>

    </RelativeLayout>


</LinearLayout>

为什么会出现这种现象?我该如何解决?

谢谢大家:)

GridView 并不真正支持具有不同高度的项目,因此您可以执行以下操作:

  • 让你的所有物品都具有相同的高度:在这种情况下它相当 很简单,将 android:lines="2" 添加到 sports_tv_item_title,使所有 你的标题高 2 行。
  • 使用自定义 android 交错网格视图,例如 https://github.com/etsy/AndroidStaggeredGrid(google 的第一击)
  • 我相信带有 StaggeredLayoutManager 的 RecyclerView 可以做到 你也一样。