Android Data Binding (Kotlin) Part 1

Andrey Molochko
3 min readOct 24, 2019

Overview
The Data Binding Library is a support library that allows you bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically.
The Data Binding Library offers both flexibility and broad compatibility — it’s a support library, so you can use it with devices running Android 4.0 (API level 14) or higher.

Photo by Annie Spratt on Unsplash

Get started
At the beginning you should enable data binding in build.gradle file.

Want to read this story later? Save it in Journal.

dataBinding {
enabled true
}

Farther you should add <layout> tag in your xml file.

<?xml version="1.0" encoding="utf-8"?>
<layout>

<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">

<TextView
android:id="@+id/main_title_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

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

After that you should initialize your layout in the activity. For this you need to declare variable and initialize it using setContentView of DataBindingUtil class. Type of var you can get throw name of your layout. For instance, if the name of layout is activity_main then var will be called ActivityMainBinding if the name of layout is activity_dog then var will be called ActivityDogBinding.

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
}

Binding Adapter
Binding adapters are responsible for making the appropriate framework calls to set values. One example is setting a property value like calling the setText() method.
The Data Binding Library allows you to specify the method called to set a value, provide your own binding logic, and specify the type of the returned object by using adapters.

object BindingAdapter{@JvmStatic
@BindingAdapter("bind:imageUrl")
fun loadImage(view: ImageView, url: String) {
Glide.with(view.context).load(url).into(view)
}
}

After addition this method, you don’t need to write a lot of code for Glide implementation for every ImageView. You should pass url in xml. (I’ll show below, how we can pass data from fields a model).

<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
bind:imageUrl="https://s1.1zoom.ru/big0/119/Switzerland_Scenery_461612.jpg"/>

Model with Data Binding

Next feature lets avoid a lot of code in an activity. Also this feature separates view logic, that positive effect on MVVM architecture. You don’t need to initialize your views and set values from your models, because you can pass a model in a xml file and link fields of this model with your xml file.
I’ll show the example from my own project. I have a usual POJO class.

data class Plant(        var id: Long,
var name: String,
var irrigationPeriod: Long,
var urlLocalPhoto: String,
var urlServerPhoto: String?,
var startIrrigation: Long,
var endIrrigation: Long) : {
}

main_activity.xml
You should add <data> tag and declare there <variable> tag. In this tag write name and type attributes. You have to choose any name. For filling type enough write the name of your POJO class and the auto complete helps you.
After addition you can link your views with fields of your model.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">

<data>

<variable
name="model"
type="com.ostrovec.mygarden.room.model.Plant" />
</data>

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/main_name_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{model.name}"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>

<ImageView
android:id="@+id/main_name_check_image_view"
bind:imageUrl="@{model.urlLocalPhoto}"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

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

This code doesn’t work at this moment, because we don’t set the model.
For setting model, you should add in code.

private lateinit var binding: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

binding = DataBindingUtil.setContentView(this, R.layout.activity_main)
binding.model = getModel()
}
fun getModel(): Plant{return Plant(0,"Name",3L,"local url","https://s1.1zoom.ru/big0/119/Switzerland_Scenery_461612.jpg",4L,6L)}

After running application you will see screen with image, which will be loaded using Glide, and TextView with text from the model.
I showed only a small part of the possibilities of Data Binding. But this is the basis and I’ll show the rest in other parts.

📝 Save this story in Journal.

👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. Read the Noteworthy in Tech newsletter.

--

--

Andrey Molochko

Hey, I'm Andrey. I'm an Android Developer from Belarus. Also I create applications via Flutter. I thirdly believe, that my articles will be useful for you.