Android - RecyclerView as Staggered Grid with Kotlin
Last Updated :
20 Jul, 2022
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
xmlns:android="http://schemas.android.com/apk/res/android"
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:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
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://videocdn.geeksforgeeks.org/geeksforgeeks/2DTranslationinComputerGraphics/2DTranslationinComputerGraphics20220628122713-small.png")
photoList.add("https://videocdn.geeksforgeeks.org/geeksforgeeks/PythonProgramforFibonacciSeries/FibonacciseriesinPython20220627183541-small.png")
photoList.add("https://pbs.twimg.com/media/FV6-TWhUsAY92R_.jpg")
photoList.add("https://videocdn.geeksforgeeks.org/geeksforgeeks/PerformCRUDOperationusingFirebaseinFlutter/PerformCRUDOperationusingFirebaseinFlutter20220627152121-small.png")
photoList.add("https://videocdn.geeksforgeeks.org/geeksforgeeks/CProgramtoConvertLowercasetoUppercaseviceversa/CProgramtoConvertLowercasetoUppercase20220627145001-small.png")
photoList.add("https://videocdn.geeksforgeeks.org/geeksforgeeks/OptimalPageReplacementAlgorithminOS/OptimalPageReplacement20220627124822-small.png")
photoList.add("https://videocdn.geeksforgeeks.org/geeksforgeeks/JavaProgramtoFindQuotientRemainder/JavaProgramtoFindQuotientandRemainder20220626125601-small.png")
photoList.add("https://videocdn.geeksforgeeks.org/geeksforgeeks/FirstandFollowinCompilerDesign/FirstFollowinCompilerDesign20220624172015-small.png")
photoList.add("https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png")
photoList.add("https://media.geeksforgeeks.org/wp-content/uploads/20220531202857/photo6102488593462309569.jpg")
photoList.add("https://practice.geeksforgeeks.org/_next/image?url=https%3A%2F%2F2.zoppoz.workers.dev%3A443%2Fhttps%2Fmedia.geeksforgeeks.org%2Fimg-practice%2Fbanner%2Fdsa-self-paced-thumbnail.png%3Fv%3D19171&w=1920&q=75")
photoList.add("https://practice.geeksforgeeks.org/_next/image?url=https%3A%2F%2F2.zoppoz.workers.dev%3A443%2Fhttps%2Fmedia.geeksforgeeks.org%2Fimg-practice%2Fbanner%2Fcompetitive-programming-live-thumbnail.png%3Fv%3D19171&w=1920&q=75")
// 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:
Similar Reads
RecyclerView as Staggered Grid in Android With Example
GridView: A ViewGroup that shows the items in a two-dimensional scrolling grid. In Grid View, each grid is of the same size. i.e., the height and width of each grid are equal. It shows symmetric items in the views. Staggered GridView: This ViewGroup is the extension of Grid View. In this view, the G
6 min read
Android - RecyclerView using GridLayoutManager with Kotlin
RecyclerView is an improved version of List View in which we can add customization to each item of our recycler view according to our requirements. We can change the orientation of our recycler view depending on our requirements. We can create a simple grid layout, vertical and horizontal recycler v
5 min read
Expandable RecyclerView in Android with Kotlin
In this article, we will get to know how to implement the expandable RecyclerView. In General, we will show the list of items in the listview but in some situations like if you want to show the sub-list items, then we have to use an expandable list. See the below image for a better understanding. ex
7 min read
Android Pull to Refresh with RecyclerView in Kotlin
Pull to Refresh is used to update the data within the list in our android application. For implementing this we have to use Swipe to Refresh Layout. Using this widget when the user swipes down the list which is being displayed on the screen is updated. In this article, we will be building a simple a
6 min read
Android - SearchView with RecyclerView using Kotlin
Many apps display vast amounts of data within their in the form of a list and the user is not able to go through each item within the list to get the item that he wants. For filtering these lists within the android application we can use SearchView to filter it. In this article, we will be building
7 min read
SearchView in Android with RecyclerView
Many apps represent data in the form of huge lists and for filtering these lists we have seen the SearchView present inside these apps. So for filtering this list of data we generally use a SearchView. In this article, we will take a look at the implementation of Search View in Android with a Recycl
10 min read
Staggered GridView in Android with Example
StaggeredGridLayout is a LayoutManager in the Android studio similar to GridView, but in StaggeredGridLayout each grid has its own height and width.Difference Between GridView and Staggered GridViewStaggeredGridlayoutThe children are in a staggered grid format.It supports horizontal and vertical lay
4 min read
Android RecyclerView in Kotlin
In this article, you will know how to implement RecyclerView in Android using Kotlin . Before moving further let us know about RecyclerView. A RecyclerView is an advanced version of ListView with improved performance. When you have a long list of items to show you can use RecyclerView. It has the ab
4 min read
Android | Horizontal RecyclerView with Examples
Recycler View is a ViewGroup added to Android Studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be customiz
4 min read
RecyclerView using GridLayoutManager in Android With Example
RecyclerView is the improved 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 a
6 min read