赞
踩
<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”>
<variable
name=“userInfo”
type=“TestInfo” />
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width=“match_parent”
android:layout_height=“match_parent”
tools:context=".MainActivity">
<Button
android:id="@+id/btnGetUserInfo"
android:layout_width=“wrap_content”
android:layout_height=“wrap_content”
android:text=“获取用户信息”
app:layout_constraintBottom_toBottomOf=“parent”
app:layout_constraintLeft_toLeftOf=“parent”
app:layout_constraintRight_toRightOf=“parent”
app:layout_constraintTop_toTopOf=“parent” />
<TextView
android:id="@+id/txtUserName"
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:gravity=“center”
android:text="@{userInfo.age}"
app:layout_constraintTop_toBottomOf="@+id/btnGetUserInfo"
android:layout_marginTop=“30dp”
android:textSize=“30dp”
/>
<TextView
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:text=“text”
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
是注解生成的。
使用单向数据绑定时,您可以为特性设置值,并设置对该特性的变化作出反应的监听器:
<CheckBox
android:id="@+id/rememberMeCheckBox"
android:checked="@{viewmodel.rememberMe}"
android:onC
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。