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?
Layout Binding expressions Expressions in the XML layout files are assigned to a value of the attribute properties using the “ @{} " syntax. We just need to use the basic syntax @{} in an assignment expression.
In Android, an XML-based layout is a file that defines the different widgets to be used in the UI and the relations between those widgets and their containers. Android treats the layout files as resources. Hence the layouts are kept in the folder reslayout.
To convert your XML layouts into the Data Binding layout, follow the below steps: Declare a <layout> tag, which will wrap your existing layout file at the root level. Declare variables under the <data> tag, which will go under the <layout> tag. Declare necessary expressions to bind data inside the view elements.
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 ?:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With