RecyclerView and CardView Tutorial for Beginners With RecyclerView Example

Introduction

If you love to play with applications with Grids and Lists, Android Lollipop has launched two new views RecyclerView and CardView which are very easy to use and have an excellent look and feel. RecyclerView is the new version of ListView, which makes use of Adapter as other Views. It is more advanced with great performance; it can render massive datasets and scroll very efficiently. For consistency, you can design a card with the help of CardView in the RecyclerView. This tutorial will explain the use of RecyclerView and CardView with the help of RecyclerView example.

Support For RecyclerView

Android RecyclerView is a component of Android Lollipop, but it doesn’t mean that you can not use it with the older versions. With the help of V7 Support Library, older versions can also support RecyclerView. If you want to support older versions, you just need to add dependencies for RecyclerView and CardView to the build.gradle file

Create DataModel to Populate RecyclerView

DataModel is the model for the data you want to place in the RecyclerView. This RecyclerView example needs username and contact information, so the DataModel contains only two fields i.e. username and contact.

Create a new class, DataModel.java with two private fields name and contact, also add getters along with a single setter as parameterised constructor.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

publicclassDataModel{

privateStringname;

privateintcontact;

publicDataModel(String_name,int_contact){

this.name=_name;

this.contact=_contact;

}

publicStringgetName(){

returnname;

}

publicintgetContact(){

returncontact;

}

}

Data to Initialize Data Model

You must have some data which is to be displayed in the RecyclerView. So to keep the data static and simple, here complete data is initialized in a class to use in RecyclerView.

Create Recycler Adapter

Implement MyViewHolder subclass which extends RecyclerView.ViewHolder. Also, create a method MyViewHolder(View itemView) which is previously used as Adapter type i.e. RecyclerView.Adapter<Adapter.MyViewHolder> and create the instances of TextViews of the CardView.

To implement click listener, create a subclass MyOnClickListener which implements View.OnClickListener and implement the abstract methods of the interface. For understandability, this RecyclerView example only displays the name in the Toast.