whayway
whayway

Reputation: 33

How to call multiple onClick on one view, and combine this with data binding and ViewModel?

I'm trying to call multiple methods through onClick and pass it thru ViewModel to data binding. I'm calling view in xml file like that

android:onClick="@{() -> gameViewModel.increaseScore()}"

and I want to add another one method, but I receive error "Duplicate attribute onClick". Theoreticlly I find solution here - Multiple click listeners on buttons but I think that was not purpose of getting rid of setOnClickListners, to now implement View.OnClickListener listener and do the same in very similar way. Is there any clever way to combine this all together?

Upvotes: 0

Views: 1071

Answers (1)

Sylwek845
Sylwek845

Reputation: 145

With kotlin you can do something like this

@BindingAdapter("customOnClickListener")
fun View.customOnClickListener(viewModel: YourViewModel) {
    setOnClickListener {
        viewModel.actionOne()
        viewModel.actionActionTwo()
        //action three...
    }
}

Then in xml you use it like this:

app:customOnClickListener="@{viewModel}"

Upvotes: 1

Related Questions