GridLayoutManager中行之间的间距相等

时间:2020-05-02 14:56:11

标签: android kotlin android-recyclerview gridlayoutmanager item-decoration

应该是一个简单的练习,此刻就给我带来了很多问题,因此,我将不胜感激!

我有一个RecyclerView和一个水平GridLayoutManager。我希望行和列之间的间距相等,整个视图的边缘没有任何空白。因此,我添加了一个简单的ItemDecoration,但似乎产生了意外的结果。

我所有相关的代码都在下面,如果您还有其他需要,请告诉我!

物品装饰

class ColorDotDecoration : RecyclerView.ItemDecoration() {

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

        val margin = parent.resources.getDimensionPixelSize(R.dimen.margin)
        val position = parent.getChildAdapterPosition(view)

        val spanCount = (parent.layoutManager as GridLayoutManager).spanCount

        outRect.set(
            if (position < spanCount) 0 else margin,
            0,
            0,
            if (position % spanCount == spanCount - 1) 0 else margin
        )

    }
}

片段代码

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

        add_goal_colors.apply {

            layoutManager =
                GridLayoutManager(context, COLOR_DOT_SPAN, GridLayoutManager.HORIZONTAL, false)

            val ta = resources.obtainTypedArray(R.array.goal_colors)
            adapter = ColorDotAdapter(Array(ta.length()) {

                ta.getColor(it, 0)
            })
            ta.recycle()

            addItemDecoration(ColorDotDecoration())
        }
    }
}

适配器查看代码

<ImageButton xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="@dimen/add_goal_color_dot_size"
    android:layout_height="@dimen/add_goal_color_dot_size"
    android:background="@drawable/color_dot" />

结果 Results

感谢您的帮助。

0 个答案:

没有答案