Android Recyclerview Simple Tutorial

RecyclerView??? Is that a View? What does it do?

How to use this one?

are these thoughts running through your head? then Go on.
Or
you know something about RecyclerView then Refresh your knowledge by reading this post.

In this article, you will learn about RecyclerView, RecyclerView Adapter, and a simple example that helps you to create your one.
At last, I will teach you how to use Checkbox with RecyclerView. Yes, you can scroll fearlessly without thinking about losing the selected states in CheckBox.

So fasten your seatbelts, let’s take-off now.

What Is RecyclerView In Android?

From the name, we can understand that it’s an Android View. Actually, It is a ViewGroup with scroll ability which works based on adapter principles.

In simple words, It helps us to show a large no. of data collections just like ListView and GridView.

If RecyclerView wants to show large no.of items, it does not create the same amount of views. It just creates the viewholders which hold the inflated view needed to fill the screen and some more.

After that when the user scrolls, it makes use of cached views. Yes, It recycles views, again and again, that’s why it got the name “RecyclerView”.

As a successor, It is far away from ancestors(ListView, GridView) by performances and abilities. By more features, it becomes a little bit complex too.

Let’s look up the history, ListView has been part of Android since 1.0, but each os releases, new features got added. Not in the case of ListView.

ListView simply defeated by developer’s needs such as different types of layouts and animation support. That’s where RecyclerView was born.

Finally in 2014 Android Lolipop introduced RecyclerView as a standalone support library.

After the arrival of the AndroidX library (after API level 28.0.0), RecyclerView changed its package name android.support.v7.widget.RecyclerView to androidx.recyclerview.widget.RecyclerView.

If you are using Android Studio, just add it to gradle and use.

8 Differences Between ListView And RecyclerView In Android

differences between listview and recyclerview in android

1. ViewHolder pattern
ViewHolder pattern is a strategy used to store view references in memory.

It reduces the number of calls to complicated and tedious findViewById(), which makes scrolling smooth.
,
In the case of ListView, it was optional, you can build your favorite list without any use of ViewHolder.

But when it comes to RecyclerView side, google developers make it as default for RecyclerView.

2. Re-Using views
Both ListView and RecyclerView support Reusing views. On the ListView side, it gives the option to reuse.

It’s the developer, who needs to take the action.

@Override
    public View getView(int position, View convertView, ViewGroup parent) 
{
     if(convertView == null)
     {
      //inflate your layout
     }
     //reuse convertView

}

Using the above example code, we can check the convertView is null or not. If it is null, that means there is no recycled view. Then we can inflate the layout.

If it is not null, means that not the first time, so we can use convertView and avoid layout inflation.

3. Layout Types

With ListView, you can easily make a list with simple and less code.

Code is a bit complex with RecyclerView, but it provides more options: horizontal, vertical list, grid, and staggered grid

You can also create your custom layout manager using RecyclerView.LayoutManager.

4.Animation Support

In the animation section, RecyclerView is far ahead from ListView. It’s not easy for beginners to make animations in ListView.

But RecyclerView shows Fade in, Fade out, translate and crossfade animations when you add, delete, move and update an item in RecyclerView.

This is default in RecyclerView because it internally uses the DefaultItemAnimator class. That’s why they gave that name.

If you don’t like these animations and want to make your animations make use of RecyclerView.ItemAnimator class.

5. Divider

ListView has divider by default.

The android:divider and android:dividerHeight attributes or setDivider(),setDividerHeight() helps you to make custom divider in ListView.

But RecyclerView doesn’t give these options.

But you can use the DividerItemDecoration class to make a simple divider or Make use of RecyclerView.OnItemDecoration class to decorate the view.

6. Click Events

One of the main disadvantages we face with RecyclerView is that it lacks OnItemClickListener. Because it’s not a subclass of AdapterView like ListView.

It provides RecyclerView.OnItemTouchListener to capture click events. It gives more control to the developer.

You can also use OnClickListener with views on the item.

7.Notify Methods
When notifying adapter, while data change occurs we can call notifyDatasetChanged() with ListView.

But ListView doesn’t know what had happened? It can be the addition, deletion or change of items in the dataset but don’t know what was happened.

For RecyclerView there are lots of notify* methods to inform, including notifyDatasetChanged().

Using the appropriate notify* method can invoke better animation in RecyclerView.

8. Header and Footer
It is easy to add Header and Footer in ListView using addHeaderView() and addFooterView().

But RecyclerView doesn’t have these methods instead it supports different types of view.

Finally, RecyclerView supports Nested Scrolling.

I think that’s enough for the comparison. So use them based on your needs. If you are a beginner in Android App Development, Learn ListView first then go with RecyclerView.

How To Use RecyclerView In Android?

RecyclerView is one of the most valuable widgets in Android development. Out of the box, RecyclerView is lazy. Because it has given responsibilities to different classes.

So before Using RecyclerView, you should know about these classes.

1)RecyclerView.Adapter

This is the most important class in RecyclerView. Same as other AdapterView, It connects the View(RecyclerView) and data.

RecyclerView has no default adapters, So you need to create a custom class by extending Recyclerview.Adapter.

It is responsible for

  • Creating ViewHolders
  • Binds data to ViewHolders.
  • Informs Recyclerview about dataset changes.

Most of the important methods in this class are:
i)OnCreateViewHolder() : This method is called when RecyclerView needed to create a viewholder.
ii)OnBindViewHolder(): Calls whenever needed to bind data with view in viewholder.
iii)getItemCount() : Used to return total number of items in the dataset (ArrayList, array etc).
iv)getItemViewType(): it returns the viewtype based on the position.

2) RecyclerView.LayoutManager

As the name says, it helps RecyclerView to manage layout by positioning each item.

Unlike ListView, RecyclerView shows child items in Horizontal, Vertical list, grid, and staggered grid because of LayoutManager.

Scrolling responsibility is also own by LayoutManager. When you scroll up in RecyclerView, LayoutManager moves your items up.
staggeredgridlayoutmanager gridlayoutmanager
It provides different classes for arranging items:

i)LinearLayoutManager: Creates vertical and horizontal lists.
ii)GridLayoutManager: Creates grid layouts.
iii)StaggeredGridLayoutManager: Creates StaggeredGrid layouts.
iv)WearableLinearLayoutManager: This class is for wearable devices.

3) RecyclerView.ItemDecoration

The name implies, it decorates RecyclerView’s item or view. It provides not only a divider, Using this abstract class you can draw four sides of the item. When using the divider as a view in XML, it decreases performance. That’s where the importance of this class comes through.

Version 25.1.0 Support library introduces the DividerItemDecoration class, to make a simple divider. Use addItemDecoration() method to add with RecyclerView. This class supports both horizontal and vertical orientations, so you can use it with any of your lists without any worries.

4) RecyclerView.ItemAnimator

Google developers gave more importance to animations in RecyclerView, So RecyclerView provides RecyclerView.ItemAnimator class for handling animations.

You can make custom animations using this class.

Just I said in ListView vs RecyclerView comparison, RecyclerView animates items when item adds, delete or any other move event happens because it internally uses DefaultItemAnimator.

But you can not see these animations when RecyclerView loading for the first time.

5) RecyclerView.ViewHolder
Android RecyclerView ViewHolder
You can consider ViewHolder as something which holds View.

Unlike ListView, we need to make custom ViewHolder class by extending RecyclerView.ViewHolder class.

In this subclass, we must store the item view’s references. This ViewHolder class contains additional information like its position in the layout.

Simple RecyclerView Example With CardView In Android Studio – OnClickListener Included


In this example, I will explain how to create RecyclerView in Android Studio in 10 simple steps with a detailed explanation. The final output will look like below.

Simple RecyclerView With  CardView Example In Android Studio
I assume that you have created a Project in Android Studio, then add these

STEP 1 – Add Dependencies In build.gradle

RecyclerView and CardView are support libraries, so you must add dependencies in your build.gradle file, If your app needs to support above API 28.0.0, you must use AndroidX libraries. otherwise, you can continue with the support library.

 
/* androidx library*/

    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'

/*
support library
 
    implementation 'com.android.support:cardview-v7:28.0.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
*/

STEP 2 – Import RecyclerView In Android Studio

Just like ListView, just add it to your layout. here activity_main.xml





This code creates a RecyclerView widget with id “recyclerview”.

  • android:scrollbars=”vertical” – It creates vertical scrollbar to the RecyclerView. Otherwise user never get to know how long the RecyclerView is.
  • Use android.support.v7.widget.RecyclerView as root widget if you are using the support library, attributes are same as above.

STEP 3 – Create Row Layout For RecyclerView

In this step, we will create a layout and RecyclerView will show it as child items. Right-click on the layout folder in res directory. New->Layout Resource File-> put file name as row_layout.xml and put below code.


    



  • This code creates TextView inside CardView. You can use app: namespace to specify support library attributes.
  • if you are using support library, Use android.support.v7.widget.CardView.

STEP 4 – Create An Array And Pass It To RecyclerView Adapter

<code><code>

RecyclerView adapter needs data and layout. So here, we will create an array of months and pass it to the adapter class, which you are going to make in the next step.

class MainActivity : AppCompatActivity()
{

    var months_array = arrayOf("JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE","JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER")

    lateinit var adapter :RecyclerViewAdapter

    override fun onCreate(savedInstanceState: Bundle?)
    {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        adapter = RecyclerViewAdapter(months_array)
        
    }
}

  • Creates an array of months
  • lateinit: It is used to create properties that can not initialized at first. It says to the compiler that, it will initialize later.
  • Creates adapter reference and passed the array to adapter class that you haven’t create. Don’t worry, if it shows in red color

STEP 5 – Create RecyclerViewAdapter Class

We are going to create RecyclerViewAdapter class which extends RecyclerView.Adapter.

Right-click on Java->New->Kotlin File/Class-> Put the class name as RecyclerViewAdapter and make it the same as the below code.

class RecyclerViewAdapter(var months_array: Array)
{

}

STEP 6 – Create A Custom ViewHolder Class And Extend Adapter Class With RecyclerView.Adapter

In this step, You will create an inner ViewHolder class by extending RecyclerView.ViewHolder. After initializing views in ViewHolder, makes RecyclerViewAdapter extends RecyclerView.Adapter with ViewHolder as the generic parameter. Just like below

class RecyclerViewAdapter(var months_array: Array) : RecyclerView.Adapter()
{

    inner class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView)
  {
      var textview = itemView.textview
  }
}

  • Creates Inner class ViewHolder which extends RecyclerView.ViewHolder
  • Inside viewholder class, initialize row_layout elements. here, TextView.
  • If there is red wavy underline below the RecyclerViewAdapter, then click ALT + ENTER. select implement members
  • select onCreateViewHolder(),onBindViewHolder() and getItemCount() and click OK
class RecyclerViewAdapter(var months_array: Array) : RecyclerView.Adapter()
{
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder 
    {  }

    override fun getItemCount(): Int 
    {   }

    override fun onBindViewHolder(holder: ViewHolder, p1: Int) 
     { }

    inner class ViewHolder(itemView : View) : RecyclerView.ViewHolder(itemView)
  {
      var textview = itemView.textview
  }
}


STEP 7 – Specify Total Items Using getItemCount() Method

In this step, we will return the array size in getItemCount() method.

    override fun getItemCount(): Int 
    { 
     return months_array.size
    }

  • months_array.length returns 12, JAN to DEC.

    STEP 8 – Create ViewHolder Using onCreateViewHolder() method

    In this step, I will do two important things.
    1. Layout Inflation
    2. Pass it to ViewHolder.

    This is called whenever RecyclerView needs a ViewHolder.

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder
        {
            val inflater = LayoutInflater.from(parent.context)
            val view = inflater.inflate(R.layout.row_layout,parent,false)
            return ViewHolder(view)
        }
    
    
    • parent: RecyclerView, viewType: 0, You can have different types of view. Here is only one viewtype, contain value zero.
    • Creates inflater object using context
    • row_layout inflated and become view object
    • Return ViewHolder with view for reference storage purpose

    STEP 9 – Bind ViewHolder With Data In onBindViewHolder()

    <code><code>Here we will bind our TextView with array item. Access TextView using viewholder. This method calls when the item wants to show, so here we attach data with the view in ViewHolder.

    
    override fun onBindViewHolder(holder: ViewHolder, position: Int)
        {
            holder.textview.text = months_array[position]
        }
    
    
    
    • You can access each element that initialized in ViewHolder class.
    • Here we access textview and set month from string array

    STEP 10 – Set LayoutManager and Adapter

    In this step, You will set LayoutManager and divider, at last, you will attach an adapter too.
    Let’s back to MainActivity. Put the below code in onCreate() and Run.

    
            //sets layoutmanager
            val layoutManager = LinearLayoutManager(this)
            recyclerview.layoutManager = layoutManager
            //sets divider in the list
            val dividerItemDecoration = DividerItemDecoration(this, LinearLayoutManager.VERTICAL)
            recyclerview.addItemDecoration(dividerItemDecoration)
            //Attaches adapter with RecyclerView.
            recyclerview.adapter = adapter
    
    
      • Unlike ListView, We need to implement LayoutManager for RecyclerView. Here we need a Vertical list. Use
      • Make sure you have attached LayoutManger and adapter is not empty, otherwise that may leads to error message
        “e recyclerview no adapter attached skipping layout”

    So use above code and Run

    RecyclerView is ready now.

    STEP 11 – Attach An OnClickListener with Root Element Inside ViewHolder Class

    In this step, you will learn how to get click events and react based on that. Here you will attach OnClickListener with itemView.

                inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
                {
                 var textview = itemView.textview
    
                   init 
                   {
                   itemView.setOnClickListener {
                     Toast.makeText(itemView.context, months_array[adapterPosition],Toast.LENGTH_SHORT).show()
                          }
                   }
    
                 }
            
    
    • init block is called after the constructor
    • Using lambda, Create OnClickListener
    • When item clicks, a toast will appear with Month.
    • getAdapterPosition() method returns the clicked item position, Using Kotlin synthetic property we can use “adapterPositon”here.

    Run again.
    Finally, you have made a simple RecyclerView. Congrats!

    How above RecyclerView Adapter Works?

    <code><code>how recyclerview works in android

    Okay. let’s clear it out… How RecyclerView adapter works based on the above example?

    • At first, getItemCount() method gets called and that will return 12.
    • After that, for creating ViewHolder, onCreateViewHolder() gets called. It inflates the XML layout and makes View and passes it to ViewHolder for storing references.
    • After that onBindViewHolder() gets called, here we use ViewHolder to access the TextView and attaches text. The 0th row is created.
    • The above process repeats and creates as many ViewHolders to fill the screen and even more. It depends on the screen size and layout size.
    • After that RecyclerView stops calling onCreateViewHolder but onBindViewHolder still repeats its job.

    RecyclerView With CheckBox Example In Android Studio

    recyclerview with checkbox example in android

    In this example, we will create an app that holds CheckBox and its state. While scrolling too.

    Let’s create a project.

    Open your Android Studio.

    Step 1

    Start a new Android Studio project.

    Application Name: RecyclerView With CheckBox In Android Example
    Company Domain: androidride.com

    Check Include Kotlin Support.


    Step 2

    Select form factors and minimum SDK

    Select API 15: IceCreamSandwich and Click Next.


    Step 3

    Add Empty activity to Project.


    After creating the project

    build.gradle(Module.app)

    Add the below code to the dependencies section.

    
    
    //androidx library users
    
        implementation 'androidx.cardview:cardview:1.0.0'
        implementation 'androidx.recyclerview:recyclerview:1.1.0'
    
    /*
    *If you are using the support library
        *implementation 'com.android.support:recyclerview-v7:28.0.0'
        * implementation 'com.android.support:cardview-v7:28.0.0'
        * 
        * */
    
    
    • For Kotlin users, Make sure that you have using kotlin-android-extensions

    activity_main.xml

    
    
    <!--?xml version="1.0" encoding="utf-8"?-->
    
    
    
    
    • It creates a RecyclerView with Vertical scrollbars and assigns id “recyclerview”.
    • If you are using the support library, replace androidx.recyclerview.widget.RecyclerView with android.support.v7.widget.RecyclerView.

    checkbox_row.xml

    
    <!--?xml version="1.0" encoding="utf-8"?-->
    
    
        
    
    
    
    
    • Creates a CheckBox inside a CardView.
    • Support library users – replace androidx.cardview.widget.CardView with android.support.v7.widget.CardView.

    Data.kt

    
    package com.androidride.recyclerviewwithcheckboxinandroidexample
    
    data class Data(var position: Int)
    
    
    • Only one property : position – We can pass it through constructor

    MainActivity.kt

    
    
    class MainActivity : AppCompatActivity()
    {
    
        var list = ArrayList()
    
        lateinit var  adapter : RecyclerViewAdapter
    
        override fun onCreate(savedInstanceState: Bundle?)
        {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            setupdata()
    
            adapter = RecyclerViewAdapter(list)
            //sets layoutmanager
            recyclerview.layoutManager = LinearLayoutManager(this)
            //sets adapter
            recyclerview.adapter = adapter
    
        }
    
        private fun setupdata()
        {
            for(i in 1..30)
            {//creates data object and add it to list.
                var data = Data(i)
    
                list.add(data)
            }
        }
    }
    
    
    

    RecyclerViewAdapter.kt

    
    
    class RecyclerViewAdapter(var list: ArrayList) : RecyclerView.Adapter()
    {
    
        var checkBoxStateArray = SparseBooleanArray()
    
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder
        {
            val context = parent.context
    //creates inflater
            val inflater = LayoutInflater.from(context)
    //inflates checkbox_row
            val view = inflater.inflate(R.layout.checkbox_row,parent,false)
    //returns ViewHolder with view.
            return ViewHolder(view)
        }
    //returns no of elements, 30
        override fun getItemCount(): Int = list.size
    
        override fun onBindViewHolder(holder: ViewHolder, position: Int)
        {
    
            if(!checkBoxStateArray.get(position,false))
            {//checkbox unchecked.
                holder.checkbox.isChecked = false
            }
            else
            {//checkbox checked
                holder.checkbox.isChecked = true
            }
    //gets position from data object
            var data_position = list.get(position).position
    //sets text with checkbox
            holder.checkbox.text = "CheckBox $data_position"
    
        }
    
        inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
        {//Using Kotlin Android Extensions, access checkbox
            var checkbox = itemView.checkbox
    
            init
            {//called after the constructor.
    
                checkbox.setOnClickListener {
    
                if(!checkBoxStateArray.get(adapterPosition,false))
                {//checkbox checked
                    checkbox.isChecked = true
                 //stores checkbox states and position
                    checkBoxStateArray.put(adapterPosition,true)
                }
                else
                {//checkbox unchecked
                    checkbox.isChecked = false
    //stores checkbox states and position.
                    checkBoxStateArray.put(adapterPosition,false)
                }
    
                }
            }
    
    
        }
    }
    
    • Using Kotlin synthetic properties, we can use adapterPosition for getAdapterPosition()
    • Using SparseBooleanArray, we stores position and boolean value

    Now run the project.

    <code><code>recyclerview with checkbox in android example - output

    oh, that’s a long tutorial.

    Finally, We are here.

    Guys, Shares really encourage me to create more rich content. Please share this post with your colleagues, family, and friends.

Please disable your adblocker or whitelist this site!