一直没使用过Data Binding,今天就来学习一下,有兴趣的朋友可以直接看官网的介绍Data Binding
准备工作
首先要在build.gradle中添加一句
dataBinding {
enabled = true
}
添加的位置是这样的
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
dataBinding {
enabled = true
}
defaultConfig {
applicationId "c.sample"
minSdkVersion 21
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
然后准备好布局,布局的文件名是会直接跟binding挂钩的,布局的时候xml的布局文件就不再单纯地展示 UI 元素,还需要定义 UI 元素用到的变量。所以,它的根节点不再是一个 ViewGroup,而是变成了 layout,并且新增了一个节点 data
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="user"
type="c.sample.User" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/tv1"
android:layout_width=