Open In App

Android – RecyclerView as Staggered Grid with Kotlin

Improve
Improve
Like Article
Like
Save
Share
Report

Staggered Grid View has been seen in most applications such as Pinterest in which each item of grid view takes its own height and aligns within the grid view according to that. In this article, we will look at how to implement Staggered Grid Layout Manager to our Recycler View in Android.

Note: If you are looking to implement Staggered Grid Layout Manager in your android recycler view. Check out the following article: Staggered Grid Layout Manager in Android Recycler View in Java

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.

Step 2: Adding dependency of Picasso

As we are loading images within our Recycler View using Image URL. So we will be using Picasso for loading these images from the Image URL. For adding the dependency of Picasso. Navigate to Gradle Scripts>build.gradle file and add the below dependency in the buid.gradle file. 

implementation 'com.squareup.picasso:picasso:2.71828'

After adding the dependency simply sync your project to install it. 

Step 3: Create a layout file for each item of our RecyclerView

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

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="4dp">
 
    <!--on below line we are
        creating a simple image view-->
    <ImageView
        android:id="@+id/idIVImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY" />
 
</RelativeLayout>


Step 4: Create a new Kotlin class for the Adapter

Similarly, create a new Kotlin Class and name the file as PhotoRVAdapter. The adapter is the main class that is responsible for RecyclerView. It holds all methods which are useful in RecyclerView. Adapter class is used to set the data to each item of our recycler view. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
 
class PhotoRVAdapter(
    // on below line we are passing variables as list
    private val photoList: ArrayList<String>,
) : RecyclerView.Adapter<PhotoRVAdapter.PhotoViewHolder>() {
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): PhotoRVAdapter.PhotoViewHolder {
        // this method is use to inflate the layout file
        // which we have created for our recycler view.
        // on below line we are inflating our layout file.
        val itemView = LayoutInflater.from(parent.context).inflate(
            R.layout.photo_rv_item,
            parent, false
        )
        // at last we are returning our view holder
        // class with our item View File.
        return PhotoRVAdapter.PhotoViewHolder(itemView)
    }
 
    override fun onBindViewHolder(holder: PhotoRVAdapter.PhotoViewHolder, position: Int) {
        // on below line we are loading image from image url in our image view.
        Picasso.get().load(photoList.get(position)).into(holder.photoIV)
    }
 
    override fun getItemCount(): Int {
        // on below line we are returning
        // the size of our list
        return photoList.size
    }
 
    class PhotoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        // on below line we are initializing our image view.
        val photoIV: ImageView = itemView.findViewById(R.id.idIVImage)
    }
 
}


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 the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--on below line we are creating
        a text for heading of our app-->
    <TextView
        android:id="@+id/idTVHeading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:gravity="center"
        android:padding="4dp"
        android:text="Staggered Grid Layout Manager"
        android:textAlignment="center"
        android:textColor="@color/purple_200"
        android:textSize="18sp"
        android:textStyle="bold" />
 
    <!--on below line we are creating a recycler view-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRVPhotos"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/idTVHeading" />
 
</RelativeLayout>


Step 6: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
 
class MainActivity : AppCompatActivity() {
 
    // on below line we are creating variables for
    // our swipe to refresh layout,
    // recycler view, adapter and list.
    lateinit var photoRV: RecyclerView
    lateinit var photoRVAdapter: PhotoRVAdapter
    lateinit var photoList: ArrayList<String>
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // on below line we are initializing
        // our views with their ids.
        photoRV = findViewById(R.id.idRVPhotos)
 
        // on below line we are
        // initializing our list
        photoList = ArrayList()
 
        // on below line we are initializing our adapter
        photoRVAdapter = PhotoRVAdapter(photoList)
 
        // on below line we are setting layout manager for our recycler view
        val staggeredGridLayoutManager = StaggeredGridLayoutManager(2, LinearLayoutManager.VERTICAL)
        photoRV.layoutManager = staggeredGridLayoutManager
 
        // on below line we are setting
        // adapter to our recycler view.
        photoRV.adapter = photoRVAdapter
 
        // on below line we are adding data to our list
        photoList.add("https://pbs.twimg.com/media/FV6-TWhUsAY92R_.jpg")
 
        // on below line we are notifying adapter
        // that data has been updated.
        photoRVAdapter.notifyDataSetChanged()
 
    }
}


Now run your application to see the output of it. 

Output: 



Last Updated : 20 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads