Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

CardView using RecyclerView in Android with Example

  • Difficulty Level : Medium
  • Last Updated : 09 Dec, 2020

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 implementation of CardView in RecyclerView. We should know what CardView and RecyclerView mean. 

  • CardView: CardView is an extended version of Framelayout which can be used to show items inside the card format. With the help of CardView, we can add radius, elevation to our items of RecyclerView. CardView gives a rich look and feels to our list of data. 
  • RecyclerView: RecyclerView is an extended version of ListView. in RecyclerView we can load a large amount of data and items of RecyclerView can have a custom design. RecyclerView works on ViewHolder design pattern so we have to create a Data class that holds data for RecyclerView and a ViewHolder class which will set data to each item of RecyclerView. 

RecyclerView is divided into 3 sections: 

Want a more fast-paced & competitive environment to learn the fundamentals of Android?
Click here to head to a guide uniquely curated by our experts with the aim to make you industry ready in no time!
  • Card Layout.
  • Modal Class.
  • ViewHolder class. 

Now we will move towards the implementation of our RecyclerView.

Example

A sample image is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 



CardView using RecyclerView in Android

So we are creating a simple example for displaying various courses available on GFG in the RecyclerView using a Card Layout.  

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add dependency for creating CardView and RecyclerView

Navigate to the Gradle Scripts > build.gradle(Module:app) and add below dependency in the dependency section. 

implementation ‘com.google.android.material:material:1.2.1’

Step 3: Create RecyclerView Card Layout 



Card Layout: Card Layout is used to display a list of data. It is the design of a single item of our RecyclerView. For creating a Card Layout navigate to the app > res > layout > Right-Click on it > New > Layout Resource File > Give a name to it(here card_layout). Now we will write a code for our Card Layout of our RecyclerView. Below is the code for the card_layout.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    app:cardBackgroundColor="@color/white"
    app:cardCornerRadius="8dp"
    app:cardElevation="8dp"
    app:cardMaxElevation="10dp"
    app:cardPreventCornerOverlap="true"
    app:cardUseCompatPadding="true">
      
    <!--
        In the above cardview widget
        cardelevation property will give elevation to your card view
        card corner radius will provide radius to your card view
        card background color will give background color to your card view
        card max elevation will give the cardview maximum elevation
        card prevent corner overlap will add padding to CardView on v20 and 
        before to prevent intersections between the Card content and rounded corners.
        card use compact padding will add padding in API v21+ as well to have the same
        measurements with previous versions.
    -->
  
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
          
        <!--ImageVIew to display our Course Image-->
        <ImageView
            android:id="@+id/idIVCourseImage"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_margin="10dp"
            android:contentDescription="@string/app_name"
            android:padding="5dp"
            android:src="@drawable/gfgimage" />
          
        <!--Text View to display Course Name-->
        <TextView
            android:id="@+id/idTVCourseName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:layout_marginTop="10dp"
            android:layout_toEndOf="@id/idIVCourseImage"
            android:text="@string/course_name"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold" />
          
        <!--Text VIew to display COurse Rating-->
        <!--Image used in present in drawable folder-->
        <TextView
            android:id="@+id/idTVCourseRating"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/idTVCourseName"
            android:layout_marginStart="10dp"
            android:layout_marginTop="20dp"
            android:layout_toEndOf="@id/idIVCourseImage"
            android:drawablePadding="2dp"
            android:text="@string/course_rating"
            app:drawableStartCompat="@drawable/ic_star" />
    </RelativeLayout>
</androidx.cardview.widget.CardView>

Step 4: Create a Model Class for storing data

Navigate to the app > java > your apps package name > Right-click on it > New > Java and name the Modal Class(here CourseModel). Model Class will store the data which we will display in our Recycler View. Below is the code for the CourseModel.java file.

Java




public class CourseModel {
  
    private String course_name;
    private int course_rating;
    private int course_image;
  
    // Constructor
    public CourseModel(String course_name, int course_rating, int course_image) {
        this.course_name = course_name;
        this.course_rating = course_rating;
        this.course_image = course_image;
    }
  
    // Getter and Setter
    public String getCourse_name() {
        return course_name;
    }
  
    public void setCourse_name(String course_name) {
        this.course_name = course_name;
    }
  
    public int getCourse_rating() {
        return course_rating;
    }
  
    public void setCourse_rating(int course_rating) {
        this.course_rating = course_rating;
    }
  
    public int getCourse_image() {
        return course_image;
    }
  
    public void setCourse_image(int course_image) {
        this.course_image = course_image;
    }
}

Step 5: Create Adapter Class for setting data to items of RecyclerView 

Navigate to the app > java > your apps package name > Right Click on it > New > Java Class and name your Adapter Class(Here CourseAdapter). Adapter Class in RecyclerView will get the data from your Modal Class and set that data to your item of RecyclerView. Below is the code for the CourseAdapter.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
  
public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.Viewholder> {
  
    private Context context;
    private ArrayList<CourseModel> courseModelArrayList;
  
    // Constructor
    public CourseAdapter(Context context, ArrayList<CourseModel> courseModelArrayList) {
        this.context = context;
        this.courseModelArrayList = courseModelArrayList;
    }
  
    @NonNull
    @Override
    public CourseAdapter.Viewholder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // to inflate the layout for each item of recycler view.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false);
        return new Viewholder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull CourseAdapter.Viewholder holder, int position) {
        // to set data to textview and imageview of each card layout
        CourseModel model = courseModelArrayList.get(position);
        holder.courseNameTV.setText(model.getCourse_name());
        holder.courseRatingTV.setText("" + model.getCourse_rating());
        holder.courseIV.setImageResource(model.getCourse_image());
    }
  
    @Override
    public int getItemCount() {
        // this method is used for showing number
        // of card items in recycler view.
        return courseModelArrayList.size();
    }
  
    // View holder class for initializing of 
    // your views such as TextView and Imageview.
    public class Viewholder extends RecyclerView.ViewHolder {
        private ImageView courseIV;
        private TextView courseNameTV, courseRatingTV;
  
        public Viewholder(@NonNull View itemView) {
            super(itemView);
            courseIV = itemView.findViewById(R.id.idIVCourseImage);
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseRatingTV = itemView.findViewById(R.id.idTVCourseRating);
        }
    }
}

Step 6: Now we will move towards creating our RecyclerView

For creating of our RecyclerView. Navigate to the app > res > layout > activity_main.xml and add RecyclerView as shown below. Below is the code for the activity_main.xml file.



XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRVCourse"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
  
</RelativeLayout>

Step 7: Now we will initialize our RecyclerView in our MainActivity.java

Navigate to the app > java > your apps package name > MainActivity.java and initialize your RecyclerView. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    private RecyclerView courseRV;
    
    // Arraylist for storing data
    private ArrayList<CourseModel> courseModelArrayList;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        courseRV = findViewById(R.id.idRVCourse);
          
        // here we have created new array list and added data to it.
        courseModelArrayList = new ArrayList<>();
        courseModelArrayList.add(new CourseModel("DSA in Java", 4, R.drawable.gfgimage));
        courseModelArrayList.add(new CourseModel("Java Course", 3, R.drawable.gfgimage));
        courseModelArrayList.add(new CourseModel("C++ COurse", 4, R.drawable.gfgimage));
        courseModelArrayList.add(new CourseModel("DSA in C++", 4, R.drawable.gfgimage));
        courseModelArrayList.add(new CourseModel("Kotlin for Android", 4, R.drawable.gfgimage));
        courseModelArrayList.add(new CourseModel("Java for Android", 4, R.drawable.gfgimage));
        courseModelArrayList.add(new CourseModel("HTML and CSS", 4, R.drawable.gfgimage));
  
        // we are initializing our adapter class and passing our arraylist to it.
        CourseAdapter courseAdapter = new CourseAdapter(this, courseModelArrayList);
  
        // below line is for setting a layout manager for our recycler view.
        // here we are creating vertical list so we will provide orientation as vertical
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
          
        // in below two lines we are setting layoutmanager and adapter to our recycler view.
        courseRV.setLayoutManager(linearLayoutManager);
        courseRV.setAdapter(courseAdapter);
    }
}

Now run the app on Emulator and see the output.

Note

Star used as an image is stored in our drawable folder. Strings used are present in our strings.xml.

  • strings.xml: Navigate to the app > res > values > strings.xml to add various strings in your app. 
  • drawable: Navigate to the app > res > drawable to add images used for your app.  

Output: 

CardView using RecyclerView in Android Output




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!