item decoration not adding margin in item in Gridlayout manager recyclerview

228 views Asked by At

I have been trying to add margin using item decoration in recyclerview item in gridlayout manager.

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

       outRect.set(10,10,10,10)
}

but it's not adding margin to the items What could be the possible reasons that it's not adding margin to grid items?

1

There are 1 answers

1
Narendra_Nath On

Try setting the margin individually like this.

@Override
  public void getItemOffsets(Rect outRect, View view, 
      RecyclerView parent, RecyclerView.State state) {
    outRect.left = space;
    outRect.right = space;
    outRect.bottom = space;

    // Add top margin only for the first item to avoid double space between items
    if (parent.getChildLayoutPosition(view) == 0) {
        outRect.top = space;
    } else {
        outRect.top = 0;
    }
  }

also add clipToPadding="false" in the XML of the recyclerView