I have a custom view in my android project, MyCustomView.
With a built-in view like button, I can use the data binding library to pass a callback function to the button:
<Button
...
android:onClick="@{() -> viewModel.donePressed()}" />
How can I pass a callback function which I can access in the MyCustomView class through the XML?
I want it to look something like this:
<MyCustomView app:onFinish="@{() -> viewModel.finish()}" />
Then in the MyCustomView class (extending LinearLayout) I need to call the onFinish variable.
Thank you for any ideas.
I found the answer: This is actually done automatically by Android.
If I add a public setter to my
MyCustomViewclass like this:Then Android will automatically generate the
app:onFinishattribute (without thesetpart of the name):Then, the function I defined is called after the constructor of the custom view.
If you need further customisation you can also use a Binding Adapter: https://developer.android.com/topic/libraries/data-binding/binding-adapters