带条件资源的Android数据绑定
以下是Android数据绑定的典型用法:带条件资源的Android数据绑定,android,android-databinding,Android,Android Databinding,以下是Android数据绑定的典型用法: android:background="@{isError ? @color/red : @color/white}" 当国家可以采用多个值时,情况就变得更加困难了编辑:在方法调用中使用status属性是使其工作的唯一方法: android:background="@{Check.getStatusColor(check.status)}" 并定义静态方法(没有@Bindable): 如何实现这一点,而不在XML中放入嵌套的三元运算符(顺便说一句,我
android:background="@{isError ? @color/red : @color/white}"
当国家可以采用多个值时,情况就变得更加困难了编辑:在方法调用中使用status属性是使其工作的唯一方法:
android:background="@{Check.getStatusColor(check.status)}"
并定义静态方法(没有@Bindable):
如何实现这一点,而不在XML中放入嵌套的三元运算符(顺便说一句,我觉得这不是很优雅),或者不通过check.status
属性
编辑:添加XML:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<import type="org.honorato.diagnostics.models.Check"/>
<variable
name="check"
type="Check"/>
</data>
<LinearLayout
android:background="@android:color/white"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="72dp"
>
<LinearLayout
android:padding="16dp"
android:layout_width="0dip"
android:layout_weight="1"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:text="@{check.title}"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@android:color/primary_text_light"
android:textStyle="bold" />
</LinearLayout>
<ImageView
android:padding="16dp"
android:src="@{check.getStatusDrawable(check.status)}"
android:background="@{check.getStatusColor(check.status)}"
android:layout_width="72dp"
android:layout_height="match_parent"
android:layout_gravity="center_vertical|center_horizontal" />
</LinearLayout>
</layout>
我将这样做:
android:background="@{check.getStatusColor()}"
getStatusColor
是一种非静态的Check
方法,这就是为什么我们可以访问实例字段status
public int getStatusColor() {
switch (status) {
case STATUS_OK:
return ContextCompat.getColor(context, R.color.success);
case STATUS_WARNING:
return ContextCompat.getColor(context, R.color.warning);
case STATUS_ERROR:
return ContextCompat.getColor(context, R.color.error);
default:
return ContextCompat.getColor(context, R.color.idle);
}
}
这应该有效。请添加xml文件数据。getColorForSttus方法是否有@Bindable注释?@Natali更新了问题。我做了一个黑客使它工作,但仍然发现它不雅观。将尝试使用Bindable annotationTry将@Bindable annotations添加到getStatusColor(int status)方法。之后,您可以在其中使用xml,如@{check.statusColor}一个警告:使用此语法,我认为在调用
notifyPropertyChanged(BR.statusColor)
时,背景不会更新。这将只使用“@{check.statusColor}”
语法更新表达式。
public int getStatusColor() {
switch (status) {
case STATUS_OK:
return ContextCompat.getColor(context, R.color.success);
case STATUS_WARNING:
return ContextCompat.getColor(context, R.color.warning);
case STATUS_ERROR:
return ContextCompat.getColor(context, R.color.error);
default:
return ContextCompat.getColor(context, R.color.idle);
}
}