Reputation: 12007
I have the XML layout code:
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:bind="http://schemas.android.com/apk/res-auto">
<data>
<variable name="info" type="com.mycompany.orm.binders.MyBinderObject"/>
</data>
<android.support.percent.PercentRelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="15dp"
android:paddingBottom="15dp"
android:gravity="end">
...
And this works great. However, I have a property inside MyBinderObject
called mygravity
, and it is set to one of two strings: start
or end
. I am trying to figure out how to read the Data Binding property mygravity
to assign the gravity to the layout.
I.e., android:gravity="@{info.mygravity}"
(However, this line does not work. The compile-time databinding code fails).
Does anyone have an idea how to dynamically set the android:gravity
based on a Data-bound objects property?
Upvotes: 1
Views: 3194
Reputation: 35579
you can definitely use android:gravity="@{info.mygravity}"
in layout file but make sure that mygravity should be int value.
you should refer this
like if you want center
gravity, value of info.mygravity
should be Gravity.CENTER
Upvotes: -1
Reputation: 1007474
I have a property inside MyBinderObject called mygravity, and it is set to one of two strings: start or end.
Therein lies the problem: you're doing something reasonable and treating the layout XML like XML.
The layout XML attribute values can be of a variety of types. Sometimes, this is obvious, such as android:enabled="false"
or android:layout_width="30sp"
. And, sometimes, the type really is a string or string resource reference (e.g., android:text="Foo"
). But sometimes the attribute value looks like an English-language string, but it is really one of a set of enumerated values (e.g., gravity values).
I didn't realize that gravity was actually an enumerated attribute
A rough-cut rule of thumb: if the build would fail if you translated the value into another language, then it is an enumerated attribute (e.g., android:gravity="fin"
instead of android:gravity="end"
, assuming that Google Translate gave me reasonable Spanish there...). If the translated value would work just fine, then it's any valid string or (usually) string resource.
I am trying to figure out how to read the Data Binding property mygravity to assign the gravity to the layout.
You will have to transmogrify the string values into equivalent Gravity
constants like Gravity.START
.
Upvotes: 5