How to use RecyclerView Databinding in Kotlin

In this android kotlin source code example, we are going to use RecyclerView Databinding in Kotlin.

You can copy and adopt this source code example to your Kotlin android project without reinventing the wheel.

Below is a step by step source code to use RecyclerView Databinding in Kotlin.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout 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">
    <data>
        <variable
            name="countryAdapter"
            type="com.bluapp.kotlinview.recyclerView.RecyclerViewActivity13.CountryAdapter" />
    </data>
    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="3dp">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:adapter="@{countryAdapter}"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintEnd_toEndOf="parent" />


    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

MainActivity.kt

import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import com.bluapp.kotlinview.databinding.ActivityRecyclerView13Binding
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.bluapp.kotlinview.BR
import com.bluapp.kotlinview.R
import com.bluapp.kotlinview.databinding.ItemDatabind13RowBinding


class RecyclerViewActivity13 : AppCompatActivity() {
    private var binding: ActivityRecyclerView13Binding? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_recycler_view13)
        populateData()
    }

    private fun populateData() {
        val countryModelList = arrayListOf<CountryModel>()
        countryModelList.add(CountryModel("Nigeria"))
        countryModelList.add(CountryModel("India"))
        countryModelList.add(CountryModel("Sweden"))
        countryModelList.add(CountryModel("Usa"))
        countryModelList.add(CountryModel("Ghana"))
        countryModelList.add(CountryModel("South Africa"))

        val countryAdapter = CountryAdapter(countryModelList, this)
        binding!!.setCountryAdapter(countryAdapter)
    }

    inner class CountryModel(val countryName: String)

    interface CustomClickListner {
        fun cardClicked(countryModel: CountryModel)
    }

    inner class CountryAdapter(private val countryModelList: List<CountryModel>, private val context: Context) : RecyclerView.Adapter<CountryAdapter.ViewHolder>(), CustomClickListner {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            val binding = DataBindingUtil.inflate<ItemDatabind13RowBinding>(LayoutInflater.from(parent.context), R.layout.item_databind13_row, parent, false)
            return ViewHolder(binding)
        }

        override fun onBindViewHolder(holder: ViewHolder, position: Int) {
            val countryModel = countryModelList[position]
            holder.bind(countryModel)
            holder.itemDatabind16RowBinding.setItemClickListner(this)
        }

        override fun getItemCount(): Int {
            return countryModelList.size
        }


        inner class ViewHolder(var itemDatabind16RowBinding: ItemDatabind13RowBinding) :
            RecyclerView.ViewHolder(itemDatabind16RowBinding.getRoot()) {

            fun bind(`object`: Any) {
                itemDatabind16RowBinding.setVariable(BR.model, `object`)
                itemDatabind16RowBinding.executePendingBindings()
            }
        }

        override fun cardClicked(countryModel: CountryModel) {
            Toast.makeText(context, "Item Click " + countryModel.countryName, Toast.LENGTH_LONG).show()
        }
    }


}

item_databind13_row.xml

<?xml version="1.0" encoding="utf-8"?>
<layout 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">
    <data>
        <variable
            name="model"
            type="com.bluapp.kotlinview.recyclerView.RecyclerViewActivity13.CountryModel" />

        <variable
            name="itemClickListner"
            type="com.bluapp.kotlinview.recyclerView.RecyclerViewActivity13.CustomClickListner" />
    </data>
    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="@{() -> itemClickListner.cardClicked(model)}"
        app:cardUseCompatPadding="true">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:layout_margin="8dp">

            <TextView
                android:id="@+id/country"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@{model.countryName}" />

        </LinearLayout>


    </androidx.cardview.widget.CardView>
</layout>

app/build.gradle

apply plugin: 'kotlin-kapt'

dataBinding {
        enabled = true
    }
kapt "com.android.databinding:compiler:3.5.0"

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.