Android 数据绑定(bind)/MVVM 模式 : computing view color based off Enum

标签 android mvvm data-binding

我有一个包含以下枚举和变量的类:

enum class ExerciseSetState {
    NOT_STARTED, PASSED, FAILED
}

@Entity
class ExerciseEntity(
        ... 
        @Ignore var setState: ExerciseSetState = ExerciseSetState.NOT_STARTED
        ....
 )

在我的数据绑定(bind)布局中,我想根据这个状态变量设置颜色:
<TextView
        android:id="@+id/tv_exer_rep_3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:text="@{String.valueOf(exercise.setReps)}"
        android:backgroundColor="@{exercise.setState == ExerciseSetState.PASSED? (Color.GREEN : exercise.setState == ExerciseSetState.FAILED ? Color.RED: Color.TRANSPARENT )}"/>

不幸的是,我有这个非常可怕的三元表达式,以便根据值计算颜色。

实现这一点的惯用方式是什么?

最佳答案

使用适配器使其变得简单:

 @BindingAdapter("xmlTag")
        public static void bindColor(TextView textView, @Nullable ExerciseSetState state) {
            //switch state and set the value
        }

在 xml 中:
app:xmlTag="@{exercies.setState}"

关于Android 数据绑定(bind)/MVVM 模式 : computing view color based off Enum,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52922691/

相关文章:

c# - 并发冲突 : the UpdateCommand affected 0 of the expected 1 records

android - 如何在 Android 中使用默认动画?

android - 执行 AsyncTask 时替换 fragment - getActivity() 上的 NullPointerException

android - 如何创建一个自动上传Android图片的应用程序?

wpf - PRISM + MEF + MVVM——不确定从哪里开始?

c# - 更新 "live"WPF Canvas (折线),当 PointCollection 发生变化时

javascript - SAPUI5:数据绑定(bind)到列表

android - 如何获取特定联系人的电子邮件 ID

c# - Prism 导航 - 上一个和下一个 View

image - Xamarin 表单 : IMarkupExtension with bindable property does not work