androiddata-bindingonclicklistenerandroid-binding-adapter

How to use customized onClick for data binding


I am using data binding and having trouble solving multiple quick click. I do not want to put a logic in every click instead, I want to create a solution once and expect it to work throughout my project.

I found one solution here. Code snippet from that page is as follows:

class SafeClickListener(
        private var defaultInterval: Int = 1000,
        private val onSafeCLick: (View) -> Unit
) : View.OnClickListener {
    private var lastTimeClicked: Long = 0
    override fun onClick(v: View) {
        if (SystemClock.elapsedRealtime() - lastTimeClicked < defaultInterval) {
            return
        }
        lastTimeClicked = SystemClock.elapsedRealtime()
        onSafeCLick(v)
    }
}

And using extension funciton:

fun View.setSafeOnClickListener(onSafeClick: (View) -> Unit) {
    val safeClickListener = SafeClickListener {
        onSafeClick(it)
    }
    setOnClickListener(safeClickListener)
}

And finally, for any view we can simply call:

anyView.setSafeOnClickListener {
    doYourStuff()
}

Which is awesome. But it only applies if I am calling setOnClickListener to a view but I am using data binding. Where I am using something like this:

android: onClick="@{(view) -> myViewModel.UIEvents(SomeUIEvent.showDialog)}"

I am aware that if I can create a binding adapter, I would be able to solve the problem. But, I couldn't make one that works. What code I should be putting here:

@BindingAdapter("android:myOwnClick")
fun CustomClickHandler(view: View, "some code here") {
    "And some codes here to deligate onclick to"
    "The setSafeOnClickListener defined above"
}

so that I would be able to use in my xml (databinding):

android: myOwnClick="@{(view) -> myViewModel.UIEvents(SomeUIEvent.showDialog)}"

How can I achieve something this? Please help. Thanks


Solution

  • Welcome to StackOverflow Community.

    Just copy your extension function to your binding adapter. :)

    @BindingAdapter("android:myOwnClick")
    fun CustomClickHandler(view: View, onSafeClick: (View) -> Unit) {
        val safeClickListener = SafeClickListener {
            onSafeClick(it)
        }
        setOnClickListener(safeClickListener)
    }