SoFunction
Updated on 2025-03-11

Detailed explanation of how to use DataBinding in Android (Kotlin)

Preface

This question mainly introduces how DataBinding is used in Android App. Data binding is a general technology that binds and synchronizes the data source of a "provider" with a "consumer".

1. Android applications use data binding

1.1 Introduction to DataBinding

Android provides support for writing declarative layouts through DataBinding. This can maximize the code associated with layout and logic.
Data binding requires the file to be modified, and the outer layer needs to wrap a layout. The references to elements and expressions in the layout are mainly written into attributes through the @{} or @={} syntax.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:andro
 xmlns:app="/apk/res-auto"
 xmlns:tools="/tools">

 <data>
  <variable
   name="mainModel"
   type="" />①
 </data>

 <
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity">②

  <TextView
   android:
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="@{()}"
   app:layout_constraintBottom_toBottomOf="parent"
   app:layout_constraintLeft_toLeftOf="parent"
   app:layout_constraintRight_toRightOf="parent"
   app:layout_constraintTop_toTopOf="parent" />

  <Button
   android:
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_marginTop="56dp"
   android:onClick="@{(view) -> (view)}"
   android:text="@string/btn_getUserInfo"
   app:layout_constraintBottom_toTopOf="@+id/tv_userinfo"
   app:layout_constraintEnd_toEndOf="parent"
   app:layout_constraintHorizontal_bias="0.498"
   app:layout_constraintStart_toStartOf="parent"
   app:layout_constraintTop_toTopOf="parent" />

 </>
</layout>

①User variables define properties and classes that can be used in this layout

② Regular layout

DataBinding will create a Binding class based on layout. This class contains all bindings from layout attributes (defined variables) to the relevant view, and will generate setters for data elements in the layout. The generated class name is based on the layout name (camel naming, plus Binding suffix). For example, the layout name is activity_main.xml, and the generated class is ActivityMainBinding. You can use this class to inflate layout and data model, or you can use the DataBindingUtil class.

DataBindingUtils loading layout

val mainBindingUtil = <ActivityMainBinding>(this, .activity_main)
 = this

inflate loading layout (this method can also be used for RecyclerView, ViewPager)

val mainBindingUtil = (layoutInflater)
setContentView()

We choose one of the two methods mentioned above. Generally, we use the first one in Activity.

1.2 How to enable DataBinding

To use databinding in Android App project, you only need to set the following code in the app/file:

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

1.3 DataBinding click event handling

In addition to data transmission, layout processing also handles click events.

The usage is the same as that of ordinary method calls. For example, I defined the getClick method in

fun getClick(v: View) {
 //TODO
}

Now I want to call the getClick method when Button clicks, just add the following code to the layout file

android:onClick="@{(view) -> (view)}"

If no parameters are needed, you can

android:onClick="@{() -> ()}"

If there are other parameters, add the corresponding parameter list

android:onClick="@{() -> (args)}"

The same applies to other treatments such as onLongClick.

1.4 Use of import

You can import the class through import and directly call the static methods of the class.

<data>
 <import type="" />
 <variable
  name="mainModel"
  type="" />
</data>

<TextView
 android:text="@{()}"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"/>

1.5 Real-time data refresh

When the viewmodel data changes, we hope that the layout will also be refreshed at the same time. There is a very simple method, and there is no need to inherit BaseObservable. We implement it by introducing LiveData.

open class MainViewModel : ViewModel() {

  var userData: MutableLiveData&lt;UserInfo&gt; = MutableLiveData()

  init {
    getUserInfo()
  }

  private fun getUserInfo() {
    val user = UserInfo("Li Si", (10..50).random())
    (user)  //After the data changes, call postValue, and there is no need to listen through observe, the layout data will be automatically refreshed without monitoring.  }

  fun getClick(v: View) {
    getUserInfo()
  }
}

1.6 Using BindingAdapter

You can use the BindingAdapter annotation to realize that when the property value changes, the control state also changes, such as the image ImageView. When the url changes, the control will display different images.

A static method needs to be defined in a static class:

object StringUtils {

  @BindingAdapter("android:src")
  @JvmStatic fun loadImage(view: ImageView, url: String) {
    MyApplication._context?.let {
      (it)
        .load(url)
        .into(view)
    }
  }
}

Note the Android:src here, which can directly specify the properties of the control or define the properties yourself.

<ImageView
      android:
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/tv_userinfo"
      android:src="@{}"
      tools:srcCompat="@tools:sample/avatars" />

The loadImage method binds the property android:src, so when the value of this property changes, the view and url will be passed to the loadImage.

What if it is a bound custom field? For example, I now bind a custom url.

@BindingAdapter("url")
@JvmStatic fun loadImage(view: ImageView, url: String) {
...
}

Then the layout file is written

<ImageView
      android:
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@+id/tv_userinfo"
      app:url="@{}"
      tools:srcCompat="@tools:sample/avatars" />

Summarize

The previous article mainly wrote some basic usages of databinding, and there are many extension usages, so we will continue to talk about them later.

This is the end of this article about how to use DataBinding (Kotlin) in Android. For more related content on Android using DataBinding (Kotlin), please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!