NaaleinGrohiik
NaaleinGrohiik

Reputation: 75

Custom onClickListener for databinding

I want to create a custom onClickListener to use for databinding. This custom click listener prevents the user from spamming the button and triggering the event twice(like showing two dialogues at the same time). I made a custom listener below that works in normal code, but I don't know how to implement it for databinding like the android:onClick="" in xml.

abstract class OneClickListener(var delay: Long) : View.OnClickListener {
private var hasClicked: Boolean = true

constructor() : this(1000)

override fun onClick(it: View) {
    if (!hasClicked) {
        return
    } else {
        hasClicked = false
        onClicked(it)
        GlobalScope.launch {
            delay(delay)
            hasClicked = true
        }
    }
}

abstract fun onClicked(it: View)

}

Is it possible to use this listner in databinding like for example app:OneClickListener="@{viewModel::MyMethod}" in XML? and if yes, could you please tell me how?

Upvotes: 3

Views: 1088

Answers (1)

Gregorio Palamà
Gregorio Palamà

Reputation: 1952

Using data binding you can specify which listener to call when an event is fired just by calling it in a lambda. For example, let's say you have a method in your viewmodel, called myOnClick(). You can use it with data binding this way:

android:onClick="@{() -> viewModel.myOnClick()}"

Defining a custom binding adapter called OneClickListener is something different and it would not be called when the click event is fired, unless you use a trick: registering a click listener inside the custom binding adapter. This means you would have to call a method that register an other method: not really the cleanest way to add a listener.

Upvotes: 1

Related Questions