Created
April 8, 2020 17:25
-
-
Save gotev/0db92be46d68aad34ee262b271b5b1bd to your computer and use it in GitHub Desktop.
Android Safe Click Listener
This file contains hidden or 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