Skip to content

Instantly share code, notes, and snippets.

@gotev
Created April 8, 2020 17:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gotev/0db92be46d68aad34ee262b271b5b1bd to your computer and use it in GitHub Desktop.
Save gotev/0db92be46d68aad34ee262b271b5b1bd to your computer and use it in GitHub Desktop.
Android Safe Click Listener
import android.os.SystemClock
import android.view.View
/**
* Implements the "throttle first" mechanism for click listeners, to prevent double taps.
*
* How it works:
* - Define a sampling window time (default: 500ms)
* - when you click at time T0, the first click gets dispatched and the subsequent ones happening
* between T0 and T0 + WindowTime gets ignored
*/
inline fun View.onSafeClick(throttleTime: Int = 500, crossinline listener: (View) -> Unit) {
var clickTime = 0L
setOnClickListener {
if (SystemClock.uptimeMillis() <= (clickTime + throttleTime)) return@setOnClickListener
clickTime = SystemClock.uptimeMillis()
listener(it)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment