Skip to content
Advertisement

Android 5.0 – Add header/footer to a RecyclerView

I spent a moment trying to figure out a way to add a header to a RecyclerView, unsuccessfully.

This is what I got so far:

JavaScript

The LayoutManager seems to be the object handling the disposition of the RecyclerView items. As I couldn’t find any addHeaderView(View view) method, I decided to go with the LayoutManager‘s addView(View view, int position) method and to add my header view in the first position to act as a header.

Aaand this is where things get uglier:

JavaScript

After getting several NullPointerExceptions trying to call the addView(View view) at different moments of the Activity creation (also tried adding the view once everything is set up, even the Adapter’s data), I realized I have no idea if this is the right way to do it (and it doesn’t look to be).

PS: Also, a solution that could handle the GridLayoutManager in addition to the LinearLayoutManager would be really appreciated!

Advertisement

Answer

I had to add a footer to my RecyclerView and here I’m sharing my code snippet as I thought it might be useful. Please check the comments inside the code for better understanding of the overall flow.

JavaScript

The above code snippet adds a footer to the RecyclerView. You can check this GitHub repository for checking the implementation of adding both header and a footer.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement