RecyclerView Sticky Headers based on item groupings

Malcolm Maima
2 min readMar 9, 2022

--

There comes a time in every Android developer’s life when they need to implement a RecyclerView. Easy peasy, right?, just slap some recyclerview xml on your layout, setup your adapter, and initialize your list of items you want to display. I mean if you’re an android developer this is something you can implement in an hour or less.

Now comes the fun part. You want to display a list of items in a RecyclerView, but you want a sticky header on each grouped items. Say a Todo App, you have different states for the ToDo tasks (in progress, done, etc). How do you go about doing this? Obviously you need to sort your list of items by the state they belong to. After this you want to add a sticky header at the beginning of each group.

In this article I will show you how to implement this using a RecyclerView.

Setup the RecyclerView

First we want to set up our RecyclerView.

After creating our layout we need to set up our RecyclerView in our activity.

A couple of things that are happening here, we are setting the adapter, Populating the objects list with our mock data and passing that list to the recyclerview adapter.

Setup the Adapter

Our Adapter is going to handle two viewholder types, one for the header and one for the item.
If the value passed to the Adapter is String, it will be a header type, if it is object, it will be an item.

On Scrolling we are checking if the first visible item is the header, if it is we are setting the header to be sticky. A working version of the tutorial implementation can be accessed here. This is an open source project and you’re welcome to make PRs. Send some love our way :-)

--

--

Malcolm Maima
Malcolm Maima

Written by Malcolm Maima

Android Engineer @ Equity Bank — I code stuff…I eat a lot too, coffee makes me sleepy Love cartoons and robots. http://linktr.ee/malcolmmaima

Responses (1)