How do you bind custom attribute types to custom views?

1.4k Views Asked by At

I'm using data binding with my view models and views, and I'd like my custom view to observe my custom type, like this:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="viewModel"
            type="com.myapp.MyViewModel" />
    </data>

    ...

        <com.myapp.MyCustomView
            android:id="@+id/custom_view"
            app:thing="@{viewModel.customThing}" />. <!-- customThing is type com.myapp.MyThing -->
/>

In the above example, viewModel.customThing is a type that MyCustomView understands and expects. Can I pass it to my view this way? If not, is there another way to bind custom types to custom views in XML? I can't seem to make it work.

1

There are 1 best solutions below

0
On

Yes, you can make your custom view support data-binding. There are two ways to implement this feature for your custom view.

1. binding adapter

For example, in your case

@BindingAdapter("thing") // attribute that you want to support data binding
fun setThing(view: MyCustomView, value: MyThing) {
    view.processThing(value)
}

But you should note that the binding adapter way can have a problem when previewing a layout in android studio.

2. Binding to setters

Let's assume that there is a layout that is called 'activity_main.xml' and that layout supports data-binding. And There is a TextView widget in the layout.

<TextView
   android:id="@+id/title
   android:text="title"
   android:enabled="@{true}"/>

If you see the class which is called ActivityMainBindingImpl.java generated by the data-binding library, you can see that android:enabled="@{true}" part is converted to this.title.setEnabled(true);

As you can see, the data-binding library is called its setters. So if you want the thing attribute to support data-binding, You can add a setter in your custom view class.

fun setThing(value: MyThing){
  // Do your stuff
}

When finishing added a custom setter, Place your cursor in layout editor in an attr "thing" and press ctrl+b(go to definition shortcut). You can see that it connects with the setter you declared.