在回收视图上自动调整单元格大小

问题描述 投票:0回答:1

我正在使用 recyclerview 创建一个 gridview,这工作正常,但我在渲染中确实遇到了问题。

我希望每个单元格保持相同的大小,并且每个单元格的大小是

例如,我有 5 列,如下图所示:

如您所见,每个单元格之间都有空间。这是因为我为单元格设置了定义的宽度。

下面是单元格的 xml:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

  
    <androidx.cardview.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintDimensionRatio="1"
        android:clickable="true">

        <TextView
            android:id="@+id/itemElevation"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:gravity="center"
            android:textColor="@android:color/black"
            app:elevationItem="@{item}"
            tools:text="33"
            tools:background="@android:color/holo_orange_dark"/>

    </androidx.cardview.widget.CardView>

</layout>

我的回收视图如下所示:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".ui.MainFragment">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/gridView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
            app:spanCount="5"
            tools:listitem="@layout/item_cell"
            tools:itemCount="25">

        </androidx.recyclerview.widget.RecyclerView>


    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

我正在尝试弄清楚如何让单元格均匀地使用屏幕的宽度,这样就没有更多的空间。

我试图得到如下但自动的,所以如果我移动到 6 列,它将保持正方形,但宽度会自动调整。

有什么想法吗?

android kotlin android-recyclerview android-cardview cardview
1个回答
0
投票

问题是您的单元格宽度当前设置为

wrap_content
,并且其内容始终为
50dp
宽。

要使单元格填充可用的全部宽度,您可以将单元格布局宽度设置为

match_parent
:

<androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constraintDimensionRatio="1"
    ...

</androidx.cardview.widget.CardView>

© www.soinside.com 2019 - 2024. All rights reserved.