Horizontal and vertical dividers with GridLayoutManager

David Leybovich
Jul 18 · 1 min read

For a long time, I was searching for a nice way to display horizontal and vertical dividers to a RecyclerView with a GridLayoutManager.

I tried custom decorators, adding padding and margin inside the cells and so much more different approaches. The correct one is so simple it’s even disappointing.

First of all — define the divider:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<size
android:width="1dp"
android:height="1dp"/>
<solid android:color="@android:color/transparent"/>
</shape>

Then just use the DividerItemDecoration that comes with the RecyclerView itself.

Just like that:

val verticalDecorator = DividerItemDecoration(Activity, DividerItemDecoration.Vertical)
val horizontalDecorator = DividerItemDecoration(Activity, DividerItemDecoration.Horizontal)

val drawable = ResourcesCompat.GetDrawable(Resources, Resource.Drawable.divider, Theme)
verticalDecorator.setDrawable(drawable)
horizontalDecorator.setDrawable(drawable)

recyclerView.addItemDecoration(verticalDecorator);
recyclerView.addItemDecoration(horizontalDecorator);

Yes, you read it correctly. Just create two decorators: one for horizontal and one for the vertical axis, and that’s it.

Have a nice day.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade