Android GridLayoutManager Example With RecyclerView

This article is about Android GridLayoutManager and how to use it with RecyclerView to show items in uniform grid with the help of simple android application.

GridLayoutManager

The RecyclerView widget is a more advanced and flexible version of ListView. It is a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views.

A LayoutManager manages how the items in the RecyclerView are arranged. With RecyclerView,  you can use GridLayoutManager (to show items in grid form i.e. row and column) or LinearLayoutManager (to show items in horizontal and vertical list).  

Let’s implement GridLayoutManager using RecyclerView in simple android application.

Creating New Project

1. In Android Studio, go to File ⇒ New Project, fill all the details required to create a new project and then click on finish.

2. Open build.gradle, add the below recyclerView dependency and then sync the project.

dependencies {
  //add recyclerView dependency
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
}

3. Open the layout file activity_main.xml and add the below code. This file consist of one RecyclerView only.

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

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

4. Create a new layout file recyclerview_item.xml (layout->New->Layout Resource File) and add the below code. This layout file represents an item of a recyclerView which consist of an ImageView (represents Android version name image) and a TextView (represents Android version name).

recyclerview_item.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"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/lightPurple"
android:padding="@dimen/padding_10dp"
android:layout_margin="@dimen/margin_2dp">

<ImageView
android:id="@+id/imgVersionName"
android:layout_width="@dimen/width_150dp"
android:layout_height="@dimen/height_150dp"
android:scaleType="fitXY"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/tvVersionName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="@dimen/margin_12dp"
android:gravity="center"
android:textColor="@android:color/holo_red_dark"
android:textSize="@dimen/textSize_18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="@+id/imgVersionName"
app:layout_constraintStart_toStartOf="@+id/imgVersionName"
app:layout_constraintTop_toBottomOf="@+id/imgVersionName" />

</androidx.constraintlayout.widget.ConstraintLayout>

5. Create a class named Item.java and add the below code. It consist of two properties( versionName and ImageResourceId (for Image)) and getter methods for each property.

Item.java

package com.c1ctech.gridusingrecyclerview;

public class Item {

    private int imageResourseId;
    private String versionName;

    public Item(int imageResourseId, String versionName) {
        this.imageResourseId = imageResourseId;
        this.versionName = versionName;
    }

    public int getImageResourseId() {
        return imageResourseId;
    }

    public String getVersionName() {
        return versionName;
    }

}

6. Open drawable folder under res directory and paste all the images which you have copied from somewhere else.

7. Now open MainActivity.java and add the below code. Here prepareItemData() method adds Item data to list, which we are passing to recyclerView Adapter (ItemAdapter).

MainActivity.java

package com.c1ctech.gridusingrecyclerview;

import android.os.Bundle;

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

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

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    private List<Item> list = new ArrayList<>();

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

       //get recyclerView by its id
        recyclerView = findViewById(R.id.recyclerView);

       //add Item data to list
        prepareItemData();

       //set GridLayoutManager in recyclerView and show items in grid with two columns
        recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(), 2));

       //set adapter ItemAdapter in recyclerView
        recyclerView.setAdapter(new ItemAdapter(list, this));
    }

    public void prepareItemData() {
        Item item = new Item(R.drawable.eclair, "Eclair");
        list.add(item);
        item = new Item(R.drawable.froyo, "Froyo");
        list.add(item);
        item = new Item(R.drawable.gingerbread, "Gingerbread");
        list.add(item);
        item = new Item(R.drawable.honeycomb, "Honeycomb");
        list.add(item);
        item = new Item(R.drawable.ice_cream_sandwich, "Ice Cream Sandwich");
        list.add(item);
        item = new Item(R.drawable.jellybean, "Jelly Bean");
        list.add(item);
        item = new Item(R.drawable.kitkat, "KitKat");
        list.add(item);
        item = new Item(R.drawable.lollipop, "Lollipop");
        list.add(item);
        item = new Item(R.drawable.marshmallow, "Marshmallow");
        list.add(item);
        item = new Item(R.drawable.nougat, "Nougat");
        list.add(item);
        item = new Item(R.drawable.oreo, "Oreo");
        list.add(item);
        item = new Item(R.drawable.pie, "Pie");
        list.add(item);

    }
}

8. Now create a class named ItemAdapter.java and add the below code.

  • onCreateViewHolder(): inflate the item layout and create the View Holder.
  • onBindViewHolder(): set the view attributes based on the data.
  • getItemCount(): determine the number of items.
  • setOnClickListener: show a Toast on click of each recyclerView Item.

ItemAdapter.java

package com.c1ctech.gridusingrecyclerview;

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 android.widget.Toast;

import java.util.List;

import androidx.recyclerview.widget.RecyclerView;

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

    private List<Item> list;
    Context context;


    public ItemAdapter(List<Item> list, Context context) {
        this.list = list;
        this.context = context;

    }

    public class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView textView;
        public ImageView imageView;


        public MyViewHolder(View view) {
            super(view);

            textView = view.findViewById(R.id.tvVersionName);
            imageView = view.findViewById(R.id.imgVersionName);
        }
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item, parent, false);
        return new MyViewHolder(itemView);

    }

    @Override
    public void onBindViewHolder(final MyViewHolder holder, final int position) {

        holder.textView.setText(list.get(position).getVersionName());
        holder.imageView.setImageResource(list.get(position).getImageResourseId());

        // implement setOnClickListener event on item view.
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Toast.makeText(context, "Android Version " + holder.textView.getText() + ": Clicked", Toast.LENGTH_LONG).show();
            }
        });
    }

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

Now when you run the app it will look like this:     

RecyclerView showing Items in grid form.

When you click on any recyclerView item it will show Toast message:

Show Toast message on click of Jelly Bean.

Leave a Reply