Android Kotlin: RecyclerView GridLayoutManager example

Introduction

This code demonstrates how to create a RecyclerView with a GridLayoutManager in an Android application written in Kotlin. A RecyclerView is a powerful and efficient view for displaying large, scrollable lists of data. GridLayoutManager arranges the data in a grid format, similar to a photo gallery.

Breakdown

The code consists of three parts:

  1. MainActivity.kt: This file defines the main activity of the application. It retrieves references to the RecyclerView and creates a list of animal names as data. Then, it sets up a GridLayoutManager with two columns and a vertical orientation. Finally, it creates an adapter for the RecyclerView and binds it to the data.

  2. RecyclerViewAdapter.kt: This file defines the adapter class for the RecyclerView. It holds the list of animal names and extends RecyclerView.Adapter. The adapter inflates a custom view for each item in the list and binds the corresponding animal name to a TextView within that view. It also overrides methods to determine the number of items, retrieve a specific item's ID, and handle view type for performance optimization.

  3. XML Layouts: Two XML layout files define the UI elements. activity_main.xml contains a ConstraintLayout that holds the RecyclerView as its child. custom_view.xml defines the layout for each item displayed in the grid. It uses a CardView to create a visually appealing card with rounded corners for each animal name.

Summary

This example showcases a basic implementation of RecyclerView with GridLayoutManager in Kotlin. By combining these components, you can display collections of data efficiently in a grid format within your Android application. The code utilizes techniques like data binding with an adapter and custom view inflation for a clean and modular approach.


MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView


class MainActivity : AppCompatActivity() {
    private lateinit var context:MainActivity

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Get the context
        context = this

        // Get the widgets reference from XML layout
        val recyclerView = findViewById<RecyclerView>(R.id.recyclerView)

        // initialize a mutable list of animals
        val animals = mutableListOf(
            "Aardvark", "Albatross", "Alligator",
            "Alpaca", "Ant", "Anteater",
            "Antelope", "Ape", "Armadillo",
            "Donkey", "Baboon", "Badger",
            "Barracuda", "Bear","Beaver",
            "Bee", "Rabbit"
        )

        // initialize grid layout manager
        GridLayoutManager(
            context, // context
            2, // span count
            RecyclerView.VERTICAL, // orientation
            false // reverse layout
        ).apply {
            // specify the layout manager for recycler view
            recyclerView.layoutManager = this
        }

        // finally, data bind the recycler view with adapter
        recyclerView.adapter = RecyclerViewAdapter(animals)
    }
}
RecyclerViewAdapter.kt

package com.cfsuman.kotlintutorials

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView


class RecyclerViewAdapter(private val animals: MutableList<String>)
    : RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup, viewType: Int): ViewHolder {
        // inflate the custom view from xml layout file
        val view: View = LayoutInflater.from(parent.context)
            .inflate(R.layout.custom_view,parent,false)

        // return the view holder
        return ViewHolder(view)

    }


    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        // display the current animal
        holder.textView.text = animals[position]
    }


    override fun getItemCount(): Int {
        // number of items in the data set held by the adapter
        return animals.size
    }


    class ViewHolder(itemView: View)
        : RecyclerView.ViewHolder(itemView){
        val textView: TextView = itemView.findViewById(R.id.textView)
    }


    // this two methods useful for avoiding duplicate item
    override fun getItemId(position: Int): Long {
        return position.toLong()
    }


    override fun getItemViewType(position: Int): Int {
        return position
    }
}
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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC">

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

</androidx.constraintlayout.widget.ConstraintLayout>
custom_view.xml

<?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"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#F5F5F5"
    app:cardCornerRadius="8dp"
    app:cardElevation="5dp"
    app:cardMaxElevation="7dp"
    app:contentPadding="24dp"
    android:layout_margin="4dp">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/textView"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:fontFamily="sans-serif"
            android:textColor="#2E2D88"
            android:textSize="24sp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>
    </androidx.constraintlayout.widget.ConstraintLayout>

</androidx.cardview.widget.CardView>
More android kotlin tutorials