A better way to set RecyclerView items margin

Cesar Morigaki
3 min readMay 31, 2020

TL;DR
Use ItemDecoration instead of setting a margin inside the item.xml.

List is a common component that every Android developer implements in its routine/daily basis. At some point, we need to add a divider between items and/or just adjust the margin for cards to be displayed harmonically. As it’s a common problem, there are plenty of old answers on the internet on how to solve them but most of them are not the best solution. Let’s stick with the margin issue.

Problem

Suppose we’re creating a screen that displays a list of cards that each is expected to have a margin of 16dp. We build the item.xml adding the desired margin:

Root of item.xml
Design preview

The item layout alone seems fine but composing it with several others leads to incorrect margins between them. The vertical margin accumulates with the next one, breaking our expectations.

Margin doubled between cards

The lazy solution

A lazy solution would be to reduce vertical margins to half. Almost everything looks good except for the top margin of the first item and the bottom of the last one. We could play with the margins adding a logic inside the ViewHolder to fix the first and last item.

Margin logic inside the Adapter's ViewHolder

But would we duplicate margin/code for every new list? And if we need to reuse the same card view inside a Grid? There is a better way to achieve the same result!

The ItemDecoration solution

RecyclerView has a feature called ItemDecoration:

An ItemDecoration allows the application to add a special drawing and layout offset to specific item views from the adapter’s data set. This can be useful for drawing dividers between items, highlights, visual grouping boundaries and more.

Cool! That’s what we need! Using ItemDecoration we can create a cleaner and reusable solution. Instead of including the margin inside each item view and adding the logic inside ViewHolder, we’ll create a generic ItemDecoration implementation to do this for us.

Setting the ItemDecoration to the RecyclerView:

Also, we may improve the solution for multiple columns (using GridLayoutManager):

And the final result using two columns:

Other usages for Item Decoration

I’m not covering these in this article but here are some examples:

  • Items divider
  • Sticky Header

That’s it! Using ItemDecoration is simple and improves how to set margins between list items.

--

--