可绑定未收到通知

Bindable not getting notified

@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; 
}

以上代码是我从 Google 的示例代码中提取的 - 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"); 时,它都会更新视图中的名字,但不会更新全名。甚至文档也有错误且不可靠。

与此问题相关的其他帖子无济于事,因为它们中的大多数都涉及非参数化的可绑定对象。

根据文档中的这一行

Whenever either firstName or lastName has a change notification, name will also be considered dirty. This does not mean that onPropertyChanged(Observable, int) will be notified for BR.name, only that binding expressions containing name will be dirtied and refreshed.

我也试过调用 notifyPropertyChanged(BR.name); 但它对结果也没有影响。

只是一个黑客

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;
    }
}

所以在对数据绑定概念进行彻底分析之后,我发现当我们在 BaseObservable class 上调用 notifyPropertyChanged 时,它实际上通知了 属性 而不是 getters 和二传手。

所以在我上面的问题中,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 因此我必须监听 myViewModel.name 而不是 myViewModel.getName() 在我的 XML 中。我们甚至不必通知 name 更改,仅通知 firstNamelastName 将通知 属性 name 因为参数化的 Bindable。

但请确保