Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set android:textAppearance with DataBinding

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?

like image 672
Ravi Avatar asked Aug 16 '16 09:08

Ravi


2 Answers

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>
like image 126
Long Ranger Avatar answered Oct 15 '22 23:10

Long Ranger


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 }"
like image 20
Marcin Orlowski Avatar answered Oct 15 '22 23:10

Marcin Orlowski