Thursday, December 26, 2024
Google search engine
HomeLanguagesJavaCardView using RecyclerView in Android with Example

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 extended version of Framelayout which can be used to show items inside the card format. With the help of CardView, we can add radius and 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 the 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: 

  • Card Layout.
  • Modal Class.
  • ViewHolder class. 

Now we will move towards the implementation of our RecyclerView.

CardView using RecyclerView in Android

 

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in both Java and Kotlin Programming Language for Android.

Step 2: Add the Required Dependencies

Navigate to the Gradle Scripts > build.gradle(Module:app) and Add the Below Dependency in the Dependencies section.

implementation 'com.google.android.material:material:1.2.1'

Add the Support Library in your settings.gradle File. This library Jitpack is a novel package repository. It is made for JVM so that any library which is present in Github and Bitbucket can be directly used in the application.

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
        
        // add the following
        maven { url "https://jitpack.io" }
    }
}

After adding this Dependency, Sync the Project and now we will move towards its implementation.

Step 3: Working with the XML Files

Card Layout: A 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 the 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 xmlns:android="http://schemas.android.com/apk/res/android"
    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 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;
    }
}


Kotlin




class CourseModel (private var course_name: String, private var course_rating: Int, private var course_image: Int) {
     
    // Getter and Setter
    fun getCourse_name(): String {
        return course_name
    }
 
    fun setCourse_name(course_name: String) {
        this.course_name = course_name
    }
 
    fun getCourse_rating(): Int {
        return course_rating
    }
 
    fun setCourse_rating(course_rating: Int) {
        this.course_rating = course_rating
    }
 
    fun getCourse_image(): Int {
        return course_image
    }
 
    fun setCourse_image(course_image: Int) {
        this.course_image = course_image
    }
}


Step 5: Create an Adapter Class for Setting Data 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 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 final Context context;
    private final 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 static class ViewHolder extends RecyclerView.ViewHolder {
        private final ImageView courseIV;
        private final TextView courseNameTV;
        private final TextView 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);
        }
    }
}


Kotlin




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.recyclerview.widget.RecyclerView
 
class CourseAdapter(private val context: Context, courseModelArrayList: ArrayList<CourseModel>) :
    RecyclerView.Adapter<CourseAdapter.Viewholder>() {
    private val courseModelArrayList: ArrayList<CourseModel>
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CourseAdapter.Viewholder {
        // to inflate the layout for each item of recycler view.
        val view: View = LayoutInflater.from(parent.context).inflate(R.layout.card_layout, parent, false)
        return Viewholder(view)
    }
 
    override fun onBindViewHolder(holder: CourseAdapter.Viewholder, position: Int) {
        // to set data to textview and imageview of each card layout
        val model: CourseModel = courseModelArrayList[position]
        holder.courseNameTV.setText(model.getCourse_name())
        holder.courseRatingTV.setText("" + model.getCourse_rating())
        holder.courseIV.setImageResource(model.getCourse_image())
    }
 
    override fun getItemCount(): Int {
        // 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.
    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val courseIV: ImageView
        private val courseNameTV: TextView
        private val courseRatingTV: TextView
        init {
            courseIV = itemView.findViewById(R.id.idIVCourseImage)
            courseNameTV = itemView.findViewById(R.id.idTVCourseName)
            courseRatingTV = itemView.findViewById(R.id.idTVCourseRating)
        }
    }
 
    // Constructor
    init {
        this.courseModelArrayList = courseModelArrayList
    }
}


Step 6: Create RecyclerView

For creating 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:android="http://schemas.android.com/apk/res/android"
    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: Initializing RecyclerView in our MainActivity

Navigate to the app > java > your apps package name > MainActivity and initialize your RecyclerView. Below is the code for the MainActivity 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 {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        RecyclerView courseRV = findViewById(R.id.idRVCourse);
 
        // Here, we have created new array list and added data to it
        ArrayList<CourseModel> courseModelArrayList = new ArrayList<CourseModel>();
        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);
    }
}


Kotlin




import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
 
class MainActivity : AppCompatActivity() {
         
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        val courseRV = findViewById<RecyclerView>(R.id.idRVCourse)
 
        // Here, we have created new array list and added data to it
        val courseModelArrayList: ArrayList<CourseModel> = ArrayList<CourseModel>()
        courseModelArrayList.add(CourseModel("DSA in Java", 4, R.drawable.gfgimage))
        courseModelArrayList.add(CourseModel("Java Course", 3, R.drawable.gfgimage))
        courseModelArrayList.add(CourseModel("C++ Course", 4, R.drawable.gfgimage))
        courseModelArrayList.add(CourseModel("DSA in C++", 4, R.drawable.gfgimage))
        courseModelArrayList.add(CourseModel("Kotlin for Android", 4, R.drawable.gfgimage))
        courseModelArrayList.add(CourseModel("Java for Android", 4, R.drawable.gfgimage))
        courseModelArrayList.add(CourseModel("HTML and CSS", 4, R.drawable.gfgimage))
 
        // we are initializing our adapter class and passing our arraylist to it.
        val courseAdapter = 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
        val linearLayoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
 
        // in below two lines we are setting layoutmanager and adapter to our recycler view.
        courseRV.layoutManager = linearLayoutManager
        courseRV.adapter = courseAdapter
    }
}


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

 

RELATED ARTICLES

Most Popular

Recent Comments