Android

Simple Android RecyclerView Example

Pinterest LinkedIn Tumblr

RecyclerView is the ViewGroup that renders adapter-based views in the simplest form. Before RecyclerView, ListView and GridView were used for creating the List base items. It is introduced in Marshmallow.

RecyclerView is the advanced version of ListView and GridView. Due to its extensible framework, it has the ability to provides the List in both Horizontal and Vertical orientation by using its LinearLayoutManager class.

As said above, RecyclerView can create the list in Horizontal and Vertical orientation. You can create the list in Grid format by using GridLayoutManager class. In this article, you will learn, How to display the data in horizontal, vertical, and Grid format?

  1. For horizontal and vertical display, you will use LinearLayoutManager class which provides the option to set the orientation.
  2. In grid display, you will use GridLayoutManager class, in this class, you will tell to the manager, how many columns will have in the single row?
  3. For vertical, horizontal and grid display, RecyclerViewHolder class will use for holding the single row or column.

Article Contents

Step-1 (Create A New Project)

Open Android Studio and create the new project by clicking on File=>New. Write the project name, select Java language and save the project in your desired location. Select the blank template from the given templates.

Step-2 (Gradle File)

Now the project is ready and you will have MainActivity.java class. On the other hand, in the res folder, you will have the activity_main.xml file. Open the project build.gradle.xml file and add the following dependencies to the project.

    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.3.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'

Step-3 (strings.xml File)

Copy the following lines of code in the strings.xml file.

<resources>
    <string name="app_name">RecyclerViewDemo</string>
    <string name="tv_title_celebrity">Celebrity Title</string>
    <string name="tv_description_celebrity">It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout</string>


    <!-- Main Activity -->
    <string name="tv_title_str">RecyclerView Demo (Java)</string>
    <string name="tv_description_str">In this demo, you will learn, how to display the data in RecyclerView in different orientation e.g Vertical, Horizontal and Grid?</string>
    <string name="btn_vertical_str">Vertical Demo</string>
    <string name="btn_horizontal_str">Horizontal Demo</string>
    <string name="btn_grid_str">Grid Demo</string>
    <string name="tv_likes">Likes (%d)</string>
</resources>

Step-4 (colors.xml File)

Following colors codes are using throughout this project, copy the following code and paste in colors.xml file.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="purple_200">#FFBB86FC</color>
    <color name="purple_500">#FF6200EE</color>
    <color name="purple_700">#FF3700B3</color>
    <color name="teal_200">#FF03DAC5</color>
    <color name="teal_700">#FF018786</color>
    <color name="black">#FF000000</color>
    <color name="white">#FFFFFFFF</color>

    <!-- Demo Color codes-->
    <color name="color_of_title">#F70303</color>
    <color name="color_of_description">#000000</color>
    <color name="color_of_likes">#111212</color>
    <color name="color_heading">#F80000</color>
    <color name="color_red_one">#FA2E2E</color>
    <color name="color_btn">#515CB2</color>
</resources>

Step-5 (Vertical Demo Adapter XML File)

As per the design, first, create the design. Explore the res folder and right-click on the layout folder. Choose New=>Android Resource File. Enter the name of the file e.g adapter_vertical_recycler_view_row. In the layout folder, your file will look like this adapter_vertical_recycler_view_row.xml. Enter the following code in this file.

<?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:layout_width="match_parent"
    app:cardUseCompatPadding="true"
    app:cardCornerRadius="5dp"
    android:layout_margin="5dp"
    android:elevation="5dp"
    android:layout_height="120dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_margin="5dp"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imgCelebrity"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/img_celebrity"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:fontFamily="@font/roboto"
            android:text="@string/tv_title_celebrity"
            android:textColor="@color/color_of_title"
            android:textSize="18sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/imgCelebrity"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/tvDescription"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/roboto"
            android:lines="2"
            android:ellipsize="end"
            android:text="@string/tv_description_celebrity"
            android:textColor="@color/color_of_description"
            android:textSize="14sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="@+id/tvTitle"
            app:layout_constraintTop_toBottomOf="@+id/tvTitle" />

        <ImageView
            android:id="@+id/imgHeart"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_heart"
            app:layout_constraintTop_toBottomOf="@+id/tvDescription"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="@id/tvTitle" />
        <TextView
            android:id="@+id/tvLikes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/roboto"
            android:text="@string/tv_likes"
            android:textColor="@color/color_of_likes"
            android:layout_marginStart="5dp"
            android:textSize="14sp"
            app:layout_constraintStart_toEndOf="@+id/imgHeart"
            app:layout_constraintBottom_toBottomOf="@+id/imgHeart"
            app:layout_constraintTop_toTopOf="@+id/imgHeart" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

Step-6 (Modal Class Java File)

If you don’t want to use the modal class, you can simply make a list of any data type and use it in the adapter class, but I will recommend to you, the best approach is to create the modal class and use it in the Adapter class.

Create the CelebrithModal.java file and add the following codes. You can modify this modal class according to your logic

package com.procodeguru.recyclerview;

/**
 * Created by procodeguru.com on 19,05,2021
 */
public class CelebrityModal {
    private String title;
    private String description;
    private int likes;

    public CelebrityModal(String title, String description, int likes) {
        this.title = title;
        this.description = description;
        this.likes = likes;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getLikes() {
        return likes;
    }

    public void setLikes(int likes) {
        this.likes = likes;
    }
}

Step-7 (Create the Vertical Demo Adapter class)

Now design is ready, now we will create the Adapter class which will hold the data. Above, I told you, for RecycleView, the Adapter class is a must, without an Adapter class, you cannot display the listing.

Right-click on the package from the java folder and add a new Java class and renamed it with AdapterVerticalDemoCelebrity.java. Now create the inner class and renamed it with CelebrityViewHolder. In this holder class, extends the abstract class RecyclerView.ViewHolder. In CelebrityViewHolder class, initialize all the views, which. you’re going to use. This class will look like this

private class CelebrityViewHolder extends RecyclerView.ViewHolder {
        private TextView tvTitle;
        private TextView tvDescription;
        private TextView tvLikes;

        public CelebrityViewHolder(View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tvTitle);
            tvDescription = itemView.findViewById(R.id.tvDescription);
            tvLikes = itemView.findViewById(R.id.tvLikes);
        }
    }

ViewHolder is ready and now extends the RecyclerView.Adapter abstract class in AdapterVerticalDemoCelebrity.java. This will override the following three methods

  • onCreateViewHolder
  • onBindViewHolder
  • getItemCount

In the onCreateViewHolder method, you will inflate your XML file and will pass the view of this XML file to the constructor of the CelebrityViewHolder.java look like this

  @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        _context = parent.getContext();
        View v1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_vertical_recycler_view_row, parent, false);
        return new CelebrityViewHolder(v1);
    }

Now in the second onBindViewHolder method, fetch the data from the list and display it in the row. See the following code

@Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        CelebrityViewHolder celebrityViewHolder = (CelebrityViewHolder) holder;
        CelebrityModal celebrityModal = celebrityModalList.get(position);
        celebrityViewHolder.tvTitle.setText(celebrityModal.getTitle());
        celebrityViewHolder.tvDescription.setText(celebrityModal.getDescription());
        celebrityViewHolder.tvLikes.setText(String.format(_context.getString(R.string.tv_likes), celebrityModal.getLikes()));
    }

In this third getItemCount method, return the size of the list like this

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

Now AdapterVerticalDemoCelebrity.java is ready. The full code of this class will look like this

package com.procodeguru.recyclerview;

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;

/**
 * Created by procodeguru.com on 19,05,2021
 */
public class AdapterVerticalDemoCelebrity extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<CelebrityModal> celebrityModalList;
    private Context _context;

    public AdapterVerticalDemoCelebrity(List<CelebrityModal> celebrityModalList) {
        this.celebrityModalList = celebrityModalList;
    }

    private class CelebrityViewHolder extends RecyclerView.ViewHolder {
        private TextView tvTitle;
        private TextView tvDescription;
        private TextView tvLikes;

        public CelebrityViewHolder(View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tvTitle);
            tvDescription = itemView.findViewById(R.id.tvDescription);
            tvLikes = itemView.findViewById(R.id.tvLikes);
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        _context = parent.getContext();
        View v1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_vertical_recycler_view_row, parent, false);
        return new CelebrityViewHolder(v1);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        CelebrityViewHolder celebrityViewHolder = (CelebrityViewHolder) holder;
        CelebrityModal celebrityModal = celebrityModalList.get(position);
        celebrityViewHolder.tvTitle.setText(celebrityModal.getTitle());
        celebrityViewHolder.tvDescription.setText(celebrityModal.getDescription());
        celebrityViewHolder.tvLikes.setText(String.format(_context.getString(R.string.tv_likes), celebrityModal.getLikes()));
    }

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

Step-8 (Vertical Demo Activity XML File)

Now create the activity_recycler_view_vertical.xml file. Add RecyclerView components in this XML file. Put the following code in this file

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".RecyclerViewVerticalDemoActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rcvCelebrity"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step-9 (RecyclerView Vertical Demo Activity Java file)

Now create the Activity class which will navigate from MainActivity by clicking on the vertical demo button. Create the RecyclerViewVerticalDemoActivity.java and put the following code. Because this is a demo, so will display the demo celebrity data.

package com.procodeguru.recyclerview;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;

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

public class RecyclerViewVerticalDemoActivity extends AppCompatActivity {
    private List<CelebrityModal> celebrityModalList;
    private AdapterVerticalDemoCelebrity adapterVerticalCelebrity;
    private RecyclerView rcvCelebrity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view_vertical);
        initComponents();
        setDummyDataToAdapter();
    }

    /**
     * initialize the all components
     */
    private void initComponents() {
        celebrityModalList = new ArrayList<>();
        rcvCelebrity = findViewById(R.id.rcvCelebrity);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
        rcvCelebrity.setLayoutManager(linearLayoutManager);
        adapterVerticalCelebrity = new AdapterVerticalDemoCelebrity(celebrityModalList);
        rcvCelebrity.setAdapter(adapterVerticalCelebrity);
    }

    /**
     * set the dummy date and notify to adapter.
     */
    private void setDummyDataToAdapter() {
        Random random = new Random();
        String title = getString(R.string.tv_title_celebrity);
        String description = getString(R.string.tv_description_celebrity);
        for (int j = 0; j < 20; j++) {
            CelebrityModal celebrityModal = new CelebrityModal(title, description, j * random.nextInt(25));
            celebrityModalList.add(celebrityModal);
        }
        adapterVerticalCelebrity.notifyDataSetChanged();
    }
}

Step-10 (Horizontal Demo Adapter Row XML File)

For the horizontal demo, right-click on the layout folder and create an Android Resource File called adapter_horizontal_recycler_view_row.xml. Copy and paste the following code

<?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:layout_width="220dp"
    app:cardUseCompatPadding="true"
    app:cardCornerRadius="5dp"
    android:layout_margin="5dp"
    android:elevation="5dp"
    android:layout_height="250dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_margin="5dp"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imgCelebrity"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/img_celebrity"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:fontFamily="@font/roboto"
            android:text="@string/tv_title_celebrity"
            android:textColor="@color/color_of_title"
            android:textSize="18sp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/imgCelebrity" />

        <TextView
            android:id="@+id/tvDescription"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/roboto"
            android:lines="3"
            android:ellipsize="end"
            android:text="@string/tv_description_celebrity"
            android:textColor="@color/color_of_description"
            android:textSize="14sp"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tvTitle" />

        <ImageView
            android:id="@+id/imgHeart"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_heart"
            app:layout_constraintTop_toTopOf="@+id/tvLikes"
            android:layout_marginEnd="5dp"
            app:layout_constraintBottom_toBottomOf="@+id/tvLikes"
            app:layout_constraintEnd_toStartOf="@+id/tvLikes" />
        <TextView
            android:id="@+id/tvLikes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/roboto"
            android:text="@string/tv_likes"
            android:textColor="@color/color_of_likes"
            android:layout_marginStart="5dp"
            android:textSize="14sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tvDescription"
            app:layout_constraintBottom_toBottomOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

Step-11 (Horizontal Demo Adapter Java File)

This class will create the same as we created for the vertical demo adapter class. We will change the XML file and all other code will be the same. You can change according to your logic if the design is different.

package com.procodeguru.recyclerview;

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;

/**
 * Created by procodeguru.com on 19,05,2021
 */
public class AdapterHorizontalDemoCelebrity extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    private List<CelebrityModal> celebrityModalList;
    private Context _context;

    public AdapterHorizontalDemoCelebrity(List<CelebrityModal> celebrityModalList) {
        this.celebrityModalList = celebrityModalList;
    }

    private class CelebrityViewHolder extends RecyclerView.ViewHolder {
        private TextView tvTitle;
        private TextView tvDescription;
        private TextView tvLikes;

        public CelebrityViewHolder(View itemView) {
            super(itemView);
            tvTitle = itemView.findViewById(R.id.tvTitle);
            tvDescription = itemView.findViewById(R.id.tvDescription);
            tvLikes = itemView.findViewById(R.id.tvLikes);
        }
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        _context = parent.getContext();
        View v1 = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_horizontal_recycler_view_row, parent, false);
        return new CelebrityViewHolder(v1);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        CelebrityViewHolder celebrityViewHolder = (CelebrityViewHolder) holder;
        CelebrityModal celebrityModal = celebrityModalList.get(position);
        celebrityViewHolder.tvTitle.setText(celebrityModal.getTitle());
        celebrityViewHolder.tvDescription.setText(celebrityModal.getDescription());
        celebrityViewHolder.tvLikes.setText(String.format(_context.getString(R.string.tv_likes), celebrityModal.getLikes()));
    }

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

Step-12 (Horizontal Demo Activity Java File)

Now create the RecyclerViewHorizontalActivity.java class which will navigation from MainActivity.java. Now we will create the object of LinearLayoutManager class and will set the orientation horizontal.

package com.procodeguru.recyclerview;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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

public class RecyclerViewHorizontalDemoActivity extends AppCompatActivity {
    private List<CelebrityModal> celebrityModalList;
    private AdapterHorizontalDemoCelebrity adapterHorizontalDemoCelebrity;
    private RecyclerView rcvCelebrity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view_vertical);
        initComponents();
        setDummyDataToAdapter();
    }

    /**
     * initialize the all components
     */
    private void initComponents() {
        celebrityModalList = new ArrayList<>();
        rcvCelebrity = findViewById(R.id.rcvCelebrity);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(RecyclerView.HORIZONTAL);
        rcvCelebrity.setLayoutManager(linearLayoutManager);
        adapterHorizontalDemoCelebrity = new AdapterHorizontalDemoCelebrity(celebrityModalList);
        rcvCelebrity.setAdapter(adapterHorizontalDemoCelebrity);
    }

    /**
     * set the dummy date and notify to adapter.
     */
    private void setDummyDataToAdapter() {
        Random random = new Random();
        String title = getString(R.string.tv_title_celebrity);
        String description = getString(R.string.tv_description_celebrity);
        for (int j = 0; j < 20; j++) {
            CelebrityModal celebrityModal = new CelebrityModal(title, description, j * random.nextInt(25));
            celebrityModalList.add(celebrityModal);
        }
        adapterHorizontalDemoCelebrity.notifyDataSetChanged();
    }
}

Step-13 (Grid Demo Adapter XML File)

The grid adapter design is the same as the horizontal demo design. But we’ll separate create the design. Right-click on the layout folder and create a new Android Resource File called adapter_grid_recycler_view_row.xml.

<?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:layout_width="match_parent"
    app:cardUseCompatPadding="true"
    app:cardCornerRadius="5dp"
    android:layout_margin="5dp"
    android:elevation="5dp"
    android:layout_height="220dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_margin="5dp"
        android:layout_height="match_parent">

        <ImageView
            android:id="@+id/imgCelebrity"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/img_celebrity"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/tvTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="10dp"
            android:fontFamily="@font/roboto"
            android:text="@string/tv_title_celebrity"
            android:textColor="@color/color_of_title"
            android:textSize="18sp"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/imgCelebrity" />

        <TextView
            android:id="@+id/tvDescription"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:fontFamily="@font/roboto"
            android:lines="2"
            android:ellipsize="end"
            android:text="@string/tv_description_celebrity"
            android:textColor="@color/color_of_description"
            android:textSize="14sp"
            android:layout_marginStart="10dp"
            android:layout_marginEnd="10dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tvTitle" />

        <ImageView
            android:id="@+id/imgHeart"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/ic_heart"
            app:layout_constraintTop_toTopOf="@+id/tvLikes"
            android:layout_marginEnd="5dp"
            app:layout_constraintBottom_toBottomOf="@+id/tvLikes"
            app:layout_constraintEnd_toStartOf="@+id/tvLikes" />
        <TextView
            android:id="@+id/tvLikes"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/roboto"
            android:text="@string/tv_likes"
            android:textColor="@color/color_of_likes"
            android:layout_marginStart="5dp"
            android:textSize="14sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/tvDescription"
            app:layout_constraintBottom_toBottomOf="parent" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</androidx.cardview.widget.CardView>

Step-14 (Grid Demo Activity Java File)

Now as same like other activities classes, create the RecyclerViewDemoActivity.java file. Put the following codes in this file

package com.procodeguru.recyclerview;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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

public class RecyclerViewGridDemoActivity extends AppCompatActivity {
    private List<CelebrityModal> celebrityModalList;
    private AdapterGridDemoCelebrity adapterGridDemoCelebrity;
    private RecyclerView rcvCelebrity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recycler_view_vertical);
        initComponents();
        setDummyDataToAdapter();
    }

    /**
     * initialize the all components
     */
    private void initComponents() {
        celebrityModalList = new ArrayList<>();
        rcvCelebrity = findViewById(R.id.rcvCelebrity);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,2);
        rcvCelebrity.setLayoutManager(gridLayoutManager);
        adapterGridDemoCelebrity = new AdapterGridDemoCelebrity(celebrityModalList);
        rcvCelebrity.setAdapter(adapterGridDemoCelebrity);
    }

    /**
     * set the dummy date and notify to adapter.
     */
    private void setDummyDataToAdapter() {
        Random random = new Random();
        String title = getString(R.string.tv_title_celebrity);
        String description = getString(R.string.tv_description_celebrity);
        for (int j = 0; j < 20; j++) {
            CelebrityModal celebrityModal = new CelebrityModal(title, description, j * random.nextInt(25));
            celebrityModalList.add(celebrityModal);
        }
        adapterGridDemoCelebrity.notifyDataSetChanged();
    }
}

Step-15 (Button Background Drawable XML File)

In the design, buttons are in a rounded shape, for a rounded shape, we will create the drawable file which will use for the button background.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="50dp"/>
    <solid android:color="@color/color_btn"/>
</shape>

Step-16 (Activity Main XML File)

In this file, we will have three buttons. By clicking on these buttons, we will open the vertical, horizontal, and grid demo screens. Create the activity_main.xml file and put the following code in this file

<?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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvHeading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:fontFamily="@font/roboto"
        android:text="@string/tv_title_str"
        android:textColor="@color/color_red_one"
        android:textSize="22sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tvParagraph"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="@font/roboto"
        android:text="@string/tv_description_str"
        android:padding="5dp"
        android:textColor="@color/black"
        android:textSize="18sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvHeading" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnVerticalDemo"
        android:layout_width="250dp"
        android:layout_height="45dp"
        android:background="@drawable/bg_btn_main_activity"
        android:text="@string/btn_vertical_str"
        android:textColor="@color/white"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintVertical_chainStyle="packed"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/btnHorizontalDemo"
        app:layout_constraintTop_toBottomOf="@+id/tvParagraph" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnHorizontalDemo"
        android:layout_width="250dp"
        android:layout_height="45dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/bg_btn_main_activity"
        android:text="@string/btn_horizontal_str"
        android:textColor="@color/white"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintBottom_toTopOf="@+id/btnGridDemo"
        app:layout_constraintTop_toBottomOf="@+id/btnVerticalDemo" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnGridDemo"
        android:layout_width="250dp"
        android:layout_height="45dp"
        android:layout_marginTop="10dp"
        android:background="@drawable/bg_btn_main_activity"
        android:text="@string/btn_grid_str"
        android:textColor="@color/white"
        app:layout_constraintBottom_toTopOf="@+id/imgBg"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnHorizontalDemo" />
    <ImageView
        android:id="@+id/imgBg"
        android:src="@drawable/bg_background"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        android:scaleType="centerCrop"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</androidx.constraintlayout.widget.ConstraintLayout>

Step-17 (Final MainActivity Java File)

All three demos will navigate from this screen. The final code of the MainActivity.java file is

package com.procodeguru.recyclerview;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

        // initialize and set listener on Vertical Demo button
        findViewById(R.id.btnVerticalDemo).setOnClickListener(view -> openVerticalDemoActivity());

        // initialize and set listener on Grid Demo button
        findViewById(R.id.btnGridDemo).setOnClickListener(view -> openGridDemoDActivity());

        // initialize and set listener on Horizontal Demo button
        findViewById(R.id.btnHorizontalDemo).setOnClickListener(view -> openHorizontalDemoActivity());
    }

    /**
     * Open RecyclerView Vertical Demo Screen
     */
    private void openVerticalDemoActivity() {
        startActivity(new Intent(this, RecyclerViewVerticalDemoActivity.class));
    }

    /**
     * Open RecyclerView Horizontal Demo Screen
     */
    private void openHorizontalDemoActivity() {
        startActivity(new Intent(this, RecyclerViewHorizontalDemoActivity.class));
    }

    /**
     * Open RecyclerView Grid Demo Screen
     */
    private void openGridDemoDActivity() {
        startActivity(new Intent(this, RecyclerViewGridDemoActivity.class));
    }
}

Thanks for reading the tutorial. Subscribe to my YouTube channel. Like and Share my Facebook page with your friends.

Write A Comment