首页 > 解决方案 > 使用数据绑定更新可绘制对象

问题描述

我有一个ImageView我根据是否存在字符串来更改 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当模型改变时更新。它只是在ImageViewActivity 重新启动之前不会更新的 alpha 版本。

标签: androidandroid-layoutandroid-databinding

解决方案


=用于双向绑定,这对 imageView 没有意义(用户无法更改图像)。您没有显示myPackage.Model. 确保模型扩展了 BaseObservable (还有其他方法可以做到这一点)并且 setter forstringAttribute正在调用notifyChange()or notifyPropertyChanged(),例如:

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

推荐阅读