nilTheDev
nilTheDev

Reputation: 450

How to modify the layout expression dynamically in data binding layout?

Let's say I have a data binding layout that looks something like this,

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    ...
    <data>
        <variable
            name="foo"
            type="com.example.sudokugame.Foo" />
    </data>
    ...

        <TextView
            android:id="@+id/cell_1"
            style="@style/cell"
            android:text="@{foo.bar}" />
    ...
</layout>

I want to inflate the layout and add it to another parent layout. So, my question is, is there any to modify the layout expression in the textview so it would look something like this,

...
<TextView
    android:id="@+id/cell_1"
    style="@style/cell"
    android:text="@{foo.baz}" <!-- or something else like foo.something -->
....

Is it possible? And if not is there any way to build a data binding layout completely programmatically without even defining an XML layout so that it could be added to another layout?

Upvotes: 0

Views: 638

Answers (1)

Anand
Anand

Reputation: 927

Use binding adapters to achieve this. Here is how you can do,

@BindingAdapter("dynamicText")
fun TextView.setDynamicText(foo: Foo) {
    text = if (<your_condition>) {
        foo.bar;
    } else {
        foo.something;
    }
}

Now change your xml textview property to,

<TextView
        android:id="@+id/cell_1"
        style="@style/cell"
        android:dynamicText="@{foo}" />

Upvotes: 1

Related Questions