Syntax for conditional statements in Android XML Layout

htwu picture htwu · Jul 16, 2016 · Viewed 39.9k times · Source

With databinding we now often see codes in layout files like this:

<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 to have any meaning)

This makes controlling the view much easier. It also tells me that conditional statements are allowed in XML Layout, but it looks like my google-fu is weak, I tried and couldn't find the syntax for this. What if I want to use literals? Something like:

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

(yes I know that's a stupid way of doing it, I am just talking about the syntax here). Or what about resource ID's? Maybe like:

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

Can it be done? What's the proper syntax?

Answer

OneCricketeer picture OneCricketeer · Jul 16, 2016

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