【发布时间】:2021-03-24 10:01:35
【问题描述】:
我想在 3 行的 recyclerview 水平网格中正确应用间距。但它没有按预期工作。
在此示例中,我只想将底部间距应用于最后一行。但它会应用于所有行。
(这只是大问题的一部分,我想在不同的行和列中应用不同的间距。所以我不想直接将底部填充应用到 recyclerview)
ItemDecorator 代码:
class GridHSpacingDecorator(private val spanCount: Int, private val bottomSpace: Float) : RecyclerView.ItemDecoration() {
lateinit var layoutManager: GridLayoutManager
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
if (this::layoutManager.isInitialized.not()) {
layoutManager = parent.layoutManager as GridLayoutManager
}
outRect.left = 0
outRect.right = 0
outRect.top = 0
val position = parent.getChildAdapterPosition(view) // item position
if (isLastRow(position)) {
Log.d("TEST", "==# isLastRow : $position -==")
outRect.bottom = bottomSpace.toInt()
} else {
outRect.bottom = 0
}
}
private fun isLastRow(position: Int): Boolean {
return layoutManager.spanSizeLookup.getSpanIndex(position, spanCount) == (spanCount - 1)
}
}
活动代码
val dp1 = (this.convertDpToPixel(1f))
val dp8 = (dp1 * 8)
rcvList.adapter = TestAdapter()
rcvList.layoutManager = GridLayoutManager(this, 3, RecyclerView.HORIZONTAL, false)
rcvList.addItemDecoration(GridHSpacingDecorator(3, dp8))
预览:
日志:
D/TEST: ==# isLastRow : 2 -==
D/TEST: ==# isLastRow : 5 -==
D/TEST: ==# isLastRow : 8 -==
D/TEST: ==# isLastRow : 11 -==
【问题讨论】:
标签: android android-recyclerview item-decoration