【问题标题】:RecyclerView Horizontal Grid Spacing ItemDecorator not working as expectedRecyclerView 水平网格间距 ItemDecorator 未按预期工作
【发布时间】: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


    【解决方案1】:

    试试这个

    public class SpacesItemDecoration extends RecyclerView.ItemDecoration {
    private int space;
    
    public SpacesItemDecoration(int space) {
        this.space = space;
    }
    
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, 
       RecyclerView.State state) {
        outRect.left = space;
        outRect.right = space;
        outRect.bottom = space;
    
      }
    } 
    

    【讨论】:

    • 但在我的示例中,我只想为最后一行应用间距。而不是所有行。只有底部填充..没有其他。所以这无济于事
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-23
    相关资源
    最近更新 更多