https://kotlinlang.org logo
#codereview
Title
# codereview
m

miqbaldc

03/24/2020, 11:27 AM
anyone knows why the lambda listener for
setOnClickLIstener
doesn’t works on point 1, but works in point 2,
DebouncingOnClickListener
is an interface that override
View.OnClickListener#onClick(View)
to prevent spamming click see this code below:
Copy code
// 1. this doesn't works
fun View.setDebouncingOnClickListener(onSafeClick: (View) -> Unit) {
    setOnClickListener(DebouncingOnClickListener {
        onSafeClick(it)
    })
}

// 2. this works
fun View.setDebouncingOnClickListener(onSafeClick: (View) -> Unit) {
    val listener = DebouncingOnClickListener {
        onSafeClick(it)
    }
    setOnClickListener(listener)
}
a

arekolek

03/24/2020, 12:52 PM
for me it works, I just had to add a
)
that was missing from
setOnClickListener
after the
}
btw, I think you could also do
Copy code
setOnClickListener(DebouncingOnClickListener(onSafeClick))
m

miqbaldc

03/24/2020, 2:57 PM
*sorry, typo for this
a

arekolek

03/24/2020, 3:11 PM
so what do you mean by "doesn't work" exactly?
it works fine as far as I can see
m

miqbaldc

03/25/2020, 6:04 AM
“doesn’t work” my onClick method doesn’t overrided by DebouncingClickListener, unless I choose option 2, here’s my code DebouncingClickListener interface (written in java):
Copy code
public interface DebouncingOnClickListener extends View.OnClickListener {

    Clicked clicked = new Clicked(0);

    void doClick(View v);

    @Override
    default void onClick(View v) {
        if (!clicked.get()) {
            clicked.set(SystemClock.elapsedRealtime());
            doClick(v);
        }
    }
}
Copy code
// when I tried to invoke using options 1
viewInKotlin.setDeouncingClickListener {
  // pressed twice, will show toast twice
}
5 Views