Search code examples
androidandroid-databinding

How to properly integrate Listener Bindings and Lambda expressions


I have started working on data binding in android application. As there is no proper material available so I am not able to properly understand the listener binding and lambda expression concept. I started studying android official documentation. In this documentation, I found following line under Listener Bindings which is not clear to me.

Listener bindings provide two choices for listener parameters: you can either ignore all parameters to the method or name all of them.

Can anyone help me to understand the above line as well as empty lambda expression and parameterised lambda expression? ex:

android:onClick="@{(v) -> v.isVisible() ? doSomething() : void}"
android:onClick="@{(theView) -> presenter.onSaveClick(theView, task)}"
android:onCheckedChanged="@{(cb, isChecked) -> presenter.completeChanged(task, isChecked)}" 

Thanks in advance.


Solution

  • Sorry, I meant to add this as an answer, not a comment.

    The onCheckedChanged() method is declared like this:

    void onCheckedChanged(CompoundButton buttonView, boolean isChecked);
    

    Any lambda expression must take all the parameters or none of them. For example:

    android:onCheckedChanged="@{(cb, isChecked) -> presenter.completeChanged(task, isChecked)}"
    android:onCheckedChanged="@{() -> presenter.completeChanged(task)}"
    

    The method that you call from the lambda can be anything you like, so you don't need to use any of the parameters.

    You can use any variable name that you'd like for the parameters. If you provided only some of the parameters, data binding wouldn't be able to figure out which parameters you wanted and which it could throw away. Thus, the all-or-none comment in the documentation.