Android RecyclerView Using GridLayoutManager in Kotlin

Till now, we have seen how to display large set of data as list using recyclerView. In this article, we will learn about how to display such data as grid i.e. how to use android recyclerView using GridLayoutManager in Kotlin.

Output

Tutorialwing Kotlin Android recyclerView using GridLayoutManager in Kotlin With Example

Getting Started

Using GridLayoutManager, we can display data as Grid in RecyclerView. We can even decide how many item we want to show in single row in grid.

Let’s see how do we use it in application –

Creating New Project

At first, we will create an application.
So, follow steps below to create any android project in Kotlin –

Step Description
1. Open Android Studio (Ignore if already done).
2. Go to File => New => New Project. This will open a new window. Then, under Phone and Tablet section, select Empty Activity. Then, click Next.
3. In next screen, select project name as RecyclerViewGridLayout. Then, fill other required details.
4. Then, clicking on Finish button creates new project.

Newbie in Android ?

Some very important concepts (Recommended to learn before you move ahead)

Before we move ahead, we need to setup for viewBinding to access Android WIDGET Using Kotlin file without using findViewById() method.

Setup ViewBinding

Add viewBinding true in app/build.gradle file.

 
 android { 
 	// OTHER CODE... 
 	buildFeatures { 
 		viewBinding true 
 	} 
 } 
 

Now, set content in activity using view binding.
Open MainActivity.kt file and write below code in it.

 
 class MainActivity : AppCompatActivity() { 
 	
 	private lateinit var binding: ActivityMainBinding 
 	
 	override fun onCreate(savedInstanceState: Bundle?) { 
 		super.onCreate(savedInstanceState) 
 		binding = ActivityMainBinding.inflate(layoutInflater) 
 		val view = binding.root 
 		setContentView(view) 
 	} 
 } 
 

Now, we can access view in Kotlin file without using findViewById() method.

Using RecyclerView with GridLayoutManager in Kotlin

Follow steps below to use RecyclerView with GridLayoutManager in newly created project –

  • Open res/values/strings.xml file. Then, add below code into it.
    <resources>
        <string name="app_name">RecyclerViewGridLayout</string>
        <string name="actress_image_description">Actress Image Description</string>
    </resources>
    
  • Create Model Data Class

    In this article, we are going to display list of actress in recyclerView. So, we need to create model class accordingly. Create a new file, Actress.kt, in com.tutorialwing.recyclerviewgridlayout package. Then, add below code in it –

    package com.tutorialwing.recyclerviewgridlayout
    
    class Actress(var name: String, var image: Int)
    

    We are going to display name and image for each actress. So, we have created class accordingly.

  • Create Adapter For RecyclerView

    Now, we need to create adapter for recyclerView that provides data to display in it. So, create a new file, ActressAdapter.kt, in com.tutorialwing.recyclerviewgridlayout package. Then, add below code in it –

    package com.tutorialwing.recyclerviewgridlayout
    
    import android.view.LayoutInflater
    import android.view.ViewGroup
    import androidx.recyclerview.widget.RecyclerView
    import com.tutorialwing.recyclerviewgridlayout.databinding.ItemBinding
    
    class ActressAdapter(
    	private val actressList: ArrayList<Actress>,
    	private val listener: (Actress, Int) -> Unit
    ) :
    	RecyclerView.Adapter<ActressAdapter.ViewHolder>() {
    
    	override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    		val v = ItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
    		return ViewHolder(v)
    	}
    
    	override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    		holder.bindItem(actressList[position])
    		holder.itemView.setOnClickListener { listener(actressList[position], position) }
    	}
    
    	override fun getItemCount(): Int {
    		return actressList.size
    	}
    
    	class ViewHolder(var itemBinding: ItemBinding) :
    		RecyclerView.ViewHolder(itemBinding.root) {
    		fun bindItem(actress: Actress) {
    			itemBinding.image.setImageResource(actress.image)
    			itemBinding.name.text = actress.name
    		}
    	}
    }
    
  • Open res/layout/activity_main.xml file. Then, add below code in it –
    <?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="0dp"
            android:layout_height="0dp"
            android:background="#fefefe"
            android:orientation="horizontal"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • Now, we need to set layoutManager and adapter to recyclerView. So, open MainActivity.kt and add below code in it –

    package com.tutorialwing.recyclerviewgridlayout
    
    import android.os.Bundle
    import android.widget.Toast
    import androidx.appcompat.app.AppCompatActivity
    import androidx.recyclerview.widget.GridLayoutManager
    import com.tutorialwing.recyclerviewgridlayout.databinding.ActivityMainBinding
    
    class MainActivity : AppCompatActivity() {
    
    	private lateinit var binding: ActivityMainBinding
    
    	override fun onCreate(savedInstanceState: Bundle?) {
    		super.onCreate(savedInstanceState)
    
    		binding = ActivityMainBinding.inflate(layoutInflater)
    		setContentView(binding.root)
    
    		setupRecyclerView()
    	}
    
    	private fun setupRecyclerView() {
    		binding.recyclerView.apply {
    			layoutManager = GridLayoutManager(context, 2)
    			adapter = ActressAdapter(createActressList()) { actress, position ->
    				Toast.makeText(
    					this@MainActivity,
    					"Clicked on actress: ${actress.name}",
    					Toast.LENGTH_SHORT
    				).show()
    			}
    		}
    	}
    
    	private fun createActressList(): ArrayList<Actress> {
    		return arrayListOf<Actress>(
    			Actress(
    				"Amber Heard",
    				R.drawable.amber_heard
    			),
    			Actress(
    				"Ananya pandey",
    				R.drawable.ananya_panday
    			),
    			Actress(
    				"Anushka Shetty",
    				R.drawable.anushka_shetty
    			),
    			Actress(
    				"Disha Patani",
    				R.drawable.disha_patani
    			),
    			Actress(
    				"Drew Barrymore",
    				R.drawable.drew_barrymore
    			),
    			Actress(
    				"Kristen Stewart",
    				R.drawable.kristen_stewart
    			),
    			Actress(
    				"Kriti Sanon",
    				R.drawable.kriti_sanon
    			),
    			Actress(
    				"Mishti",
    				R.drawable.mishti
    			),
    			Actress(
    				"Nicole",
    				R.drawable.nicole
    			),
    			Actress(
    				"Priyanka Chopra",
    				R.drawable.priyanka_chopra
    			),
    			Actress(
    				"Rashami Desai",
    				R.drawable.rashami_desai
    			),
    			Actress(
    				"Tamanna",
    				R.drawable.tamanna
    			)
    		)
    	}
    }
    

    Inside setupRecyclerView() method, we have created a GridLayoutManager and set it to recyclerView. first parameter inside it is context, and second parameter is Count i.e. number of items we want to show in single row.

    createActressList() method creates list of actress with name and image for each actress.

Now, run the application. We will get output as below –
Tutorialwing Kotlin Android recyclerView using GridLayoutManager in Kotlin With Example

That’s end of tutorial on Android RecyclerView Using GridLayoutManager in Kotlin.

Leave a Reply