1

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)?

0

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I'll try, but BookView is not a TextView
@Andrea yes, that is not a problem, the sample is just for your reference. You can invoke the appropriate call inside the Binding adapter.
Thank you very much for all the insight. You also happen to know what's the appropriate style-setting call if BookView is AppCompatImageView?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.