繁体   English   中英

在数据绑定中切换大小写

[英]Switch case in Data Binding

是否可以使用android Data Binding编写switch case?

假设我有3个条件,比如

value == 1 then print A
value == 2 then print B
value == 3 then print C

有没有办法通过使用数据绑定在xml中执行此操作?

我知道我们可以实现条件语句

android:visibility="@{age < 13 ? View.GONE : View.VISIBLE}"

但在这里我正在寻找切换案例陈述。

不,据我所知,这是不可能的,也会使xml文件真的不可读。 我认为最好在业务逻辑中实现它,而不是在布局文件中实现。

这在单独的java类中的业务逻辑中肯定更好,但是如果你想在xml文件中使用数据绑定,那么你必须使用更多的内联if语句来做这样的事情:

android:text='@{TextUtils.equals(value, "1") ? "A" : TextUtils.equals(value, "2") ? "B" : TextUtils.equals(value, "3") ? "C" : ""}'

如你所见,你必须在else状态中添加每个下一个条件,这使得一切都很糟糕。

我会使用BindingAdapter 例如,将枚举映射到TextView中的字符串可以这样完成(此示例使用枚举,但它可以与int或可在switch语句中使用的任何其他内容一起使用)。 把它放在Activity类中:

@BindingAdapter("enumStatusMessage")
public static void setEnumStatusMessage(TextView view, SomeEnum theEnum) {
    final int res;
    if (result == null) {
        res = R.string.some_default_string;
    } else {
        switch (theEnum) {
            case VALUE1:
                res = R.string.value_one;
                break;
            case VALUE2:
                res = R.string.value_two;
                break;
            case VALUE3:
                res = R.string.value_three;
                break;
            default:
                res = R.string.some_other_default_string;
                break;
        }
    }
    view.setText(res);
}

然后在你的布局中:

<TextView
app:enumStatusMessage="@{viewModel.statusEnum}"
tools:text="@string/some_default_string"
android:id="@+id/statusText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="24dp"/>

请注意注释中的名称enumStatusMessage和XML标记。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM