RecyclerView in Android with Java

Introduction

 
RecyclerView is the advanced version of ListView in Andriod. In this article, we will learn about RecyclerView in Android with Java programming language.
 

RecyclerView in Android

 
RecyclerView is the advanced version of ListView in Android. RecyclerView is used to show the data into the form of a scrollable list. It is a ViewGroup to display a large set of data. For each item in a large dataset, it displays a View. RecyclerView is an efficient way to implement a scrollable list.
 
RecyclerView is a ViewGroup that arranges our views on the screen like LinearLayout, RelativeLayout, etc. It shows the data on the screen in the form of a list. The views in the list are represented by objects with view holder. Such objects are instances of a class you define. Each view holder is responsible for showing a view of a single object.
 

Why use RecyclerView in Android?

 
One reason is so we can create a List through the LinearLayout and the orientation can be vertical. For example, in the Gmail application, all emails will be rendered as many views in our inbox. Now if we will take LinearLayout, all the mail will create separate views in the memory, but only a few emails will be shown on the screen of the device. This is a waste of memory.
 
Data = ["item1", "item2", "item3",........"item500"] 
 
For each item, we have a view, but if we create a separate view holder for each item, we can only see 10-15 views at a time. This will also be a waste of memory.
 
RecyclerView creates only the number of views which can be shown on the screen of the device because it recycles the views. RecyclerView is used to overcome the problem of memory waste.
 
So, RecyclerView provides an efficient way to create a scrollable list. For example, if we have data of 500 items.
 

How RecyclerView works in android?

 
As we know, RecyclerView recycles the views. We will understand how RecyclerView works internally through the image given below.
 
RecyclerView image
 
Explanation
 
As we saw in the first device of the image, there are 5 items is visible at a time. So we know that the recycler view recycles the views. When the user will scroll the screen first view from the top will be removed and it will be shifted in the below of the last one.
 
Now we will see the example code of RecyclerView in Android, step-by-step.
 
Step 1
 
First, we will create an Android Studio project named RecyclerView Example. Android Studio will create two files in the project MainActivity.java and activity_main.xml.
 
Step 2
 
Before starting with RecyclerView we have to add the RecyclerView dependency in our build.gradle code file of the application. Here is our build.gradle file.
  1. apply plugin: 'com.android.application'  
  2.   
  3. android {  
  4.     compileSdkVersion 29  
  5.   
  6.     defaultConfig {  
  7.         applicationId "manigautam.apps.recyclerviewexample"  
  8.         minSdkVersion 21  
  9.         targetSdkVersion 29  
  10.         versionCode 1  
  11.         versionName "1.0"  
  12.   
  13.         testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"  
  14.     }  
  15.   
  16.     buildTypes {  
  17.         release {  
  18.             minifyEnabled false  
  19.             proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'  
  20.         }  
  21.     }  
  22. }  
  23.   
  24. dependencies {  
  25.     implementation fileTree(dir: "libs", include: ["*.jar"])  
  26.     implementation 'androidx.appcompat:appcompat:1.1.0'  
  27.     implementation 'androidx.constraintlayout:constraintlayout:1.1.3'  
  28.     implementation 'androidx.recyclerview:recyclerview:1.1.0'  
  29.     testImplementation 'junit:junit:4.12'  
  30.     androidTestImplementation 'androidx.test.ext:junit:1.1.1'  
  31.     androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'  
  32.   
  33.     implementation "androidx.recyclerview:recyclerview:1.1.0" //RecyclerView depedency  
  34.     implementation "androidx.recyclerview:recyclerview-selection:1.1.0-rc01"  
After adding the RecyclerView dependency in our project sync the project.
 
Step 3
 
Now we will add RecyclerView layout in our activity_main.xml file. Here is our activity_main.xml file.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3. xmlns:app="http://schemas.android.com/apk/res-auto"  
  4. xmlns:tools="http://schemas.android.com/tools"  
  5. android:layout_width="match_parent"  
  6. android:layout_height="match_parent"  
  7. tools:context=".MainActivity">  
  8.   
  9. <androidx.recyclerview.widget.RecyclerView  
  10.     android:id="@+id/recyclerView"  
  11.     android:layout_width="match_parent"  
  12.     android:layout_height="match_parent" />  
  13.   
  14. </RelativeLayout> 
Step 4
 
Now we will make an xml file in the drawable folder of the project named border_file.xml which we will use for making the border of the RecyclerView. Here is the code of this file.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:shape="rectangle">  
  4.     <stroke android:color="@color/colorAccent" android:width="2dp"/>  
  5.     <corners android:radius="5dp" />  
  6. </shape> 
Step 5
 
Now we will create a custom row layout which will represent the layout of every single element displayed in the RecyclerView. We create a layout file named row_layout.xml.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:orientation="horizontal">  
  6.   
  7.     <ImageView  
  8.         android:id="@+id/image"  
  9.         android:layout_width="300px"  
  10.         android:layout_height="300px"  
  11.         android:layout_marginLeft="10dp"  
  12.         android:layout_marginTop="10dp"  
  13.         android:src="@color/colorPrimaryDark" />  
  14.   
  15.     <TextView  
  16.         android:id="@+id/description"  
  17.         android:layout_width="250dp"  
  18.         android:layout_height="55dp"  
  19.         android:layout_toRightOf="@id/image"  
  20.         android:layout_marginLeft="15dp"  
  21.         android:layout_marginTop="35dp"  
  22.         android:text="abcd"  
  23.         android:textColor="#000"  
  24.         android:textSize="30sp" />  
  25.   
  26. </RelativeLayout>
In this row_layout.xml file, we create an ImageView and TextView for every row of the RecyclerView. The design of the row of RecyclerView is shown in the figure below.
 
row_layout
 
Step 6
 
The RecyclerView which we will create will show the list of some randomly chosen programming languages. We need a class that represents a single RecyclerView item data, create a file named Data.java. The code of this Data.java file is listed below.
  1. public class Data {  
  2.   
  3.     public String name;  
  4.   
  5.     public String getName() {  
  6.         return name;  
  7.     }  
  8.   
  9.     public void setName(String name) {  
  10.         this.name = name;  
  11.     }  
  12.   
  13.     public int getImageId() {  
  14.         return imageId;  
  15.     }  
  16.   
  17.     public void setImageId(int imageId) {  
  18.         this.imageId = imageId;  
  19.     }  
  20.   
  21.     public int imageId;  
  22.   
  23.     Data(String name, int imageId) {  
  24.         this.name = name;  
  25.         this.imageId = imageId;  
  26.     }  
In this Data.java class file, we create a public constructor for the image and the name of the programming language and setter and getter method for these variables.
 
Step 7
 
In this step, we will create a custom RecyclerView.Adapter file named RecyclerView_Adapter.java. The RecyclerView.Adapter is similar to the adapters used on a ListView but with performance improvement, ViewHolder provided.
 
A ListView has adapters for various sources such as ArrayAdapter for arrays, and CursorAdapter for the output of databases. The RecyclerView.Adapter requires a custom implementation to supply the adapter with data.
 
The code file of RecyclerVIew_Adapter.java is listed below.
  1. import android.app.Application;  
  2. import android.content.Context;  
  3. import android.view.LayoutInflater;  
  4. import android.view.View;  
  5. import android.view.ViewGroup;  
  6.   
  7. import androidx.annotation.NonNull;  
  8. import androidx.recyclerview.widget.RecyclerView;  
  9. import java.util.Collections;  
  10. import java.util.List;  
  11.   
  12. public class RecyclerView_Adapter extends RecyclerView.Adapter<View_Holder> {  
  13.   
  14.     List<Data> list = Collections.emptyList();  
  15.     Context context;  
  16.   
  17.     public RecyclerView_Adapter(List<Data> data, Application application) {  
  18.         this.list = data;  
  19.         this.context = application;  
  20.     }  
  21.   
  22.     @NonNull  
  23.     @Override  
  24.     public View_Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {  
  25.         //Inflate the layout, initialize the View Holder  
  26.         View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, parent, false);  
  27.         View_Holder holder = new View_Holder(v);  
  28.         return holder;  
  29.     }  
  30.   
  31.     @Override  
  32.     public void onBindViewHolder(@NonNull View_Holder holder, int position) {  
  33.   
  34.         //Use the provided View Holder on the onCreateViewHolder method to populate the current row on the RecyclerView  
  35.         holder.name.setText(list.get(position).name);  
  36.         holder.imageView.setImageResource(list.get(position).imageId);  
  37.   
  38.     }  
  39.   
  40.     @Override  
  41.     public int getItemCount() {  
  42.         return list.size();  
  43.     }  
In this recyclerView_Adapter.java file, we extend RecyclerView.Adapter and creates its constructor. It shows an error so we have to implement its methods onCreateViewHolder(), onBindViewHolder(), and getItemCount(). 
  • onCreateViewHolder()- It inflates the row layout and initializes the view holder. It handles findViewById) (methods, find views once, and recycle them so that repetitive calls are avoided.
     
  • onBindViewHolder()- It uses the onCreateViewHolder() View Holder to fill in the current RecyclerView row with data.
     
  • getItemCount()- This method returns the collection size which contains the items that we wish to show 
Step 8
 
Now we will create a ViewHolder class named View_Holder.java Java file because, for the one entry in the RecyclerView, the RecyclerView uses a ViewHolder to store references to the respective view. This solution avoids all the findViewById() method calls in the adapter to find out which views to fill with data.
 
The code file of the ViewHolder Java class is listed below.
  1. import android.view.View;  
  2. import android.widget.ImageView;  
  3. import android.widget.TextView;  
  4. import androidx.recyclerview.widget.RecyclerView;  
  5.   
  6. public class View_Holder extends RecyclerView.ViewHolder {  
  7.   
  8.     TextView name;  
  9.     ImageView imageView;  
  10.   
  11.     View_Holder(View itemView) {  
  12.         super(itemView);  
  13.         name = (TextView) itemView.findViewById(R.id.name);  
  14.         imageView = (ImageView) itemView.findViewById(R.id.image);  
  15.     }  
This is ViewHolder file class extends RecyclerView.ViewHolder class, and a constructor with super(). 
 
Step 9
 
Here is the MainActivity.java class file:
  1. import androidx.appcompat.app.AppCompatActivity;  
  2. import androidx.recyclerview.widget.LinearLayoutManager;  
  3. import androidx.recyclerview.widget.RecyclerView;  
  4.   
  5. import android.os.Bundle;  
  6.   
  7. import java.util.ArrayList;  
  8. import java.util.List;  
  9.   
  10. public class MainActivity extends AppCompatActivity {  
  11.   
  12.     @Override  
  13.     protected void onCreate(Bundle savedInstanceState) {  
  14.         super.onCreate(savedInstanceState);  
  15.         setContentView(R.layout.activity_main);  
  16.   
  17.         List<Data> data = fill_with_data();  
  18.   
  19.         RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);  
  20.         RecyclerView_Adapter adapter = new RecyclerView_Adapter(data, getApplication());  
  21.         recyclerView.setAdapter(adapter);  
  22.         recyclerView.setLayoutManager(new LinearLayoutManager(this));  
  23.   
  24.     }  
  25.   
  26.     public List<Data> fill_with_data() {  
  27.   
  28.         List<Data> data = new ArrayList<>();  
  29.         data.add(new Data("C", R.drawable.c));  
  30.         data.add(new Data("C++", R.drawable.cc));  
  31.         data.add(new Data("Java", R.drawable.java));  
  32.         data.add(new Data("Android", R.drawable.android));  
  33.         data.add(new Data("Kotlin", R.drawable.kotlin));  
  34.         data.add(new Data("Html", R.drawable.html));  
  35.         data.add(new Data("CSS", R.drawable.css));  
  36.         data.add(new Data("JavaScript", R.drawable.js));  
  37.         data.add(new Data("SQL", R.drawable.sql));  
  38.         data.add(new Data("SQL Server", R.drawable.sqls));  
  39.         data.add(new Data("Data Structure", R.drawable.data_structure));  
  40.         data.add(new Data("Json", R.drawable.json));  
  41.         data.add(new Data("JSP", R.drawable.jsp));  
  42.         data.add(new Data("Alexa Skills", R.drawable.alexa));  
  43.   
  44.         return data;  
  45.     }  

In this MainActivity.java file, Create an instance of the Recycler View Adapter in the onCreate() method of the  MainActivity class, and send this adapter the list of data and background. The method getApplication() will provide the context for an application.
 
We need sample data, for this example, we generated a method named fill_with_data(), in this method we provide the text as a string and images to show in the RecyclerView. 
 
Output
 
output_gif
 

Summary

 
In this article, we learned about RecyclerView in Android Studio with Java programming language along with an example program.