Signup/Sign In
PUBLISHED ON: AUGUST 10, 2021

Android Recycler View

In this article, we are going to add Recycler View to our android app. For doing this, we use Recycler View. Recycler View is a View in android studio which is similar to Listview but with more controls and features. So, let's create a project.

Step 1: Create a new Project

  1. Open Your Android Studio Click on "Start a new Android Studio project"(Learn how to set up Android Studio and create your first Android project).

  2. Choose "Empty Activity" from the project template window and click Next.

  3. Enter the App Name, Package name, save location, language(Java/Kotlin, we use Java for this tutorial ), and minimum SDK(we are using API 19: Android 4.4 (KitKat)).

  4. Next click on the Finish button after filling in all the details,

  5. Now, wait for the project to finish building.

Step 2: Adding the dependency

Go to Gradle Scripts -> build.gradle (Module: app) section and import below dependencies, and click the "sync Now" show at the top:

dependencies
{
//Adding Recycler view 
 implementation 'androidx.recyclerview:recyclerview:1.2.1'
}

Step 3: UI Part

Before applying any changes to the activity_main.xml file, we need an image and text which we will show in the Recycler View, you can download any images and put the image in the app -> res -> drawable, and give it a suitable name.

Now, go to app -> res -> layout -> activity_main.xml and add RecyclerView as shown below.

<?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">

    <!-- Recycler view -->
    <androidx.recyclerview.widget.RecyclerView
        android:id = "@+id/recycleView"
        android:layout_width = "match_parent"
        android:layout_height = "match_parent"/>
</RelativeLayout>

Next, we create a new layout resource file ( recyclerview_row.xml ) inside it, we add a simple ImageView and TextView set. The complete code of recyclerview_row.xml is shown below

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/listPreferredItemHeightLarge"
    android:id="@+id/relativeLayout">
    <ImageView
        android:padding="4dp"
        android:layout_centerVertical="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentLeft="true"
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
       android:layout_margin="8dp"
        android:contentDescription="Icon" />
    <TextView
        android:textStyle="bold"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/textView"
        android:layout_toEndOf="@id/imageView"
        android:gravity="center_vertical"
        android:textSize="24sp"/>
</RelativeLayout>

Step 4: Coding Part

First, we create a MyData.java class, and add the following code as shown below.

package com.studytonight.project;

public class MyData {

    private String desc;
    private int imgId;
    public MyData(String desc, int imgId) {
        this.desc = desc;
        this.imgId = imgId;
    }
    public String getDescription() {
        return desc;
    }
    public int getImgId() {
        return imgId;
    }
}

Then, we create a new RecyclerViewAdapter.java class and extend it to RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> and implements some of its methods as shown below.

package com.studytonight.project;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.recyclerview.widget.RecyclerView;
public class RecyclerViewAdapter extends RecyclerView.Adapter < RecyclerViewAdapter.ViewHolder > {
    private MyData[] mydata;
    // RecyclerView recyclerView;  
    public RecyclerViewAdapter(MyData[] mydata) {
        this.mydata = mydata;
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
        View listItem = layoutInflater.inflate(R.layout.recyclerview_row, parent, false);
        ViewHolder viewHolder = new ViewHolder(listItem);
        return viewHolder;
    }
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        final MyData MyData = mydata[position];
        holder.textView.setText(mydata[position].getDescription());
        holder.imageView.setImageResource(mydata[position].getImgId());
        holder.relativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(view.getContext(), "click on item: " + MyData.getDescription(), Toast.LENGTH_LONG).show();
            }
        });
    }
    @Override
    public int getItemCount() {
        return mydata.length;
    }
    public static class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView imageView;
        public TextView textView;
        public RelativeLayout relativeLayout;
        public ViewHolder(View itemView) {
            super(itemView);
            this.imageView = (ImageView) itemView.findViewById(R.id.imageView);
            this.textView = (TextView) itemView.findViewById(R.id.textView);
            relativeLayout = (RelativeLayout) itemView.findViewById(R.id.relativeLayout);
        }
    }
}

Finally, we add data to the recycler view and show it to the user. The complete code of the MainActivity.java is shown below:

package com.studytonight.project;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);        
        MyData[] myListData = new MyData[]{
                new MyData("Upload", R.drawable.u1),
                new MyData("Chart", R.drawable.u2),
                new MyData("Wifi", R.drawable.u3),
                new MyData("Clock", R.drawable.u4),
                new MyData("Video", R.drawable.u5),
                new MyData("Share", R.drawable.u6),
                new MyData("Download", R.drawable.u7),
                new MyData("Torch", R.drawable.u8),
                new MyData("Delete", R.drawable.u9),
                new MyData("Phone", R.drawable.u10),
                new MyData("Bluetooth", R.drawable.u11),
                new MyData("Processor", R.drawable.u12),
        };
        RecyclerView recyclerViewOKL = (RecyclerView) findViewById(R.id.recycleView);
        RecyclerViewAdapter adapter = new RecyclerViewAdapter(myListData);
        recyclerViewOKL.setHasFixedSize(true);
        recyclerViewOKL.setLayoutManager(new LinearLayoutManager(MainActivity.this));
        recyclerViewOKL.setAdapter(adapter);
    }
}

Output:

In the below snapshots, you can see how Recycler View will look in the android application.

When App is opened for the first time:

When we scroll Down

When we click on the item



About the author:
K S Lohan is an accomplished author and expert in technical writing on Android language and develop android App. He is highly skilled at communicating complex programming concepts in a clear and concise manner.