Created
November 19, 2022 01:32
-
-
Save prilaga/16eaf81b1a76ec547449479eba01eb7f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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