Right way of setting margin on Recycler View’s cell

Everyone uses RecyclerView today. But some might miss out how to set the recycler view’s cells’ margin in the right way.

What is needed

We have a RecyclerView with cells, and we want the cell have equal margin on the top, start, bottom, end. Something as illustrated in the image below.

First thing come to mind

That sounds simple. We could just add margin to the card cell as below. This would ensure that the top, start, bottom, end of the cell has the same margin.

<android.support.v7.widget.CardView 
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin"@dimen/default_padding"
android:orientation="vertical">

When we compile and run it becomes as below.

All horizontal margin becomes 2x the size, except for the top cell’s top margin and bottom cell’s bottom margin. This is easily explained as…

--

--