Android RecyclerView Item Margins — “The Right Way”

--

Problem

Have you ever encountered scrolling to the bottom of a RecyclerView and the last item looks too close to the bottom of the screen?

It looks awkward. It would be good if we can add a margin after the last item to give it a more breathing room. But how?

Possible solution

One solution could be adding a Footer item type with a fixed height to your adapter.

But, this has a few major drawbacks. First, you will have to change the data set to include the footer item. Appending new items to the list is now a headache since you have to consider your footer item. Lastly, the item count of your list now needs to return currentList + 1.

Too much inconvenience for a simple problem as adding margin at the bottom of the list.

So how do we do this the right way?

We can do this using RecyclerView.ItemDecoration. Below are the steps on how to implement it.

1. Create a class LastItemMarginItemDecoration that extends RecyclerView.ItemDecoration. Make its constructor accept lastItemMargin parameter which we will use in setting the last item’s margin.

class LastItemMarginItemDecoration(
private val lastItemMargin: Int
) : RecyclerView.ItemDecoration() {
}

2. Add a private function isLastItem() that checks for the last item.

private fun isLastItem(parent: RecyclerView, view: View, state: RecyclerView.State): Boolean {
return parent.getChildAdapterPosition(view) == state.itemCount - 1
}

3. Override getItemOffsets() from extended RecyclerView.ItemDecoration base class.

override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
// To be implemented on the next step.
}

4. Now, we’re going to check for the last item using the method we created above and apply the last item margin by changing bottom value of outRect parameter.

override fun getItemOffsets(
outRect: Rect,
view: View,
parent: RecyclerView,
state: RecyclerView.State
) {
with(outRect) {
bottom = if (isLastItem(parent, view, state)) {
lastItemMargin
} else {
0
}
}
}

5. It’s time to link our custom LastItemMarginDecoration class to our RecyclerView.

Using RecyclerView’s addItemDecoration() method, we can add our custom ItemDecorations.

val lastItemMargin = 
resources
.getDimensionPixelOffset(
R.dimen.last_item_margin
)
binding
.recyclerView
.addItemDecoration(
LastItemMarginItemDecoration(
lastItemMargin
)
)

Result:

Congratulations! We just successfully added margin to the last item in our RecyclerView!

Bonus!

I have created classes VerticalMarginItemDecoration and HorizontalMarginItemDecoration. We can use this to set margins for the first item, last item, and even on each item inside the RecyclerView.

You can see them here:

Thank you!

--

--

Jermaine Dilao

A Work in Progress Android Developer. You can check me @ https://jermainedilao.github.io/. | 💻 Senior Android Developer @ Speakap