I have some lines code that prevents multiple quick click on a button.
If I use that code every time inside Button.OnClickListener
, it works fine.
But calling the same code every time is not a good idea, so I wanted to keep the code as a global function and call the function when needed.
Here is my code:
lastClickTime = 0L
MyButton.setOnClickListener {
if (SystemClock.elapsedRealtime() - lastClickTime < 1000) {
return@setOnClickListener
}
lastClickTime = SystemClock.elapsedRealtime()
I am trying to make a global method to call from every Button.OnClickListener
. But I couldn't figure it out what code can replace return@setOnClickListener
.
var lastClickTime = 0L
fun preventMultiQuickClick() {
if (SystemClock.elapsedRealtime() - lastClickTime < 1000) {
//I WANT TO RETURN TO THE button.setOnClickListener
//OF THE BUTTON WHICH INVOKES THIS FUNCTION LIKE IN ABOVE CODE
}
lastClickTime = SystemClock.elapsedRealtime()
}
Button.setOnClickListener {
preventMultiQuickClick()
//do other stuffs
}
How can I achieve this? Any help will be highly appreciated.
You can do it like this:
var lastClickTime = 0L
fun preventMultiQuickClick(): Boolean {
return if (SystemClock.elapsedRealtime() - lastClickTime < 1000) {
false
}
lastClickTime = SystemClock.elapsedRealtime()
true
}
Button.setOnClickListener {
if(!preventMultiQuickClick()) {
//do other stuffs
}
}