简体   繁体   中英

Switch case in Data Binding

Is it possible to write switch case with android Data Binding?

Suppose i have 3 conditions like

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

Does there any way to do this stuff in xml by using Data Binding?

I know we can implement conditional statement like

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

But here i am searching for switch case statement.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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