/>
</androidx.constraintlayout.widget.ConstraintLayout>
Activity 中调用代码如下:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val activityBinding: ActivityMainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main)
activityBinding.lifecycleOwner = this
activityBinding.userInfo = TestInfo(“lsm”,“lsj”)
}
TestInfo 的定义如下:
public class TestInfo extends BaseObservable { //继承 BaseObservable
private String age;
private String name;
public TestInfo(String age,String name){
this.name = name;
this.age = age;
}
public void setAge(String age) {
this.age = age;
notifyPropertyChanged(BR.age); //需要变更的变量的 set 方法中加上 notifyPropertyChanged
}
public void setName(String name) {
this.name = name;
notifyPropertyChanged(BR.name); //需要变更的变量的 set 方法中加上 notifyPropertyChanged
}
@Bindable //需要变更的变量还要加上 @Bindable 注解
public String getAge() {
return age;
}
@Bindable //需要变更的变量还要加上 @Bindable 注解
public String getName() {
return name;
}
}
TestInfo
需要继承BaseObservable
,同时对于需要监听变化的变量加上@Bindable
注解,同时该变量的set
方法还要加上notifyPropertyChanged
,BR.xxx
是注解生成的。
数据的双向绑定
使用单向数据绑定时,您可以为特性设置值,并设置对该特性的变化作出反应的监听器:
双向数据绑定为此过程提供了一种快捷方式:
@={}
表示法(其中重要的是包含“=”符号)可接收属性的数据更改并同时监听用户更新。其他的设置和前面的单向数据绑定一致。
结合 LiveData 使用
内容参考自这里,我们上面在使用 DataBinding 时,TestInfo 还要继承 BaseObserble
,使用注解、notifyPropertyChanged(),使用起来其实挺复杂,而且还有侵入性。LiveData 结合 DataBinding 的使用步骤如下:
- 使用 LiveData 对象作为数据绑定来源,需要设置 LifecycleOwner。
- xml 中定义变量 ViewModel,并使用 ViewModel。
- binding 设置变量 ViewModel。
//结合DataBinding使用的ViewModel
//1. 要使用LiveData对象作为数据绑定来源,需要设置LifecycleOwner
binding.setLifecycleOwner(this);
ViewModelProvider viewModelProvider = new ViewModelProvider(this);
mUserViewModel = viewModelProvider.get(UserViewModel.class);
//3. 设置变量ViewModel
binding.setVm(mUserViewModel);
xml 文件的定义如下:
这样就ok了,你会发现 我们不需要在 Activity 中拿到 LivaData 去 observe(owner,observer)了,DataBinding 自动生成的代码,会帮我们去做这操作,所以需要设置LifecycleOwner。
使用自定义特性的双向数据绑定
例如,如果要在名为 MyView
的自定义视图中对 "time"
特性启用双向数据绑定,请完成以下步骤:
- 使用
@BindingAdapter
,对用来设置初始值并在值更改时进行更新的方法进行注释:
@BindingAdapter(“time”)
@JvmStatic fun setTime(view: MyView, newValue: Time) {
// Important to break potential infinite loops.
if (view.time != newValue) {
view.time = newValue
}
}
- 使用
@InverseBindingAdapter
对从视图中读取值的方法进行注释:
@InverseBindingAdapter(“time”)
@JvmSt