Android’s Data Binding with Kotlin

I assume you are (or are trying to be) an Android developer. I ask then, have you tried using Data Binding?

It’s a library which allows you to flexibly bind the data of your models directly to xml views.

My first experience with this was a year ago trying to set up more than 10 different fonts for the Android App I was developing at that moment. For me, it was the discovery of a powerful tool. By then, another powerful tool I was flirting with during that period of time was the programming language called Kotlin.

Now, in this post I want to show you the approach I used to mix the power of Data Binding with Kotlin by using a simple example.

First, after having a created Android project in Android Studio, we need to add the Data Binding and Kotlin dependencies to the build.gradle file of our app. 

 


//build.gradle 
apply plugin: 'kotlin-android' 
apply plugin: 'kotlin-kapt' 
android { 
	.... 
    dataBinding { 
    	enabled = true 
    } 
 } 
 dependencies { 
 	... 
    // notice that the compiler version must be the same as our gradle version 
    kapt 'com.android.databinding:compiler:2.3.1' 
}

That’s all the configuration we need to start using Data Binding with Kotlin. Thank you very much for reading this … Now let’s continue the fun by viewing the code.

First we need to create a model. In this case, we’ll create a basic one like User.kt


data class User(val name: String, val age: Int)

 

In our activity_main.xml we can do something like this:

 
< ?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" >
<!-- Inside the layout tag it is possible to set the data tag in order to set one or many variables. For this example we are having an User property-->
  <data> 
  	<variable name="user" type="com.kuma.sample.User" /> 
  </data>
  <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="com.kuma.sample.MainActivity" > 
    <TextView android:id="@+id/user_name_text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" android:text="@{user.name}" tools:text="Name" />
    <TextView android:id="@+id/user_age_text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="16dp" android:text="@{Integer.toString(user.age)}" tools:text="XX" />
  </LinearLayout>
</layout> 

 Remember to always set your usual xml view inside the <layout> tag and attach all the “xmlns:” properties to it. Otherwise, it will display a compilation error, since the generated files will have duplicated properties.

And here comes the Binding:

package com.kuma.sample


import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.kuma.kotlinsteps.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
         super.onCreate(savedInstanceState)
         val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
         val user = User("Kuma", 23)
         binding.setVariable(BR.user, user)
         binding.executePendingBindings()
   }
}

In that code snippet there are some things to note:

 

  • There now exists a class called ActivityMainBinding, which is autogenerated from the activity_main.xml and this contains all the references to use the views that the xml contains.
  • The way of making an instance of ActivityMainBinding is a little different than how we set the xml layout to an activity.
  • There is also a new BR class which is some kind of secondary R class used to store the variables declared on the data tag of the xml.
  • After setting the variable to the binding object, it is necessary 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 having to write any textView.text = user.name
  • This was my simple approach to use DataBinding inside a Kotlin project. I hope this is of use to you.

Contact Us

Learn More about Encora

We are the software development company fiercely committed and uniquely equipped to enable companies to do what they can’t do now.

Learn More

Global Delivery

READ MORE

Careers

READ MORE

Industries

READ MORE

Related Insights

Enabling Transformation in Hospitality through Technology-Led Innovation

As the exclusive sponsor of the 2024 Hotel Visionary Awards, we support organizations leading ...

Read More

Key Insights from HLTH 2024: The Future of Patient-Centered Healthcare

Discover key insights from HLTH 2024 on digital health, AI in diagnostics, data interoperability, ...

Read More

Data-Driven Engineering: Transforming Operations and Products from Insight to Impact

Discover how data-driven engineering transforms operations and product development, enhancing team ...

Read More
Previous Previous
Next

Accelerate Your Path
to Market Leadership 

Encora logo

Santa Clara, CA

+1 669-236-2674

letstalk@encora.com

Innovation Acceleration

Speak With an Expert

Encora logo

Santa Clara, CA

+1 (480) 991 3635

letstalk@encora.com

Innovation Acceleration