2 illustrated phones. One without header and one with header.

Get ahead using headers in RecyclerView

Meghan Mehta
Android Developers
Published in
3 min readFeb 25, 2021

--

This is the fourth in a series of articles which cover the fundamentals of using RecyclerView. If you already have a solid understanding of how to create a RecyclerView, then carry on. Otherwise, consider starting with this post.

You can add information and context about your app’s data by including a Header in your RecyclerView. Although you can emulate a header by placing a TextView above your RecyclerView in a LinearLayout, this fake header stays on screen even when a user scrolls toward the bottom of the RecyclerView. By providing a genuine header element, you allow the header to scroll off screen when the user scrolls through a RecyclerView.

This blog post goes through adding a Header to a RecyclerView that displays different types of flowers. The Header displays the text “Flower Finder” and displays the number of flowers in the list.

Create header layout

Create a layout file which defines what the Header looks like.

Creating HeaderAdapter and HeaderViewHolder

Create a new file to request and bind the Header’s view.

The Adapter for the Header inherits from RecyclerView.Adapter<RecyclerView.ViewHolder>().

Inside of the Header’s Adapter, create a ViewHolder that inherits from RecyclerView.ViewHolder. If you have dynamic text, create a val to represent the TextView that will be updated. Create a bind() function that updates the TextView to the value passed in.

In the class definition, update the Adapter’s parameter to take in HeaderViewHolder.

Since the Adapter inherits from RecyclerView.Adapter, it has to implement onCreateViewHolder(), onBindViewHolder() and getItemCount().

  • onCreateViewHolder() inflates the view and returns a HeaderViewHolder.
  • getItemCount() returns 1 since there is only one Header item.
  • onBindViewHolder() binds information to the Header.

Using ConcatAdapter in the Activity class

In the Activity class, create a val to hold the HeaderAdapter() above the RecyclerView’s Adapter.

Then use the ConcatAdapter to add both of the adapters to the RecyclerView. ConcatAdapter presents the contents of multiple adapters sequentially. Add in headerAdapter before flowersAdapter.

Run the code and voila! It’s that easy to add a Header.

Next Steps

The full code sample including Header can be found here.

Thank you for reading the last installment in my RecyclerView series, if you missed the other posts check them out here!

Happy coding!

--

--