In Android, Recyclerview is an advanced, flexible and upgraded version of Listview and Gridview. It is fast becoming one of the most used components in android applications. It uses less memory for listing large amount of datasets and collections. Furthermore, it provides the user a better experience.
I was looking for a finished model to add a header item to the recyclerview, yet, I couldn’t discover something that was concise and clear. In this blog, we will try to develop a model that can be used for adding a header item to recyclerview for android applications.
Have a look at the screenshots below to get an idea about what we are trying to achieve in this tutorial.
Misaligned viewitem output
Actual Output
Let’s get started.
1. Adding Support Library
You need to add the following support libraries to gradle(Module.app) for Recyclerview to work in your project.
2. Creating Recyclerview
Use Recyclerview instance of listview for an improved experience and defining it in xml is quite simple. You can define it in xml as follows..
activity_main.xml
3. Create two different layouts for Header and Viewitem layout
Here we create two xml layout, one for header item and another one for viewitem.
Headerview holds the UI components needed to be shown in the header item.
Your code for Header item xml should be similar to the one below,
activity_headeritem.xml
Similar to the Headerview, Listview Items holds the UI components for the view items.
I have attached the xml code for the Listview item below,
activity_listviewitem.xml
4. CustomAdapterclass.java
We have achieved adding the header item to recyclerview by using the viewtype property. So now we will create custom adapter for Recyclerview. In onCreateViewHolder
method, we have to use two inflate methods, which will help you to define your layout.xml. You should extend your adapter with “RecyclerView.Adapter” which follows the viewtype property.
CustomAdapter.java
getItemViewType() provides the viewtype property to Recyclerview, which helps with scrolling the Recyclerview.
getItemCount() increases the list item position by one (listitem + 1). It provides the row under the header.
5. MainActivity.java
In this class, we have to pass the adapter class of Recyclerview to complete the scrolling function. Finally, we achieve the complete function of Recyclerview with Header view.
MainActivity.java
This brings us to the end of this tutorial. I hope that you have learned how to create a recyclerview for your android app. Now, you can run this on your android device and see the output for yourself. This output seems to be exactly what you want.