The Android documentation does a great job of describing how one can create a binding class using a layout xml file. But I have a couple of questions.
Is there a way to create a data binding class for a custom view that is instantiated programmatically? For example, lets say I have two custom view classes and I want to bind the same view model object to them programmatically without using any xml. The classes are as follows:
class MyViewModel {
}
class MyCustomView extends View {
}
class MyAnotherCustomView extends MyCustomView {
}
Now lets say I instantiate MyCustomView/MyAnotherCustomView using:
MyCustomView customView = new MyCustomView(context);
How do I go about using data binding in this case? Is this possible using the official Android data binding framework? If not, what other frameworks/libraries are available or recommended to achieve this?
My second question is a follow up of the first question. Lets say it is not possible to achieve what I want in my first question. Then, I will have to define a my_custom_view.xml file. This will look something like this:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="user" type="com.example.User"/>
</data>
<com.example.name.MyCustomView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="@{user.firstName}"/>
</layout>
Now, if I want to use MyAnotherCustomView which is a subclass of MyCustomView keeping the binding logic the same, will I have to create a new xml file my_another_custom_view.xml just to replace MyCustomView with MyAnotherCustomView to define the same binding?
DataBindingUtil#bind(View root)"and I want to bind the same view model object to them programmatically without using any xml" oh sorry, i missed that, so what exactly are you trying to achieve? bindings are defined in xml only, so how do you want to define the mapping between data and views?