以下是 Android 数据绑定的典型用法:
android:background="@{isError ? @color/red : @color/white}"
当国家可以采用多种价值观时,情况会变得更加困难。编辑:在方法调用中使用 status 属性是使其工作的唯一方法:
android:background="@{Check.getStatusColor(check.status)}"
并定义静态方法(没有@Bindable):
public int getStatusColor(int status) {
switch (status.get()) {
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 中放置嵌套的三元运算符(我觉得这不是很优雅,顺便说一句),或者不传递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>