概念
DataBinding
是 Google
在 Jetpack
中推出的一款数据绑定的支持库,利用该库可以实现在页面组件中直接绑定应用程序的数据源。使其维护起来更加方便,架构更明确简介。 DataBinding
是 MVVM
模式在 Android
上的一种实现,用于降低布局和逻辑的耦合性,使代码逻辑更加清晰。MVVM
相对于 MVP,其实就是将 Presenter 层替换成了 ViewModel
层。DataBinding
能够省去我们一直以来的 findViewById()
步骤,大量减少 Activity 内的代码,数据能够单向或双向绑定到 layout 文件中,有助于防止内存泄漏,而且能自动进行空检测以避免空指针异常

步骤
一、启用DataBinding
- 要将应用配置为使用数据绑定,请在应用模块的
build.gradle
文件中添加dataBinding
元素,如下:
android {
...
dataBinding {
enabled = true
}
}
二、布局文件的配置
- 在xml布局中使用
<data></data>
标签来描述,在该标签中添加<variable name="data" type="com.example.databinding.MyViewModel"/>
,这里的name
描述了可以在这个布局中使用的属性,type
则表示该属性所属类的详细路径,如下: - data 标签的作用就像一个桥梁搭建了 View 和 Model 之间的通道
<?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>
<variable
name="date"
type="com.example.databinding.MyViewModel" />
</data>
</layout>
- 如果
date
类型要多处用到,也可以直接将之 import 进来,这样就不用每次都指明整个包名路径了,而java.lang.*
包中的类会被自动导入,所以可以直接使用
<data>
<import type="com.example.databinding.MyViewModel"/>
<variable
name="date"
type="date"/>
</data>
- 在布局中,要使用属性则使用
@{}
将其属性及方法写入其中
<!--在标签中使用属性-->
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@{String.valueOf(date.number)}"
app:layout_constraintVertical_bias="0.296" />
<!--在标签中使用方法-->
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="@{()->date.add()}"
android:text="Button" />
三、类文件的配置
- 假设我们有一个
ViewModel
类,用其来承载视图的相关数据及方法,如下:
/**
* @author iwen大大怪
* @Data 2020/3/7 15:13
*/
public class MyViewModel extends ViewModel {
private MutableLiveData<Integer> number;
public MutableLiveData<Integer> getNumber() {
if (number == null){
number = new MutableLiveData<>();
number.setValue(0);
}
return number;
}
public void add(){
number.setValue(number.getValue()+1);
}
}
- 开始将数据与视图双向绑定
/**
* @author iwen大大怪
* @Data 2020/3/7 14:13
*/
public class MainActivity extends AppCompatActivity {
MyViewModel myViewModel;
// 创建一个binding对象
ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
// 使用binding的DataBindingUtil.setContentView()方法绑定布局
binding = DataBindingUtil.setContentView(this,R.layout.activity_main);
// 创建myViewModel对象
myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
//myViewModel = new ViewModelProvider();
// 将具体的值绑定进去,就是将 ViewModel 绑定进去
binding.setDate(myViewModel);
// 刷新
binding.setLifecycleOwner(this);
}
}
四、相关代码解释
ActivityMainBinding binding;
系统会为每个布局文件生成一个绑定类。默认情况下,类名称基于布局文件的名称,它会转换为 Pascal 大小写形式并在末尾添加 Binding 后缀。以上布局文件名为 activity_main.xml
,因此生成的对应类为 ActivityMainBinding
。此类包含从布局属性(例如,number
变量)到布局视图的所有绑定,并且知道如何为绑定表达式指定值。
binding.setDate(myViewModel);
这里是为了设置我们在xml
布局中的数据,将其ViewModel
设置在其中,什么date可以直接调用ViewModel
中的属性方法和方法