Home > Software design >  Android Databinding, set xml style from a function call
Android Databinding, set xml style from a function call

Time:10-25

App description

I'm using data binding in a simple android app which shows a list of books.
I use a RecyclerView to list them. I prepared a Book object which has a title and a color.

data class Book(val title: String, val color: BookColor)

Where BookColor is an enum, containing 10 different colors.
Now, I created 10 different styles (tailored for the BookView custom view) for all the 10 colors (so that they are compatible with dark mode).

Issue

What I can't figure out is how to get the book style applied to the actual BookView using databinding.

I would like to use (from databinding) a function I can define in a helper class, something like:

fun mapColorToStyle(color: Book)

accepting a Book object, which will map book.color to its matching XML style.

Then the style will be returned to the view (the RecyclerView item).

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

<data>
    <variable
        name="book"
        type="com.x.y.model.Book" />
</data>


<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <BookView
        android:id="@ id/squircle"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_gravity="center"
        android:padding="26dp"
        style="@{???}"
    />

    <TextView ... />
</LinearLayout>

Is there a way to achieve this without setting the style programmatically (which I doubt is a nice solution)?

CodePudding user response:

You can use the binding adapter instead of applying the style mentioned above.

@BindingAdapter("bindBookViewStyle")
fun TextView.bindViewStyle(bookColor: BookColor) {
    val style =  mapColorToStyle(bookColor)
    TextViewCompat.setTextAppearance(this, style)
}    

and then modify your item xml

<layout xmlns:app="http://schemas.android.com/apk/res-auto">

<data>

    <variable
        name="book"
        type="com.xx.xx.Book" />
</data>

<BookView app:bindBookViewStyle="@{book.color}" />

Please check similar answers

  • Related