Till now, we have learnt how to use android recyclerView using linearLayoutManager and GridLayoutManager. In this article, we will learn how to use android recyclerView using staggeredGridLayoutManager in Kotlin. We will display some list of flowers in staggered grid.
Output
Getting Started
StaggeredGridLayoutManager accepts parameter as count and orientation. count depicts number of items to be shown in each row, orientation depicts whether list is horizontally or vertically scrollable.
Now, how do we use android recyclerView using staggeredGridLayoutManager in android 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 RecyclerViewStaggeredGridLayout. 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 recyclerView 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 StaggeredGridLayoutManager in Kotlin
Follow steps below to use StaggeredGridLayoutManager in newly created project –
- Open res/values/strings.xml file. Then, add below code into it.
<resources> <string name="app_name">RecyclerViewStaggeredGridLayout</string> <string name="flower_image_description">Flower Image Description</string> </resources>
-
Create Data Model Class
In this article, we are going to show list of flowers using recyclerView. So, we need to create model class. Create a new file, Flower.kt, in com.tutorialwing.recyclerviewstaggeredgridlayout package. Then, add below code in it –
package com.tutorialwing.recyclerviewstaggeredgridlayout class Flower(var name: String, var image: Int)
-
Create UI for Single Item
Now, we need to create ui for single item i.e. how are we going to display each flower item in recyclerView. So, create a new file, flower_item.xml, in res/layout folder. Then, add below code in it –
<?xml version="1.0" encoding="utf-8"?> <androidx.cardview.widget.CardView 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="wrap_content" android:layout_margin="5dp"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?android:attr/selectableItemBackground" tools:context=".MainActivity"> <ImageView android:id="@+id/image" android:layout_width="0dp" android:layout_height="wrap_content" android:adjustViewBounds="true" android:contentDescription="@string/flower_image_description" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <TextView android:id="@+id/name" android:layout_width="0dp" android:layout_height="wrap_content" android:gravity="center" android:padding="5dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/image" /> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.cardview.widget.CardView>
-
Create Adapter for RecyclerView
Now, we need to create adapter for recyclerView. So, create a new file, FlowerAdapter.kt, in com.tutorialwing.recyclerviewgridlayout package. Then, add below code in it –
package com.tutorialwing.recyclerviewstaggeredgridlayout import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.tutorialwing.recyclerviewstaggeredgridlayout.databinding.FlowerItemBinding class FlowerAdapter( private val flowerList: ArrayList<Flower>, private val listener: (Flower, Int) -> Unit ) : RecyclerView.Adapter<FlowerAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val v = FlowerItemBinding.inflate(LayoutInflater.from(parent.context), parent, false) return ViewHolder(v) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { holder.bindItem(flowerList[position]) holder.itemView.setOnClickListener { listener(flowerList[position], position) } } override fun getItemCount(): Int { return flowerList.size } class ViewHolder(var flowerItemBinding: FlowerItemBinding) : RecyclerView.ViewHolder(flowerItemBinding.root) { fun bindItem(flower: Flower) { flowerItemBinding.image.setImageResource(flower.image) flowerItemBinding.name.text = flower.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" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Here, we have defined recyclerView in xml file.
-
Now, we will set adapter and layoutManager to recyclerView dynamically. So, open MainActivity.kt and add below code in it –
package com.tutorialwing.recyclerviewstaggeredgridlayout import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.StaggeredGridLayoutManager import com.tutorialwing.recyclerviewstaggeredgridlayout.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 = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) adapter = FlowerAdapter(createFlowerList()) { flower, position -> Toast.makeText( this@MainActivity, "Clicked on Flower: ${flower.name}", Toast.LENGTH_SHORT ).show() } } } private fun createFlowerList(): ArrayList<Flower> { return arrayListOf<Flower>( Flower( "Blue Bell", R.drawable.bluebell ), Flower( "Calendula", R.drawable.calendula ), Flower( "Iris", R.drawable.iris ), Flower( "Jasmine", R.drawable.jasmine ), Flower( "Lavender", R.drawable.lavender ), Flower( "Lily", R.drawable.lily ), Flower( "Lotus", R.drawable.lotus ), Flower( "MaryGold", R.drawable.marygold ), Flower( "Orchid", R.drawable.orchid ), Flower( "Poppy", R.drawable.poppy ), Flower( "Rose", R.drawable.rose ), Flower( "Rosemary Dahlia", R.drawable.rosemary_dahlia ), Flower( "Sunflower", R.drawable.sunflower ), Flower( "Tulip", R.drawable.tulip ) ) } }
Now, run the application. We will get output as below –
That’s end of our tutorial on Android RecyclerView Using StaggeredGridLayoutManager in Kotlin .
You must be logged in to post a comment.