14

以下是 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>
4

1 回答 1

5

我会这样做:

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

这应该有效。

于 2015-12-15T08:52:20.133 回答