Android Jetpack中DataBinding数据绑定布局和绑定表达式(三)
布局和绑定表达式
借助表达式语言,您可以编写表达式来处理视图分派的事件。数据绑定库会自动生成将布局中的视图与您的数据对象绑定所需的类。
数据绑定布局文件略有不同,以根标记 layout 开头,后跟 data 元素和 view 根元素。此视图元素是非绑定布局文件中的根。以下代码展示了示例布局文件:
<?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>
data 中的 user 变量描述了可在此布局中使用的属性。
<variable name="user" type="com.example.User" />
布局中的表达式使用“@{}”语法写入特性属性中。在这里,TextView 文本被设置为 user 变量的 firstName 属性:
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.firstName}" />
注意:布局表达式应保持精简,因为它们无法进行单元测试,并且拥有的 IDE 支持也有限。为了简化布局表达式,可以使用自定义绑定适配器。
数据对象
现在我们假设您有一个 plain-old 对象来描述 User 实体:
Kotlin
data class User(val firstName: String, val lastName: String)
Java
public class User {
public final String firstName;
public final String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
此类型的对象拥有永不改变的数据。应用包含读取一次后不会再发生改变的数据是很常见的。也可以使用遵循一组约定的对象,例如 Java 中的访问器方法的使用,如以下示例所示:
Kotlin
// Not applicable in Kotlin.
data class User(val firstName: String, val lastName: String)
Java
public class User {
private final String firstName;
private final String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return this.firstName;
}
public String getLastName() {
return this.lastName;
}
}
从数据绑定的角度来看,这两个类是等效的。用于 android:text 特性的表达式 @{user.firstName} 访问前一个类中的 firstName 字段和后一个类中的 getFirstName() 方法。或者,如果该方法存在,也将解析为 firstName()。
绑定数据
系统会为每个布局文件生成一个绑定类。默认情况下,类名称基于布局文件的名称,它会转换为 Pascal 大小写形式并在末尾添加 Binding 后缀。以上布局文件名为 activity_main.xml,因此生成的对应类为 Activity