簡體   English   中英

可綁定未通知

[英]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"); 它會更新視圖中的名字,但不會更新全名。 甚至文檔都是錯誤的,也不可靠。

與該問題相關的其他帖子沒有太大幫助,因為它們中大多數都處理非參數化的Bindable。

按照文檔中的這一行

每當firstName或lastName發出更改通知時,名稱也將被視為骯臟。 這並不意味着將為BR.name通知onPropertyChanged(Observable,int),只有包含name的綁定表達式才會被弄臟和刷新。

我也嘗試調用notifyPropertyChanged(BR.name); 但對結果也沒有影響。

只是一個hack

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類上調用notifyPropertyChanged ,它實際上是通知屬性,而不是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更改,因為參數化的Bindable可以僅通知firstNamelastName通知屬性name

但是請確保

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM