借助表达式语言,可以编写表达式来处理视图分派的事件。数据绑定库会自动生成讲布局中的视图与您的数据对象绑定所需的类。
数据绑定文件有所不同,已根据layout开头,后跟data元素和view根元素。此视图元素是非绑定布局文件中的根。以下代码展示了实例布局文件:
<?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">
<data>
<import type="java.util.List"/>
<import type="java.util.Map"/>
<variable
name="user"
type="com.bw.day1110.User" />
<variable
name="view"
type="android.view.View" />
<variable
name="list"
type="List<String>" />
<variable
name="index"
type="int" />
<variable
name="map"
type="Map<String ,String>" />
<variable
name="key"
type="String" />
<variable
name="presenter"
type="com.bw.day1110.Presenter" />
<variable
name="userinfo"
type="com.bw.day1110.Userinfo" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity2">
<TextView
android:text="@{user.name}"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(user.age)}"
android:visibility="@{user.age>19? view.GONE:view.VISIBLE}"/>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/input_et"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/input_tv"
android:text="@{inputEt.text}"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{list.get(index)}"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{map.get(key)}"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="事件绑定"
android:onClick="@{()->presenter.onClick()}"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{userinfo.name}"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{presenter.firstName}"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="可观察数据对象"
android:onClick="@{()->presenter.onSaveClick(userinfo)}"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/iv"/>
</LinearLayout>
</layout>