android:gravity=“center”
app:layout_constraintTop_toBottomOf="@+id/txtUserName"
/>
</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.setV