首页 > 解决方案 > 在 RecyclerView 中的单元格之间添加空间?

问题描述

在我的回收站视图中,项目被紧紧地粘在一起,我想在项目之间添加空间而不在项目本身中添加边距。我想知道我怎么能做到这一点?

目前它看起来像这样: 在此处输入图像描述

我希望它看起来像:

在此处输入图像描述

我可以编辑 XML 本身来完成这个吗?

<androidx.recyclerview.widget.RecyclerView
                android:id="@+id/list"
                android:background="@color/gray6"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:animationCache="false"
                android:cacheColorHint="@color/transparent"
                android:descendantFocusability="afterDescendants"
                android:divider="@color/transparent"
                android:dividerHeight="0dp"
                android:listSelector="@color/transparent"
                android:scrollingCache="false" />

标签: androidandroid-recyclerview

解决方案


也可以通过制作这样的自定义recyclerview装饰器来完成,

class MarginItemDecoration(private val spaceHeight: Int) : RecyclerView.ItemDecoration() {
    override fun getItemOffsets(outRect: Rect, view: View, 
        parent: RecyclerView, state: RecyclerView.State) {        with(outRect) {
            if (parent.getChildAdapterPosition(view) == 0) {
                top = spaceHeight
            }
            left =  spaceHeight
            right = spaceHeight
            bottom = spaceHeight
        }
    }
}

并将其添加到您的回收站视图中,

recyclerView.addItemDecoration(MarginItemDecoration(
        resources.getDimension(R.dimen.default_padding).toInt()))

但是,这种方法有点冗长,我建议将margin放在recyclerview行的xml中,这也是一种不用担心的好方法!

希望问题的答案。


推荐阅读