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