Everything You Should Know To Create A Recyclerview

How to make Recyclerview in 4 simple steps with 4 examples

Vatsal Patel
Geek Culture
12 min readJun 4, 2021

--

Source: Alliesinteractive on Freepik

Android RecyclerView is a more advanced version of ListView with improved performance and other benefits. The RecyclerView class extends the ViewGroup class and implements the ScrollingView interface. It is introduced in Marshmallow. RecyclerView is mostly used to design the user interface with fine-grain control over the lists and grids of android applications.

In this tutorial, we will learn how to render a simple RecyclerView with a custom layout. We’ll also learn how to write an adapter class, custom model, and item click listener. The recycler view we are going to design contains a list of marvel heroes and their ages (Ages are given randomly).

Structure of Recyclerview

To implement a basic RecyclerView three sub-parts are needed to be constructed which offer the users the degree of control they require in making varying designs of their choice.

  • The Item Layout: The card layout is an XML layout that will be treated as an item for the list created by the RecyclerView.
  • The Data Class: The Data class is a custom java class that acts as a structure for holding the information for every item of the RecyclerView.
  • The Adapter: The adapter is the main code responsible for RecyclerView. It holds all the important methods dealing with the implementation of
  • The ViewHolder: The ViewHolder is a java class, part of the Adapter that stores the reference to the card layout views that have to be dynamically modified during the execution of the program by a list of data obtained either by online databases or added in some other way.

Adapter

The basic methods for a successful implementation are:

  • onCreateViewHolder: which deals with the inflation of the card layout as an item for the RecyclerView.
  • onBindViewHolder: which deals with the setting of different data and methods related to clicks on particular items of the RecyclerView.
  • getItemCount: which Returns the length of the RecyclerView.
  • onAttachedToRecyclerView: which attaches the adapter to the RecyclerView.(not necessary)

Gradle Dependency to use RecyclerView:

The RecyclerView widget is a part of a separate library valid for API 7 level or higher. Add the following dependency in your Gradle build file to use recyclerview.

Gradle Scripts > build.gradle and inside dependencies

Following are the steps of making Recyclerview:

1. Setup Recyclerview

As shown in the image above add Recyclerview in layout and set it to size “match_parent”. Also, give it id as “@+id/recyclerview”. Now go to the code part and make a variable mRecyclerview as an instance of Recyclerview and attach it to the layout part with “findViewById()”.

2. Design Custom Item Layout

As shown in the image above we will create a new resource file named “recyclerview_item.xml”. We will add 2 text views in a relative layout as we want to show the name and age of our heroes.

3. Create Data Class(Custom Model)

As shown in the image above we will create a new java file named “Model.java”. It should be able to take the Name and Age of the hero. Every item of this variable will hold information for one hero.

4. Create Adapter

An adapter is a logic that renders and processes everything related to recyclerview. Viewholder is a part of it that holds references to elements of item layout which we created in the Structure.

We will create a new java file named “AdapterClass.java”. We need the adapter to extend “RecyclerView.Adapter<AdapterClass.ViewHolder>” but as we have not created a viewholder, it will show an error. We will make Viewholder within AdapterClass file with the code given below.

After that, we need to implement the default Recyclerview method, press Ctrl + O while keeping the cursor in the adapter class. It will show an option named “Implement methods”, click on it and then press on “OK”. You will find 3 methods as “onCreateViewHolder()”, “onBindViewHolder()” and “getItemCount()” whose functions are described in Adapter section.

We need to add the code given below in “onCreateViewHolder()” which creates a view as an instance of our custom item layout for each item in the list.

After that, we will create a custom ArrayList name “data” as code given below which will hold information of heroes as a list of Model objects.

We need to add the code given below in “onBindViewHolder()” which shows the Name and Age of each hero in the list.

We need to add the code given below in “getItemCount()” which will return the number of items present in the list.

We have completed all necessary code for the adapter, but how can we get the list of hero data in the adapter? For that, we will add a constructor in AdapterClass by pressing Alt + Insert and selecting data as a field in the constructor. You can also copy the code as below.

After completion of these steps, we will manually make a list of heroes and their data as shown in the image above and make an adapter variable. We will assign this adapter to the mRecyclerview variable. Code is given below

Sample

Hurray, we have made a recyclerview, wasn’t it easy? We will improve its feature in the examples below as for now it will only show a list that scrolls.

This is a simple recyclerview. Now we need to enhance it so that it can be successfully used in the app. We will work on the 4 most necessary features of recyclerview that are frequently used.

Here are the 4 features we will work on:

1. Item Click Listener

As a simple list won’t work in most cases we will add a click listener to each item. It will detect the user’s click on the item and execute code written in block. We can add many types of listeners but we will be working on “Single Click Listener” and “Long Click Listener”. We will show Toast on user click but you can customize it for anything like opening other activity, or showing a dialog or showing hero details, etc as per your need.

We will need to assign id “layout” to the relative layout of the “recyclerview_item.xml” file.

After that, we will add it to Viewholder as below.

Now we need to add click listeners for both single and long click and show different toasts for them, so we will add them as given below.

Sample

2. Layout Managers

In Android, a RecyclerView needs to have a Layout Manager and an Adapter to be instantiated. Layout Manager is a new concept introduced in RecyclerView for defining the type of Layout which RecyclerView should use. It Contains the references for all the views that are filled by the data of the entry. We can create a custom Layout Manager by extending RecyclerView.LayoutManager Class but RecyclerView Provides three types of in-built Layout Managers.

  • Linear Layout Manager — It is used for displaying the items in a horizontal or vertical scrollable list
  • GridLayoutManager — It is used to show the items in grid format
  • StaggeredGridLayoutManager — It is used to show the items in a staggered grid.

Linear Layout Manager

It is used for displaying the items in a horizontal or vertical scrollable list. If we need a list(vertical or horizontal) then we need to use LinearLayoutManager with explicit orientation.

LinearLayoutManager(Context context, int orientation, boolean reverseLayout): In this first parameter is used to set the current context, second is used to set the Layout Orientation should be vertical or horizontal. By using this constructor we can easily make a horizontal or vertical list. The third parameter is a boolean, when set true, items are shown in reverse order.

Default Linear Layout:

Sample

With Reverse Linear Layout:

Just change false to true to show items in reverse order.

Sample

GridLayoutManager

It is used to display the items in a grid layout. We can use the GridLayoutManager for displaying RecyclerView as a GridView.

GridLayoutManager (Context context, int span count, int orientation, boolean reverse layout): In this constructor, the first parameter is used to set the current context, the second parameter is used to set the span count means the number of columns in the grid, the third parameter is used to set the Layout Orientation which should be vertical or horizontal and the last param is a boolean when set true, items are shown in reverse order.

StaggeredGridLayoutManager

It is used to show the items in a staggered grid. It is better than GridLayoutManager if items in the list can expand (eg Note). It will automatically arrange items as per their length without cutting them which is not available in GridLayoutManager.

StaggeredGridLayoutManager(int span count, int orientation): It is used to create a StaggeredGridLayoutManager with 2 params. The first parameter is used to set spanCount means number of columns if orientation is vertical or rows if orientation is horizontal, the second parameter is used to set the orientation, it should be vertical or horizontal.

With Vertical Orientation:

Sample

With Horizontal Orientation:

Sample

3. Data Processing

We see in numerous apps that data in the list is arranged in ascending, descending, or on custom factor, we might also need to implement it as a developer. Here are the 2 types of data processing we will work on:

  • Sort
  • Differentiate

Sort

We will sort this list based on the age of the hero in ascending order. For that, we will go to AdapterClass and make a new public method “sortByAge” as given below. This method takes in and returns a list of data after sorting it. Here we are using the Comparator class of Java and comparing the age variable of o1 and o2 objects(every object will be compared and sorted within o1 and o2).

We can also sort descending by reversing code as given below.

We need to use this method to sort our “data” list. We will call this method in OnCreateViewHolder() class before creating the view. It is not compulsory to perform in OnCreateViewHolder(), it can be done anywhere. Code is given below.

Sample

Differentiate

We can process data based on the different properties it holds. Here we will differentiate heroes based on their gender and give them different colors. For males it will be Blue and for females Yellow. For that, we need to add a Boolean variable named “male” in the Model file to determine if the hero is male or not.

We will also create a method instead of manual data entry named “addHeros”(for better viewing, not necessary) and add more female heroes as in the code below.

Now we will go to AdapterClass and we only need to add these 3 simple lines as below which are the “if-else” block that checks for male and female and assigns a color to their layout.

Sample

4. Item Decoration

RecyclerView allows you to plugin for decoration of items in RecyclerView. Itemdecoration is a separate component that needs to be defined and added to the recyclerview. ItemDecoration can be drawn on all four sides of the item. ItemDecoration gives full control to the developers in measuring and drawing the decorations. Decoration can be a divider or just an inset.

We are taking a simple approach of divider for just understanding it, for more advanced decorations like box or line separator you can search online.

We are making a customer class named “Decoration” in MainActivity. Our goal is to provide spaces between items as per the user input.

We can add decoration to recyclerview by making a variable of our custom class and then assigning it as below in MainActivity.

Sample

Here I have taken 30, it is a big number in terms of spacing but I did it so you can see a significant difference. You can take whatever amount of space you require.

If you have reached this far you have known almost everything necessary for making Recyclerview. Above 4 are the most commonly used cases of the recyclerview. You can explore more by playing with the code. There are endless possibilities and combinations that are available for recyclerview, so keep learning.

Here is the complete code of files which you can use to create your custom recyclerview.

Layouts

Java Code

Thank You for giving your time. If you found this tutorial knowledgeable and helpful please appreciate it below. You can find my other similar articles here.

If you want to talk more or any queries are left unanswered you can connect with me via -

- Linkedin

- Twitter

--

--

Vatsal Patel
Geek Culture

I am an Electronic Engineer, an AI Enthusiast, an Android developer and an Investor :)