首页 > 解决方案 > 使用 GridlayoutManager 和 ItemDecoration 为多行水平 Recyclerview 正确间距

问题描述

我正在尝试绘制一个呈现方形卡片的水平滚动网格。

所以下面有类似的东西

在此处输入图像描述

使用我编写的代码,我在第一行和第二行之间获得了更大的顶部间距。中间的卡片比边缘的卡片宽,如果不是空的,底排的最后一项更窄(尽管我在卡片上设置了固定的高度和宽度)。

在此处输入图像描述

是什么导致 recyclerview 压缩它的内容,有没有办法让卡片内边缘的间距均匀,而边缘上的卡片有不同的水平间距值?

我的代码如下

Horizo​​ntalGridItemDecoration.kt

class HorizontalGridItemDecoration(private val numberOfRows: Int) : RecyclerView.ItemDecoration() {

    // value resource later on
    private val outerSpacing = 60
    private val innerSpacing = 25

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State,
    ) {

        val itemCount = parent.adapter?.itemCount ?: 0
        val currentItemPos = parent.getChildLayoutPosition(view)
        
        // add top spacing to rows except for first row
        if (currentItemPos % numberOfRows == 0) {
            outRect.bottom = innerSpacing
        } else {
            outRect.top = innerSpacing
        }

        // add bigger spacing for last column
        if (currentItemPos > (itemCount - (numberOfRows + 1))) {
            outRect.right = outerSpacing
        } else {
            outRect.right = innerSpacing
        }

        // add bigger spacing for first column
        if (currentItemPos < numberOfRows) {
            outRect.left = outerSpacing
        }
    }
}

我的片段.kt

    //in fragment
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        val rowNum = 4
        recyclerview.apply {
            adapter = GridAdapter(createTitleList())
            layoutManager = GridLayoutManager(requireContext(), rowNum, GridLayoutManager.HORIZONTAL,false)
            addItemDecoration(HorizontalGridItemDecoration(rowNum))
        }
    }

    private fun createTitleList(): List<String> = listOf(
        "No Highway",
        "Aristotle and Dante Discover the Secrets of the Universe",
        "Lord of the Rings: The Fellowship of the Ring",
        "Ulysses",
        "The Curious Incident of the Dog in the Night-Time",
        "Hungry Hungry Caterpillar",
        "Ender's Game",
        "The Maltese Falcon",
        "1984",
        "Neuromancer",
        "Aristotle and Dante Discover the Secrets of the Universeeeee extra section for the title"
    )

GridAdapter.kt

class GridAdapter(private val titleList: List<String>) : RecyclerView.Adapter<GridItemViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GridItemViewHolder {
        val itemView = LayoutInflater.from(parent.context).inflate(R.layout.grid_item_view, parent, false)
        return GridItemViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: GridItemViewHolder, position: Int) {
        holder.bind(titleList[position])
    }

    override fun getItemCount(): Int {
        return titleList.size
    }
}

grid_item_view.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="190dp"
    android:layout_height="190dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="22sp"
        android:textStyle="bold"
        android:textAlignment="center"
        android:padding="16dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="This is a title" />

</androidx.constraintlayout.widget.ConstraintLayout>

my_fragment_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.main.MainFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/main_recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:background="@android:color/holo_orange_light"/>

</androidx.constraintlayout.widget.ConstraintLayout>

标签: androidxmlkotlinandroid-recyclerviewgridlayoutmanager

解决方案


推荐阅读