@Bindable
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
notifyPropertyChanged(BR.firstName);
}
@Bindable
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
notifyPropertyChanged(BR.lastName);
}
@Bindable({"firstName", "lastName"})
public void getName() {
return this.firstName + ' ' + this.lastName;
}上面的代码是我从谷歌的示例代码- https://developer.android.com/reference/android/databinding/Bindable中学到的
并在XML中使用它,如
<TextView
android:id="@+id/first_name"
.....
android:text="@{myViewModel.firstName}" />
<TextView
android:id="@+id/last_name"
.....
android:text="@{myViewModel.lastName}" />
<TextView
android:id="@+id/full_name"
.....
android:text="@{myViewModel.getName()}" />每当我调用myViewModel.setFirstName("Mohammed");时,它都在更新视图中的名称,而不是全名。甚至这些文件都是错误的,而且不可靠。
其他与这个问题有关的帖子没有多大帮助,因为它们中的大多数都涉及非参数化的Bindable。
按照doc中的这一行
每当firstName或lastName有更改通知时,名称也将被认为是脏的。这并不意味着onPropertyChanged(可观察的int)将被通知为BR.name,只有包含名称的绑定表达式才会被污染和刷新。
我也尝试过调用notifyPropertyChanged(BR.name);,但它对结果也没有影响。
发布于 2018-07-03 11:10:21
因此,在深入分析了绑定概念之后,我发现当我们在BaseObservable类上调用BaseObservable时,它实际上会通知属性,而不是getter和setter。
因此,在我上面的问题中,JAVA部件没有变化,但是XML部件需要进行更改。
<TextView
android:id="@+id/first_name"
.....
android:text="@{myViewModel.firstName}" />
<TextView
android:id="@+id/last_name"
.....
android:text="@{myViewModel.lastName}" />
<TextView
android:id="@+id/full_name"
.....
android:text="@{myViewModel.name}" />由于我将getName()声明为Bindable({"firstName", "lastName"}),所以数据绑定将生成属性name,因此我必须在XML中侦听myViewModel.name而不是myViewModel.getName()。我们甚至不需要通知name进行更改,只通知firstName或lastName会因为参数化的Bindable通知属性name。
但要确保
发布于 2018-07-03 11:00:24
只是一次攻击
public class Modal {
private String firstName;
private String lastName;
private String name;
@Bindable
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
notifyPropertyChanged(BR.firstName);
notifyPropertyChanged(BR.name);
}
@Bindable
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
notifyPropertyChanged(BR.lastName);
notifyPropertyChanged(BR.name);
}
@Bindable
public void getName() {
return this.firstName + ' ' + this.lastName;
}
}https://stackoverflow.com/questions/51152708
复制相似问题