Using DataBinding library for binding events
Many Ways for setting Click
Pass handler to binding.
ActivityMainBinding binding = DataBindingUtil.setContentView(this,R.layout.activity_main); Hander handler = new Handler(); binding.setHandler(handler);
Set clicks (use any of below)
android:onClick="@{handler::onClickMethodReference}"
OR
android:onClick="@{handler.onClickMethodReference}"
OR
android:onClick="@{() -> handler.onClickLamda()}"
OR
android:onClick="@{(v) -> handler.onClickLamdaWithView(v)}"
OR
android:onClick="@{() -> handler.onClickLamdaWithView(model)}"
See Handler class for understanding.
public class Handler {
public void onClickMethodReference(View view) {
//
}
public void onClickLamda() {
//
}
public void onClickLamdaWithView(View view) {
//
}
public void onClickLamdaWithObject(Model model) {
//
}
}
Note that
- You can use Method Reference (::) when you have same argument as the attribute onClick.
- You can pass any object like
onClickLamdaWithObject
example. - If you need to pass
View
object then just use(v)->
expression.
Further reading
https://developer.android.com/topic/libraries/data-binding/expressions
I think you will need to bind the handlers
as well, maybe something like this in onCreate
:
MyHandlers handlers = new MyHandlers();
binding.setHandlers(handlers);