I am trying to set android:textAppearance
with use of DataBinding
, but it is not allowing me to use ?android:attr/textAppearanceLarge
with ternary operator.
android:textAppearance="@{position==1 ? ?android:attr/textAppearanceLarge : ?android:attr/textAppearanceMedium}"
It is showing me compile time error <expr> expected, got '?'
.
Does there any other way to use this with DataBinding?
You can use android.R.attr package instead of the ?android:attr
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<import type="android.R.attr"/>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="hello world"
android:textAppearance='@{age==1 ? android.R.attr.textAppearanceLarge : android.R.attr.textAppearanceMedium}'
tools:textAppearance="?android:textAppearanceLarge"
/>
</LinearLayout>
</layout>
You cannot use it directly, however here's trick I use in such cases. Create own styles using textAppearanceLarge
and textAppearanceMedium
as parents and then set these styles instead:
First create Foo
style:
<style name="Foo" parent="TextAppearance.AppCompat.Large">
... [whatever you need to set or override ] ...
</style>
and do the same for for FooMedium
. Then edit your layout file as shown below. Note you must import project's R
class in <data>
block first:
<data>
<import type="<your-package-id>.R"
</data>
Finally apply the appearance as you formerly wanted:
android:textAppearance="@{ position==1 ? R.style.Foo : R.style.FooMedium }"
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