簡體   English   中英

使用數據綁定更新可繪制

[英]Update drawable with data binding

我有一個ImageView ,我根據是否存在String來更改Alpha。

XML格式

<data>
    <import type="android.text.TextUtils"/>
    <variable name="model" type="myPackage.Model"/>
</data>

<TextView
    android:text="@={model.stringAttribute}"/>

<ImageView
    android:alpha='@{model.stringAttribute.eqals("") ? 0.5f : 1.0f }'
    android:src="@drawable/thing"/>

在我的activity

binding.setModel(model);

除在ImageView上的Alpha僅在活動重新啟動時才更新外,此方法有效。 我試過在@之后添加等號,但不會編譯。

模型

public class Model extends BaseObservable {
    private String stringAttribute;
    public void setStringAttribute(String s) {
        stringAttribute = s
        notifyPropertyChanged(BR.stringAttribute)
    }
    @Bindable
    public String getStringAttribute() {
        return stringAttribute;
    }
}

為了明確TextView當模型更改時, TextView也會更新。 只是ImageView上的Alpha直到活動重新啟動才更新。

<data>
    <import type="android.text.TextUtils"/>
    <variable name="model" type="yourPackage.MainViewModel"/>
</data>

...

<ImageView
    android:alpha='@{TextUtils.isEmpty(model.stringAttribute) ? 0.5 : 1.0 }'
    android:src="@drawable/thing"/>

確保您還通過活動設置model

binding.setModel(model);

=是雙向綁定,對於imageView沒有意義(用戶無法更改圖像)。 您不會顯示myPackage.Model的代碼。 確保模型擴展了BaseObservable(還有其他方法可以做到這一點),並且stringAttribute的設置stringAttribute正在調用notifyChange()notifyPropertyChanged() ,例如:

public void setStringAttribute(String val) {
    . . .
    notifyPropertyChanged(BR.stringAttribute);
}

暫無
暫無

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

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