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

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.

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.

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

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.

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 🙂

 

I am a very enthusiastic Android developer to build solid Android apps. I have a keen interest in developing for Android and have published apps to the Google Play Store. I always open to learning new technologies. For any help drop us a line anytime at contact@mobologicplus.com

Leave a Reply

Your email address will not be published. Required fields are marked *

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