Skip to content

Instantly share code, notes, and snippets.

@prilaga
Created November 19, 2022 01:32
Show Gist options
  • Save prilaga/16eaf81b1a76ec547449479eba01eb7f to your computer and use it in GitHub Desktop.
Save prilaga/16eaf81b1a76ec547449479eba01eb7f to your computer and use it in GitHub Desktop.
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