androidandroid-custom-viewandroid-xmlandroid-custom-attributes

Pass Callback Function to Custom View in Android


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.


Solution

  • I found the answer: This is actually done automatically by Android.

    If I add a public setter to my MyCustomView class like this:

    public fun setOnFinish(callback: () -> Unit) {
        ...
    }
    

    Then Android will automatically generate the app:onFinish attribute (without the set part of the name):

    <MyCustomView app:onFinish="@{() -> viewModel.finish()}" />
    

    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