Switch case in Data Binding

大兔子大兔子 提交于 2019-12-06 03:54:18

No, as far as I know it is not possible and also would make the xml files really unreadable. I think it would be better to implement this in your business logic, not in layout files.

This is definitely better to do in business logic in seperate java class, but if you want to do this with databinding inside xml file, than you have to do it with more inline if statements like this:

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

As you see you have to add every next condition in else state, which makes everything terrible to read.

I would use a BindingAdapter. For example, mapping an enum to strings in a TextView can be done like so (this example uses an enum but it could be used with an int or anything else that can be used in a switch statement). Put this in your Activity class:

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

And then in your layout:

<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"/>

Note the name enumStatusMessage in the annotation and the XML tag.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!