Skip to content
Related Articles

Related Articles

Improve Article
RecyclerView using GridLayoutManager in Android With Example
  • Difficulty Level : Easy
  • Last Updated : 24 Nov, 2020

RecyclerView is the improvised version of a ListView in Android. It was first introduced in Marshmallow. Recycler view in Android is the class that extends ViewGroup and implements Scrolling Interface. It can be used either in the form of ListView or in the form of Grid View. 

How to use RecyclerView as GridView?

While implementing Recycler view in Android we generally have to set layout manager to display our Recycler View. There are two types of layout managers for Recycler View to implement. 

  1. Linear Layout Manager
  2. Grid Layout Manager

Linear Layout Manager

In linear layout manager, we can align our recycler view in a horizontal or vertical scrolling manner by specifying its orientation as vertical or horizontal. 

Grid Layout Manager

In Grid Layout manager we can align our recycler in the form of a grid. Here we have to mention the number of columns that are to be displayed in the Grid of Recycler View.

Difference Between RecyclerView and GridView

1) View Holder Implementation.

In GridView it was not mandatory to use View holder implementation but in RecyclerView it is mandatory to use View Holder implementation for Recycler View. It makes the code complex but many difficulties that are faced in GridView are solved in RecyclerView. 



2) Performance of Recycler View. 

RecyclerView is an improvised version of ListView. The performance of Recycler View has improvised. In Recycler View the items which are ahead and behind the visible entries. 

Example of GridLayoutManager in RecyclerView

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. 

RecyclerView using GridLayoutManager in Android

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Project just refer to this article on How to Create new Project in Android Studio and make sure that the language is Java. To implement Recycler View three sub-parts are needed which are helpful to control RecyclerView. These three subparts include: 

  • Card Layout: The card layout is an XML file that will represent each individual grid item inside your Recycler view.  
  • View Holder: View Holder Class is the java class that stores the reference to the UI Elements in the Card Layout and they can be modified dynamically during the execution of the program by the list of data. 
  • Data Class: Data Class is an object class that holds information to be displayed in each recycler view item that is to be displayed in Recycler View. 

Step 2: Create a Card Layout for Recycler View Card Items

Go to the app > res > layout> right-click > New >Layout Resource File and name the file as card_layout. In this file, all XML code related to card items in the RecyclerView is written. Below is the code for the card_layout.xml file.

XML






<?xml version="1.0" encoding="utf-8"?>
<!--XML implementation of Card Layout
    Keep the width of card layout to match parent-->
<androidx.cardview.widget.CardView 
    android:layout_width="match_parent"
    android:layout_height="120dp"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    app:cardCornerRadius="5dp"
    app:cardElevation="5dp">
  
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
  
        <ImageView
            android:id="@+id/idIVcourseIV"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:layout_gravity="center"
            android:contentDescription="@string/image"
            android:src="@mipmap/ic_launcher" />
  
        <TextView
            android:id="@+id/idTVCourse"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:textAlignment="center" />
  
    </LinearLayout>
  
</androidx.cardview.widget.CardView>

Step 3: Create a Java class for Modal Data

Go to the app > java > Right-Click on your app’s package name > New > Java Class and name the file as RecyclerData. This class will handles data for each Recycler item that is to be displayed. Below is the code for the RecyclerData.java file.

Java




public class RecyclerData {
  
    private String title;
    private int imgid;
  
    public String getTitle() {
        return title;
    }
  
    public void setTitle(String title) {
        this.title = title;
    }
  
    public int getImgid() {
        return imgid;
    }
  
    public void setImgid(int imgid) {
        this.imgid = imgid;
    }
  
    public RecyclerData(String title, int imgid) {
        this.title = title;
        this.imgid = imgid;
    }
}

Step 4: Create a new java class for the Adapter

Similarly, create a new Java Class and name the file as RecyclerViewAdapter. The adapter is the main class that is responsible for RecyclerView. It holds all methods which are useful in RecyclerView. 

Note: View Holder Class is also implemented in Adapter Class itself. 

These methods to handle Recycler View includes: 

  • onCreateViewHolder: This method inflates card layout items for Recycler View.
  • onBindViewHolder: This method sets the data to specific views of card items. It also handles methods related to clicks on items of Recycler view.
  • getItemCount: This method returns the length of the RecyclerView.

Below is the code for the RecyclerViewAdapter.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 RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
  
    private ArrayList<RecyclerData> courseDataArrayList;
    private Context mcontext;
  
    public RecyclerViewAdapter(ArrayList<RecyclerData> recyclerDataArrayList, Context mcontext) {
        this.courseDataArrayList = recyclerDataArrayList;
        this.mcontext = mcontext;
    }
  
    @NonNull
    @Override
    public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // Inflate Layout
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false);
        return new RecyclerViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
        // Set the data to textview and imageview.
        RecyclerData recyclerData = courseDataArrayList.get(position);
        holder.courseTV.setText(recyclerData.getTitle());
        holder.courseIV.setImageResource(recyclerData.getImgid());
    }
  
    @Override
    public int getItemCount() {
        // this method returns the size of recyclerview
        return courseDataArrayList.size();
    }
  
    // View Holder Class to handle Recycler View.
    public class RecyclerViewHolder extends RecyclerView.ViewHolder {
  
        private TextView courseTV;
        private ImageView courseIV;
  
        public RecyclerViewHolder(@NonNull View itemView) {
            super(itemView);
            courseTV = itemView.findViewById(R.id.idTVCourse);
            courseIV = itemView.findViewById(R.id.idIVcourseIV);
        }
    }
}

 Step 5: Working with the activity_main.xml file



This is the main screen that displays all data in the form of a grid. Here we have to implement Recycler View. Below is the code snippet of the XML layout in activity_main.xml file.

XML




<?xml version="1.0" encoding="utf-8"?>
<!--XMl Layout for RecyclerView-->
<androidx.constraintlayout.widget.ConstraintLayout 
    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/idCourseRV"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
  
</androidx.constraintlayout.widget.ConstraintLayout>

Step 6: Working with the MainActivity.java file 

This is the main java file where we will set LayoutManager, adapter, and set data to RecyclerView which is to be displayed in 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.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
  
public class MainActivity extends AppCompatActivity {
  
    private RecyclerView recyclerView;
    private ArrayList<RecyclerData> recyclerDataArrayList;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView=findViewById(R.id.idCourseRV);
  
        // created new array list..
        recyclerDataArrayList=new ArrayList<>();
  
        // added data to array list
        recyclerDataArrayList.add(new RecyclerData("DSA",R.drawable.ic_gfglogo));
        recyclerDataArrayList.add(new RecyclerData("JAVA",R.drawable.ic_gfglogo));
        recyclerDataArrayList.add(new RecyclerData("C++",R.drawable.ic_gfglogo));
        recyclerDataArrayList.add(new RecyclerData("Python",R.drawable.ic_gfglogo));
        recyclerDataArrayList.add(new RecyclerData("Node Js",R.drawable.ic_gfglogo));
  
        // added data from arraylist to adapter class.
        RecyclerViewAdapter adapter=new RecyclerViewAdapter(recyclerDataArrayList,this);
          
        // setting grid layout manager to implement grid view.
        // in this method '2' represents number of columns to be displayed in grid view.
        GridLayoutManager layoutManager=new GridLayoutManager(this,2);
          
        // at last set adapter to recycler view.
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }
}

Output:  

RecyclerView using GridLayoutManager in Android

You can check out the GitHub repo mentioned below where you can get all code to implement Recycler View with Grid Layout Manager. If you want to implement On Click Listener for Recycler Items in Grid Layout then check out this post for implementation of RecyclerView

Link for the GitHub Repo: https://github.com/ChaitanyaMunje/GFG-GridLayout-Manager     

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!
My Personal Notes arrow_drop_up
Recommended Articles
Page :