Kotlin - Android

How to use android data binding in Kotlin?

DataBinding is the Android library which is allowed to bind the data model directly to XML view in an easy and flexible way.

So in this tutorial, we will try to use the data binding feature in Kotlin. Kotlin provides the data binding dependency library to use the data binding feature. It is flexible and comfortable with any design pattern like MVP and MVVM. I would be recommended checking this post MVP with Kotlin.  What do you need to do to use data binding feature? Here is few steps are required to add to your build.gradle file.

  1. Add Kotlin plugin
  2. Enable the data binding
  3. Add dependency library
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

android {
    .......
    dataBinding {
        enabled = true
    }
}

dependencies {
    .......
    compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    kapt 'com.android.databinding:compiler:2.3.1'
}
repositories {
    mavenCentral()
}

Ok Great 🙂

Let’s see how we can use data binding? We need the model class first which I want to bind with XML view. Here is model class.

class Friends {

      @SerializedName("user")
      @Expose
      var user: List<User>? = null

      class User {

            @SerializedName("id")
            @Expose
            var id: String? = null
            @SerializedName("name")
            @Expose
            var name: String? = null
            @SerializedName("email")
            @Expose
            var email: String? = null

            constructor(id: String?, name: String?, email: String?) {
                  this.id = id
                  this.name = name
                  this.email = email
            }
      }

}

I am getting the model of data from the server. I want to load all user data on recycling view. I used the item layout XML file and we need to bind this model with this view.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <data>
        <variable name="data" type="com.sunil.databindingkotlin.model.Friends.User" />
    </data>
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="10dp">


    <RelativeLayout
        android:id="@+id/relative"
        android:layout_toLeftOf="@+id/delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/name"
            android:text="@{data.name}"
            android:textStyle="bold"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

        <TextView
            android:layout_marginTop="5dp"
            android:layout_below="@+id/name"
            android:id="@+id/email"
            android:text="@{data.email}"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </RelativeLayout>



    <ImageView
        android:padding="5dp"
        android:id="@+id/delete"
        android:layout_marginTop="10dp"
        android:layout_alignParentRight="true"
        android:src="@drawable/ic_delete_red_500_24dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>
</layout>

Data Binding makes the code very simple and understandable. Let’s see how we can use DataBinder in adapter class?

class FriendsAdapter(private val context: Context, private val friendsList: MutableList<Friends.User>) : RecyclerView.Adapter<FriendsAdapter.FriendViewHolder>() {

    override fun onCreateViewHolder(viewGroup: ViewGroup?, viewType: Int): FriendViewHolder {
        val layoutInflater = LayoutInflater.from(context)
        val binding: ViewDataBinding = DataBindingUtil.inflate(layoutInflater, R.layout.item_layout, viewGroup, false)
        return FriendsAdapter.FriendViewHolder(binding)
    }

    override fun onBindViewHolder(holder: FriendViewHolder?, position: Int) {
        var friends = friendsList[position]
        holder!!.bind(friends)
    }

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

    class FriendViewHolder(val binding: ViewDataBinding) : RecyclerView.ViewHolder(binding.root){
        fun bind(data: Any) {
            binding.setVariable(BR.data, data)
            binding.executePendingBindings()
        }
    }
}

In above code, we can see that BR class. BR is some kind of secondary R class used to store the variables declared on the data tag of the XML. After setting the variable we need to call the executePendingBindings() in order to set the user variable attributes to the marked views.

After compiling this you’ll be able to see that the Data has been set to your view without the necessity of writing any code which is required to set the model data on view.

holder!!.name!!.text = friends.name

This is the simple approach to using data binding concept in Kotlin. To get the more detail about the Data Binding Here.

Please do subscribe your email to get the updated newsletters from this blog and if you feel that this post will help you to understand then do not forget to share and comment below.

Happy Coding 🙂

0 0 votes
Article Rating
How to use android data binding in Kotlin?

Recent Posts

Hide your production API key or any sensitive data in Android

Hi everyone, In this article, we are going to learn how to hide the production… Read More

2 years ago

How to handle the localisation or multi language support in android with examples?

Hello everyone, Today in this article, we are going to learn about localisation to support… Read More

2 years ago

How to convert any callback to Coroutines and use them in Kotlin Android?

Hello everyone, In this article, we are going to learn something to handle the callback… Read More

2 years ago

Request Permission Launcher with Kotlin in Android

In this article, we are learning about the run time permissions for request permission launchers.… Read More

2 years ago

Implement the SMS User Consent API and SMS Retriever API in Android

Hello everyone. In my last tutorial, we learned about the Jetpack Compose introduction and about applying the… Read More

3 years ago

Jetpack Compose Coroutine flow with LiveData/ViewModel in Android

Hello everyone, In this article, we are going to learn about the Jetpack Compose with… Read More

3 years ago