The expression language lets you write expressions that handle events dispatched by views. The Data Binding Library automatically generates the classes required to bind the views in the layout with your data objects.
Data binding layout files are slightly different and start with a root tag of
layout, followed by a data element and a view root element. This view
element is what your root is in a non-binding layout file. The following code
shows a sample layout file:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="user" type="com.example.User"/>
</data>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.firstName}"/>
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.lastName}"/>
</LinearLayout>
</layout>
The user variable within data describes a property that can be used within
this layout:
<variable name="user" type="com.example.User" />
Expressions within the layout are written in the attribute properties using the
@{} syntax. In the following example, the
TextView text is set to the
firstName property of the user variable:
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.firstName}" />
Data objects
Suppose you have a plain object to describe the User entity:
Kotlin
data class User(val firstName: String