Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/201.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 使用数据绑定更新drawable_Android_Android Layout_Android Databinding - Fatal编程技术网

Android 使用数据绑定更新drawable

Android 使用数据绑定更新drawable,android,android-layout,android-databinding,Android,Android Layout,Android Databinding,我有一个ImageView,根据是否存在字符串来更改alpha XML <data> <import type="android.text.TextUtils"/> <variable name="model" type="myPackage.Model"/> </data> <TextView android:text="@={model.stringAttribute}"/> <ImageView

我有一个
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"/>
这项工作除了
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
会在模型更改时更新。只有
ImageView
上的alpha才会更新,直到活动重新启动。

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

<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"/>
public void setStringAttribute(String val) {
    . . .
    notifyPropertyChanged(BR.stringAttribute);
}

我已经更新了我的问题,
TextView
在模型更改时可以正常更新。只是绘图表上的alpha设置不起作用,无法编译。代码在那部分是可以的。表达式求值且alpha发生更改,在未重新启动活动的情况下,它不会更新GUI。您的模型是否对
stringAttribute
使用
observefield
,还是
observeable
?如果两者都不存在,那么这就是您的问题。它是可观察的(用
@Bindable
注释)。
notifyPropertyChanged()
位于setter中,并且类扩展为
BaseObservable
。字符串属性用
@Bindable
注释,同时确保在setter中最后调用notifyPropertyChanged。您还可以尝试针对null设置和测试,以防万一。
binding.setModel(model);
public void setStringAttribute(String val) {
    . . .
    notifyPropertyChanged(BR.stringAttribute);
}