Android XML 布局中条件语句的语法

Syntax for conditional statements in Android XML Layout

通过数据绑定,我们现在经常在布局文件中看到这样的代码:

<Variable name="displayIt" type="Boolean"/>

之后:

android:visibility="@{displayIt ? View.VISIBLE : View.GONE}"

(当然android.view.View必须先导入,View.VISIBLE和View.GONE才有意义)

这使得控制视图变得更加容易。 它还告诉我条件语句在 XML 布局中是允许的,但看起来我的 google-fu 很弱,我试过了但找不到它的语法。 如果我想使用文字怎么办?类似于:

android:text="{@isValid ? "valid" : "invalid"}"

(是的,我知道这是一种愚蠢的做法,我只是在谈论这里的语法)。 或者资源 ID 呢?也许喜欢:

android:color="@{isValid ? R.color.green : R.color.red}"

可以吗?正确的语法是什么?

调用数据绑定语句的正确语法类似于 "@{<some expression>}",因此三元条件语句为

"@{bool ? ifTrue : ifFalse}"

这两个值将是您通常在没有数据绑定的情况下放入 XML 中的值(未加引号)。

例如

android:color="@{isValid ? @color/green : @color/red}"

或者,您可以导入具有您需要的静态字段的 class,例如

<data>
    <import type="android.view.View"/>
</data>

android:visibility="@{isVisible ? View.VISIBLE : View.GONE}"

两者都显示在 data binding documentation

语法简单

android:text="@{user.gender ?? `male`}"

相当于

android:text="@{user.gender != null ? user.gender : `male`}"

Android Documentation开始,你有很多可用的表达方式

Mathematical + - / * %
String concatenation +
Logical && ||
Binary & | ^
Unary + - ! ~
Shift >> >>> <<
Comparison == > < >= <=
instanceof
Grouping ()
Literals - character, String, numeric, null
Cast
Method calls
Field access
Array access []
Ternary operator ?:

你也可以这样组合多个条件

<androidx.appcompat.widget.AppCompatTextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:text="@{sold_price == 0 ? (otherValue == 0 ? show_public_price : show_private_price) : (sold_price)}"
     android:textColor="@color/colorRed"
     android:textSize="@dimen/_12ssp" />

如果有人想像我们在 "if" 中那样使用条件语句,那么可以在 XML 的任何视图中使用下面的内容。

app:visibleGone="@{model!=null && model.somevariable}"

将上面的“&&”替换为“&&”; (去掉白色space我特意放在这里的)

逻辑与运算,使用

"&amp ;&amp ;"

而不是没有space的&&,我在这里给出。

android:visibility="@{viewModel.isCardSelected() &amp ;&amp ; !viewModel.isPaymentMethodEmpty() ? View.VISIBLE : View.GONE}"