Syntax for conditional statements in Android XML Layout

ID : 131313

viewed : 8

Tags : androidxmlandroid-databindingandroid

Top 5 Answer for Syntax for conditional statements in Android XML Layout

vote vote

91

The correct syntax for calling a data-bind statement looks like "@{<some expression>}", and so a ternary conditional would be

"@{bool ? ifTrue : ifFalse}" 

Where those two values would be the (unquoted) values of what you would normally place into the XML without data binding.

For example

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

Or, you can import a class that has 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

vote vote

81

simple syntax

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

is equivalent to

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

From Android Documentation, you have many available expressions

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

79

You can also combine multiple conditions in 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" /> 
vote vote

65

If anyone wants to use the conditional statement as we do in "if" then below can be used in XML in any view.

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

replace above "&&" with "& amp;& amp"; (remove white space I intentially put here)

vote vote

55

For logical AND operation, use

"&amp ;&amp ;"

rather than && with no space, I give here.

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

Top 3 video Explaining Syntax for conditional statements in Android XML Layout

Related QUESTION?