Learn Recycle view Android – Thecseguide

Introduction

Hello Everyone, Today we are going to learn very interesting and important topic in android development and that is recycle view android. Recycle-view is very important component to learn if you want to because an android developer. Majority of application uses recycle-view to show a list of data to their users. So without wasting a time let’s jump into this article and start learning about recycle-view.

Components used by recycle view android

So Before starting the implementation of recycle-view in android. Let’s first understand what components and files we are need to Implement recycle-view. I am already assuming that you have create a blank activity.

  1. First We need a Layout file which we are going to use as an holder layout for our data.
  2. Second we need an adapter class which will manage and help to show our data in the recycle view. This will work as a bridge between frontend and backend of recycle-view.
  3. Third and last create a data class which will hold all the data we are going to display on recycle-view.

So now we know that we require 3 files to start. Now let’s start designing and coding these files. Let’s first start with layout file which will work as a holder layout for the recycle-view.

Holder Layout

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/parentOfHolder"
    app:cardBackgroundColor="@color/white"
    app:cardCornerRadius="5dp"
    app:cardElevation="5dp"
    app:cardUseCompatPadding="true"
    app:cardPreventCornerOverlap="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/ChildLayOfCard"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/NameTxt"
            android:layout_width="wrap_content"
            android:layout_margin="10dp"
            android:textSize="20sp"
            android:layout_height="wrap_content"
            android:text="Name = Rohit Sharma"
            android:textStyle="bold"
            android:textColor="@color/black"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/AgeTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="Age = 18"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/NameTxt" />


        <TextView
            android:id="@+id/MarksTxt"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:text="Marks = 720/800"
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/AgeTxt" />

    </androidx.constraintlayout.widget.ConstraintLayout>


</androidx.cardview.widget.CardView>

Data Class

package thecseguide.com;


/* @author www.thecseguide.com

This class will be used to hold the data of every student we display
in recycle-view

*/

public class studentDataClass {

    String name;
    int Age;
    int Marks;

    public studentDataClass(String name, int age, int marks) {
        this.name = name;
        Age = age;
        Marks = marks;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return Age;
    }

    public void setAge(int age) {
        Age = age;
    }

    public int getMarks() {
        return Marks;
    }

    public void setMarks(int marks) {
        Marks = marks;
    }
}

Adapter Class

package thecseguide.com;


/* @author www.thecseguide.com

This is an adapter for recycle-view it is used to show the data in recycle-view
in this adapter their are three main methods to understand

1. onCreateViewHolder() = We return the layout we want to use to display out data in recycle-view.

2. onBindViewHolder() = In this method we set our data in every layout with the help of index number.

3. getItemCount() = In this method we tell our adapter about what is the size of our recycleview is going to be. So that our recycleview generates layouts according to that

*/

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;

public class AdapterForRecycleview extends RecyclerView.Adapter<AdapterForRecycleview.MyViewHolder> {

    Activity activity;
    Context context;

    List<studentDataClass> studentDataClassList;

    public AdapterForRecycleview(Activity activity, Context context, List<studentDataClass> studentDataClassList) {
        this.activity = activity;
        this.context = context;
        this.studentDataClassList = studentDataClassList;
    }

    @NonNull
    @Override
    public AdapterForRecycleview.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.holder_layout_for_recycleview,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull AdapterForRecycleview.MyViewHolder holder, int position) {

        // We are using String.valueOf() of function to convert our int values in string
        holder.AgeTxt.setText(activity.getString(R.string.age)+String.valueOf(studentDataClassList.get(position).Age));
        holder.MarksTxt.setText(activity.getString(R.string.marks)+String.valueOf(studentDataClassList.get(position).Marks + "/800"));


        holder.NameTxt.setText(activity.getString(R.string.name)+studentDataClassList.get(position).name);

    }

    @Override
    public int getItemCount() {
        return studentDataClassList.size();
    }


    // Here we are declaring the components we used in the creation of holder layout by using findViewById
    public static class MyViewHolder extends RecyclerView.ViewHolder {

        TextView NameTxt;
        TextView MarksTxt;
        TextView AgeTxt;
        public MyViewHolder(@NonNull View itemView) {
            super(itemView);


            NameTxt = itemView.findViewById(R.id.NameTxt);
            MarksTxt = itemView.findViewById(R.id.MarksTxt);
            AgeTxt = itemView.findViewById(R.id.AgeTxt);

        }
    }
}

Connect Components to recycle-view

After creating all the necessary files for recycle-view. Now let’s create activity and which will contain our recycle-view. Let’s first design layout file for the activity

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/DisplayStudentMarksRecycleview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:listitem="@layout/holder_layout_for_recycleview" />

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity.java

package thecseguide.com;

import android.os.Bundle;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    RecyclerView DisplayStudentMarksRecycleview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        DisplayStudentMarksRecycleview = findViewById(R.id.DisplayStudentMarksRecycleview);

        
        // Creating object of Adapter and then set it to recycle view
        AdapterForRecycleview adapterForRecycleview = new AdapterForRecycleview(MainActivity.this,MainActivity.this,AddStudentData());
        DisplayStudentMarksRecycleview.setAdapter(adapterForRecycleview);

    }

    
    // This AddStudentData() function will help to add dummy data of students to list and we will display this data in recycle-view

    private List<studentDataClass> AddStudentData(){

        List<studentDataClass> studentList = new ArrayList();

        studentList.add(new studentDataClass("Rahul Arora",18,500));
        studentList.add(new studentDataClass("Rohit Sharma",21,520));
        studentList.add(new studentDataClass("Keshav",18,550));
        studentList.add(new studentDataClass("John",21,595));
        studentList.add(new studentDataClass("Akshay Sharma",22,600));
        studentList.add(new studentDataClass("Aman Kanwar",23,644));
        studentList.add(new studentDataClass("Lakhwinder Singh",20,547));
        studentList.add(new studentDataClass("Kashvi",19,352));
        studentList.add(new studentDataClass("Simran Kaur",24,744));
        studentList.add(new studentDataClass("Aniket Ahuja",22,780));
        studentList.add(new studentDataClass("Vaibhav",19,533));
        studentList.add(new studentDataClass("Divya Dawar",23,643));
        studentList.add(new studentDataClass("Sanjay",22,574));

        return studentList;
    }
}

Download Source Code

If you want source code to study or to practice regarding recycle view then you can download the source code directly or clone it in android studio by clicking on this GitHub link.

Output

recycle view android

Conclusion

So I hope you guys understood that how you can implement recycle-view in android. I tried to explain you about this in an easy way. My suggestion to you guys is just don’t only read this article but also try to implement the recycle-view and still if you have any doubt then comment section is all yours. Ask me your doubts in the comment section and I will provide you solutions of your questions. If you have any suggestions please let us know by clicking on this link Contact us.

Leave a Comment