3

In my recyclerview, items are stuck close together, I want to add space between Items WITHOUT adding margins in the items themselves. I am wondering how I can accomplish this?

Currently it looks like this: enter image description here

I want it to look like:

enter image description here

Could I edit the XML itself to accomplish this?

<androidx.recyclerview.widget.RecyclerView
                android:id="@+id/list"
                android:background="@color/gray6"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:animationCache="false"
                android:cacheColorHint="@color/transparent"
                android:descendantFocusability="afterDescendants"
                android:divider="@color/transparent"
                android:dividerHeight="0dp"
                android:listSelector="@color/transparent"
                android:scrollingCache="false" />
testingsah
  • 71
  • 2
  • 5

2 Answers2

2

It can also be done by making a custom recyclerview decorator like this,

class MarginItemDecoration(private val spaceHeight: Int) : RecyclerView.ItemDecoration() {
    override fun getItemOffsets(outRect: Rect, view: View, 
        parent: RecyclerView, state: RecyclerView.State) {        with(outRect) {
            if (parent.getChildAdapterPosition(view) == 0) {
                top = spaceHeight
            }
            left =  spaceHeight
            right = spaceHeight
            bottom = spaceHeight
        }
    }
}

And add it to your recyclerview,

recyclerView.addItemDecoration(MarginItemDecoration(
        resources.getDimension(R.dimen.default_padding).toInt()))

But, This approach is bit lengthy, I suggest to put margin inside your recyclerview row's xml, It's also a good approach nothing to worry about that!

blackgreen
  • 34,072
  • 23
  • 111
  • 129
2

You can use DividerItemDecoration such as:

public static class DividerItemDecoration extends RecyclerView.ItemDecoration {
    int spacing;
    public DividerItemDecoration(Context context, int spacing) {
        this.spacing=spacing;
    }
    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
         outRect.bottom=spacing;
    }
}

and then add this

recyclerView.addItemDecoration(new DividerItemDecoration(30));

where 30 is the spacing you need, you can change it to any number.

//Add both the codes to the activity containing recylerview.

Sam
  • 173
  • 6