XML Conditional Statements Syntax for Android

With data binding, we now often see codes in layout files, for example:

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

and then later:

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

(of course, android.view.View must first be imported for View.VISIBLE and View.GONE in order to make any sense)

This simplifies viewing management. It also tells me that conditional statements are allowed in the XML layout, but it looks like my google-fu is weak, I tried and could not find the syntax for this. What if I want to use literals? Sort of:

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

(yes, I know this is a dumb way to do this, I'm just talking about the syntax here). Or what about resource identifiers? Maybe like:

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

Can this be done? What is the correct syntax?

+11
source share
3 answers

The correct syntax for calling the data binding operator is "@{<some expression>}" , and therefore the ternary condition will be

 "@{bool ? ifTrue : ifFalse}" 

Where these two values โ€‹โ€‹will be (without quotes) the values โ€‹โ€‹of what you usually put in XML without data binding.

for instance

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

Or you can import a class with a static field that you need, for example

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

And

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

Both of which are shown in the data binding documentation.

+23
source

simple syntax

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

equivalently

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

From the Android documentation you have many expressions available

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

You can also combine several conditions this way.

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

All Articles