The Wayback Machine - https://web.archive.org/web/20240930221651/https://www.geeksforgeeks.org/android-recyclerview/
Open In App

RecyclerView in Android with Example

Last Updated : 29 Aug, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be customized vastly while improving on the efficiency of ListViews and GridViews. This improvement is achieved by recycling the views which are out of the visibility of the user. For example, if a user scrolled down to a position where items 4 and 5 are visible; items 1, 2, and 3 would be cleared from the memory to reduce memory consumption.

Implementation: 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.

  1. The Card Layout: The card layout is an XML layout which will be treated as an item for the list created by the RecyclerView.
  2. The ViewHolder: The ViewHolder is a java class 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.
  3. 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.

Below is the implementation of the RecyclerView:

exam_card.xml




<!-- XML Code illustrating card layout usage. -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="105dp">
  
  
    <TextView
        android:layout_width="200dp"
        android:id="@+id/examName"
        android:textSize="16sp"
        android:layout_marginStart="20dp"
        android:text="First Exam"
        android:textColor="@color/black"
        android:layout_marginEnd="20dp"
        android:maxLines="1"
        android:layout_marginTop="15dp"
        android:layout_height="wrap_content"/>
  
    <ImageView
        android:id="@+id/examPic"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_below="@+id/examName"
        android:tint="#808080"
        android:layout_marginStart="20dp"
        android:layout_marginTop="7dp"
        app:srcCompat="@drawable/baseline_schedule_black_36dp"/>
  
    <TextView
        android:id="@+id/examDate"
        android:layout_toEndOf="@+id/examPic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/examName"
        android:layout_marginTop="5dp"
        android:layout_marginEnd="20dp"
        android:layout_marginStart="10dp"
        android:gravity="center"
        android:text="May 23, 2015"
        android:textSize="16sp"/>
  
    <ImageView
        android:id="@+id/examPic2"
        android:layout_width="20dp"
        android:layout_height="20dp"
        android:layout_below="@+id/examDate"
        android:tint="#808080"
        android:layout_marginStart="20dp"
        android:layout_marginTop="7dp"
        app:srcCompat="@drawable/baseline_school_black_36dp"/>
  
    <TextView
        android:id="@+id/examMessage"
        android:layout_toEndOf="@+id/examPic2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/examDate"
        android:layout_marginEnd="20dp"
        android:layout_marginTop="5dp"
        android:layout_marginStart="10dp"
        android:gravity="center"
        android:text="Best Of Luck"
        android:textSize="16sp"/>
  
  
    <TextView
        android:id="@+id/border2"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginStart="15dp"
        android:layout_marginEnd="15dp"
        android:layout_alignParentBottom="true"
        android:background="#808080"/>
  
  
</RelativeLayout>


examViewHolder.java




// ViewHolder code for RecyclerView
package com.example.admin.example;
  
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
  
public class examViewHolder
    extends RecyclerView.ViewHolder {
    TextView examName;
    TextView examMessage;
    TextView examDate;
    View view;
  
    examViewHolder(View itemView)
    {
        super(itemView);
        examName
            = (TextView)itemView
                  .findViewById(R.id.examName);
        examDate
            = (TextView)itemView
                  .findViewById(R.id.examDate);
        examMessage
            = (TextView)itemView
                  .findViewById(R.id.examMessage);
        view  = itemView
    }
}


examData.java




package com.prodigieux.admin.prodigieux;
  
public class examData {
    String name;
    String date;
    String message;
  
    examData(String name,
             String date,
             String message)
    {
        this.name = name;
        this.date = date;
        this.message = message;
    }
}


To click on recycler item:

To click on item of recycler view pass the instance of click interface in constructor of adapter




public class ClickListiner{
  
// here index is index
// of item clicked
public click(int index);
  
}


The Adapter: The adapter is the main code responsible for RecyclerView. It holds all the important methods dealing with the implementation of RecylcerView. 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.

Below program illustrates an example of a custom adapter:

ImageGalleryAdapter2.java




private class ImageGalleryAdapter2
    extends RecyclerView.Adapter<examViewHolder> {
  
    List<examData> list
        = Collections.emptyList();
  
    Context context;
    ClickListiner listiner;
  
    public ImageGalleryAdapter2(List<examData> list,
                                Context context,ClickListiner listiner)
    {
        this.list = list;
        this.context = context;
        this.listiner = listiner; 
    }
  
    @Override
    public examViewHolder
    onCreateViewHolder(ViewGroup parent,
                       int viewType)
    {
  
        Context context
            = parent.getContext();
        LayoutInflater inflater
            = LayoutInflater.from(context);
  
        // Inflate the layout
  
        View photoView
            = inflater
                  .inflate(R.layout.card_exam,
                           parent, false);
  
        examViewHolder viewHolder
            = new examViewHolder(photoView);
        return viewHolder;
    }
  
    @Override
    public void
    onBindViewHolder(final examViewHolder viewHolder,
                     final int position)
    {
        final index = viewHolder.getAdapterPosition();
        viewHolder.examName
            .setText(list.get(position).name);
        viewHolder.examDate
            .setText(list.get(position).date);
        viewHolder.examMessage
            .setText(list.get(position).message);
        viewHolder.view.setOnClickListener(new View.OnClickListener() { 
            @Override
            public void onClick(View view) 
            { 
                listiner.click(index); 
            } 
        }); 
    }
  
    @Override
    public int getItemCount()
    {
        return list.size();
    }
  
    @Override
    public void onAttachedToRecyclerView(
        RecyclerView recyclerView)
    {
        super.onAttachedToRecyclerView(recyclerView);
    }
  
      
}


RecyclerView Implementation in an activity:

exam.java




package com.example.admin.example;
  
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
  
import com.prolificinteractive
    .materialcalendarview
    .MaterialCalendarView;
  
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
  
public class exam extends AppCompatActivity
    implements NavigationView
                   .OnNavigationItemSelectedListener {
  
    ImageGalleryAdapter2 adapter;
    RecyclerView recyclerView;
    ClickListiner listiner;
  
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exam);
        Toolbar toolbar
            = (Toolbar)findViewById(R.id.toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
  
        List<examData> list = new ArrayList<>();
        list = getData();
  
        recyclerView
            = (RecyclerView)findViewById(
                R.id.recyclerView);
       listiner = new ClickListiner() {
            @Override
            public void click(int index){
         Toast.makeTexT(this,"clicked item index is "+index,Toast.LENGTH_LONG).show();
         }
      };
        adapter
            = new ImageGalleryAdapter2(
                list, getApplication(),listiner);
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(
            new LinearLayoutManager(exam.this));
    }
  
    @Override
    public void onBackPressed()
    {
        super.onBackPressed();
    }
  
    // Sample data for RecyclerView
    private List<examData> getData()
    {
        List<examData> list = new ArrayList<>();
        list.add(new examData("First Exam",
                              "May 23, 2015",
                              "Best Of Luck"));
        list.add(new examData("Second Exam",
                              "June 09, 2015",
                              "b of l"));
        list.add(new examData("My Test Exam",
                              "April 27, 2017",
                              "This is testing exam .."));
  
        return list;
    }
}


activity_exam.xml




<?xml version="1.0" encoding="utf-8"?>
<ScrollView 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_marginTop="56dp" 
    android:background="#FFFFFF" 
    tools:context=".exam" > 
  
    <LinearLayout 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:orientation="vertical" > 
  
        <android.support.v7.widget.RecyclerView 
            android:nestedScrollingEnabled="false" 
            android:id="@+id/recyclerView" 
            android:layout_width="match_parent" 
            android:overScrollMode="never" 
            android:layout_height="wrap_content"/> 
  
    </LinearLayout> 
</ScrollView>



Output:
Image

Keep in mind, that the drawable mentioned in the XML layouts have to be added to the drawable folder under res of the Android Studio Project and support package v7 should be added as an implementation in the Gradle file of the project for the code to run. The above code uses ScrollView as a parent to RecyclerView and disables the scrolling of the RecyclerView hence making the whole page scroll instead of just the RecyclerView contents.



Previous Article
Next Article

Similar Reads

RecyclerView using GridLayoutManager in Android With Example
RecyclerView is the improvised version of a ListView in Android. It was first introduced in Marshmallow. Recycler view in Android is the class that extends ViewGroup and implements Scrolling Interface. It can be used either in the form of ListView or in the form of Grid View. How to use RecyclerView as GridView? While implementing Recycler view in
6 min read
CardView using RecyclerView in Android with Example
RecyclerView is an extended version of ListView and GridView. It works on the ViewHolder design pattern. With the help of RecyclerView, we can add many extra features to our list of data. Before starting our example on the implementation of CardView in RecyclerView. We should know what CardView and RecyclerView mean. CardView: CardView is an extend
9 min read
RecyclerView Multiple View Types in Android with Example
We've all used RecyclerView in Android to display a list in our applications. RecyclerView is used to display emails in the Gmail app, feeds on Facebook and Instagram, and messages in WhatsApp, among other things. However, as being an Android Developer you would have come across a fact that when we define a view and the list items are only displaye
4 min read
Two Dimensional RecyclerView in Android with Example
In many cases, we have to display the horizontally scrollable list in such a way that we also have to show headers on it to indicate the list belongs to which category. So for that, we have to create a two-dimensional Recycler-View in our app. In this article, we will take a look at creating a 2-dimensional Recycler-View in our app. What we are goi
9 min read
Android RecyclerView Load More on Scroll with Example
Many apps display so many amounts of data in the form of a list. This data is so much so that it cannot be loaded at a time. If we load this data at a time then it may take so much loading time and degrades the performance of our RecyclerView. So to solve this we generally load the data in chunks and display it at a time. In this article, we will t
8 min read
RecyclerView using ListView in Android With Example
RecyclerView is a more flexible and advanced version of ListView and GridView. RecyclerView is used for providing a limited window to a large data set, which means it is used to display a large amount of data that can be scrolled very efficiently by maintaining a limited number of Views. In RecyclerView we supply data and define how each item looks
6 min read
Pull to Refresh with RecyclerView in Android with Example
The SwipeRefreshLayout widget is used for implementing a swipe-to-refresh user interface design pattern. Where the user uses the vertical swipe gesture to refresh the content of the views. The vertical swipe is detected by the SwipeRefreshLayout widget and it displays a distinct progress bar and triggers the callback methods in the app. In order to
5 min read
RecyclerView as Staggered Grid in Android With Example
GridView: A ViewGroup that shows the items in a two-dimensional scrolling grid. In Grid View, each grid is of the same size. i.e., the height and width of each grid are equal. It shows symmetric items in the views.  Staggered GridView: This ViewGroup is the extension of Grid View. In this view, the Grid is of varying size .i.e., their height and wi
6 min read
How to Add Fade and Shrink Animation in RecyclerView in Android?
In this article, we are going to show the fade and shrink animation in RecyclerView. When we move downward then the item at the top will be fading out and then it will shrink. In the output, we can see how it is happening. We will be implementing this Java programming language. [video mp4="https://media.geeksforgeeks.org/wp-content/uploads/20210403
3 min read
Expandable RecyclerView in Android with Kotlin
In this article, we will get to know how to implement the expandable RecyclerView. In General, we will show the list of items in the listview but in some situations like if you want to show the sub-list items, then we have to use an expandable list. See the below image for a better understanding. Step by Step Implementation 1. If you observe the ab
7 min read
Create Floating Animation for RecyclerView Items in Android
In Android, a RecyclerView is a UI element that is used to display a type of layout items in the form of a list. This list is scrollable and each element of the list is clickable. You can find more information on creating RecyclerView in this article: RecyclerView in Android with Example. RecyclerView by default has no entry or exit animation. Howe
5 min read
How to Improve RecyclerView Performance in Android Using DiffUtil?
DiffUtil class is used to improve the performance of RecyclerView. The algorithm behind DiffUtil is that it takes two lists and finds differences between the two and provides the updated list as an output. It uses Eugene W. Myers’s difference algorithm to calculate the minimal number of updates. In this article, we will see its implementations. Not
6 min read
Android | Horizontal RecyclerView with Examples
RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be customized vastly while improving on the efficiency of
4 min read
Android - RecyclerView as Staggered Grid with Kotlin
Staggered Grid View has been seen in most applications such as Pinterest in which each item of grid view takes its own height and aligns within the grid view according to that. In this article, we will look at how to implement Staggered Grid Layout Manager to our Recycler View in Android. Note: If you are looking to implement Staggered Grid Layout
5 min read
How to Implement RecyclerView in a Fragment in Android?
In Android, a fragment is a modular section of a user interface that can be combined with other fragments to create a flexible and responsive application. A fragment represents a behavior or a portion of the user interface in an Activity, which can be reused in different activities or layouts. It has its own lifecycle and can receive input events a
12 min read
How to add Bullet list in a RecyclerView in Android?
Recycler View allows us to show a list of items but to convert our list into the bulleted list we have to do some extra work. You can do this task by following these simple steps given below:- Add the support Library in build.gradle file for Recycler View in the dependencies section. C/C++ Code &lt;dependency&gt; implementation 'androidx.re
2 min read
How to insert Slide From Bottom animation in RecyclerView in Android
In this article, the animation that makes the items slide from the bottom is added in the recycler view. Here we don`t use any other library to add the animation. Adding animations make the application attractive and give a better user experience. Approach:Step 1: Create "anim" resource directory. Right-click on res folder and follow path res ->
2 min read
How to populate RecyclerView with Firebase data using FirebaseUI in Android Studio
Firebase is one of the most popular online databases in use today and will be the same for at least a few years to come. Firebase offers a Realtime Database that can be used to store and retrieve data in real-time to all users. In this post, let's connect the Realtime Database with an Android application and show the data in RecyclerView using the
7 min read
How to Improve RecyclerView Scrolling Performance in Android?
RecyclerView is the main UI component in Android which is used to represent the huge list of data. If the RecyclerView is not implemented properly then it will not smoothly scrollable and it may lead to a bad user experience. To make it scrollable smoothly we have to optimize it and follow some tips to improve its performance. In this article, we w
4 min read
Android Pull to Refresh with RecyclerView in Kotlin
Pull to Refresh is used to update the data within the list in our android application. For implementing this we have to use Swipe to Refresh Layout. Using this widget when the user swipes down the list which is being displayed on the screen is updated. In this article, we will be building a simple application in which we will be displaying a list v
6 min read
Content Placeholder Animation using Shimmer in Android with RecyclerView
We have seen the implementation of Content Placeholder Animation using Shimmer in Android for a simple view. In this article, we will take a look at implementing Content Placeholder Animation using Shimmer in Android with RecyclerView. What we are going to build in this article? We will be building a simple application in which we will be simply di
8 min read
How to Use View Binding in RecyclerView Adapter Class in Android?
View Binding is a part of Android Jetpack which provides the views to bind with the classes by replacing the findViewById() method in a null safe way. In this article, we will see its implementations in the Adapter class of RecyclerView. Note that we are going to implement this project using the Kotlin language. Step by Step Implementation Step 1:
5 min read
Endless RecyclerView in Android
In this article, we are going to see how to build an endless RecyclerView in Android Studio. It is mostly used to design the user interface with great control over the lists and grids of android applications. We can implement both horizontal and vertical layouts using RecyclerView. Here, we will be creating a RecyclerView with a load more option. A
6 min read
How to Create a Collapsing ToolBar and FAB on Scroll with RecyclerView in Android?
In this article, we are going to create a collapsing Toolbar and Floating action button (FAB) on scroll with RecyclerView. Many popular apps have this effect eg. LinkedIn. Below is the sample video to show what we are going to build. Note that we are going to implement this project using the Kotlin language. [video mp4="https://media.geeksforgeeks.
5 min read
How to Disable RecyclerView Scrolling in Android?
RecyclerView is a view group used for displaying data from arrays and databases. RecyclerView basically is a list of items from the data. RecyclerView is often referred to as a successor of GridView and ListView. More about RecyclerView could be found at RecyclerView in Android with Example. RecyclerView lets the users scroll up and down and left a
3 min read
Android - How to Change the Color of Alternate Rows in RecyclerView
RecyclerView is an essential ViewGroup used in Android to display a list of items. It provides a flexible and highly customizable way of implementing a list that can be presented as a grid or a list. In this project, we will be working with RecyclerView to change the color of alternate rows. Typically, all items in a RecyclerView have the same colo
10 min read
How to Delete Multiple RecyclerView Items in Android?
RecyclerView is an advanced version of ListView with improved performance. When you have a long list of items to show you can use RecyclerView. It has the ability to reuse its views. In RecyclerView when the View goes out of the screen or is not visible to the user it won’t destroy it, it will reuse these views. This feature helps in reducing power
8 min read
How to Select Single RadioButton in Android RecyclerView?
RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible the construction of any lists with XML layouts as an item that can be customized vastly while improving the efficiency of
4 min read
How to Display Data in Tabular Form using Android RecyclerView?
RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible the construction of any lists with XML layouts as an item that can be customized vastly while improving the efficiency of
7 min read
Kotlin Lambda Functions For RecyclerView Adapter Callbacks in Android
Are you using old lengthy java fashioned way of creating & handling callbacks in Android with Interfaces? If yes then it's a very good time to switch on Kotlin Lambda Functions or Higher Order Functions to create & handle callbacks. It's a much short, simpler & easy way. Let's first quickly have a look at older java style way Remember w
4 min read