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.
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
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.
If you see the class which is called
ActivityMainBindingImpl.java
generated by the data-binding library, you can see thatandroid:enabled="@{true}"
part is converted tothis.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.
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.