RecyclerView Horizontal Grid Spacing ItemDecorator not working as expected

296 Views Asked by At

I want to apply spacing properly in recyclerview horizontal grid of 3 row. but it's not working as expected.

In this example here, I want to apply bottom spacing to last row only. but it's getting applied to all rows.

(It's just part of big problem where I want to apply different spacing in different rows and column. so I do not want to apply bottom padding to recyclerview directly)

ItemDecorator Code :

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)
    }
}

Activity Code

        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))

Preview :

enter image description here

Log:

D/TEST: ==# isLastRow : 2 -==
D/TEST: ==# isLastRow : 5 -==
D/TEST: ==# isLastRow : 8 -==
D/TEST: ==# isLastRow : 11 -==
1

There are 1 best solutions below

1
Amit pandey On

Try this one

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;

  }
}