可以用android数据绑定编写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}"但在这里我要搜索switch case语句。
发布于 2016-08-08 17:29:24
不,据我所知,这是不可能的,而且也会使xml文件变得不可读。我认为在你的业务逻辑中实现它会更好,而不是在布局文件中。
发布于 2017-02-21 16:59:59
在单独的java类中的业务逻辑中这样做肯定会更好,但是如果你想在xml文件中绑定数据,那么你就必须使用更多的内联if语句来完成,比如:
android:text='@{TextUtils.equals(value, "1") ? "A" : TextUtils.equals(value, "2") ? "B" : TextUtils.equals(value, "3") ? "C" : ""}'正如您所看到的,您必须在else状态中添加每个下一个条件,这使得所有内容都很难读。
发布于 2018-10-25 07:42:41
我会使用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"/>注意注释和XML标记中的名称enumStatusMessage。
https://stackoverflow.com/questions/38825459
复制相似问题