一、在app module的build.gradle如下配置
android {
...
dataBinding {
enabled = true
}
}
二、修改布局文件
根布局改成<layout>
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="user" type="net.dou7.learndatabinding.models.User" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="@dimen/activity_vertical_margin">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@{user.name}" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text='@{String.valueOf(user.age)}' />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text='@{user.lolita ? "萝莉" : "不是萝莉"}' />
</LinearLayout>
</layout>
修改Activity
public class MainActivity extends AppCompatActivity {
ActivityMainBinding mBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main); //no
mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); // yes
// 设置数据
mBinding.setUser(new User("安妮", 12, true));
}
}
一个User
类
public class User {
private String name;
private int age;
private boolean lolita;
// 省略getter,setter
}
运行之后