我有一个包含以下枚举和变量的类:
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/