Android Data Binding的使用
1.安装插件
2. 创建dataBinding 环境
dataBinding {
enabled = true
}
注意:如果你的应用中有其他模块或依赖的库用到了Data Binding,也需要在buidl.gradle中配置
3. BaseActivity 统一调用布局
private void performDataBinding() {
binding = DataBindingUtil.setContentView(this, getLayoutId());
binding.executePendingBindings();
}
4. 编写布局xml之后通过插件将布局转换成databinding
5. databinding 的使用
5.1 variable简单使用
bean中
public class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
layout中
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="textStr"
type="String" />
<variable
name="onClickListener"
type="android.view.View.OnClickListener" />
<variable
name="user"
type="com.example.mvvm.bean.User" />
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{user.name}" />
<!--注意:这里age是int类型,必须转化为String,否则会运行时异常-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(user.age)}" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{onClickListener}"
android:text="@{textStr}" />
</LinearLayout>
</layout>
activity 中
pub