Skip to content

Instantly share code, notes, and snippets.

@afollestad
Created November 30, 2018 22:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afollestad/cfdbe91dd6695b84a4e323a53d65d772 to your computer and use it in GitHub Desktop.
Save afollestad/cfdbe91dd6695b84a4e323a53d65d772 to your computer and use it in GitHub Desktop.
import android.view.View
import java.lang.System.currentTimeMillis
private const val HALF_SECOND = 500L
/** @author Aidan Follestad (@afollestad) */
abstract class DebouncedOnClickListener(
private val delayBetweenClicks: Long = HALF_SECOND
) : View.OnClickListener {
private var lastClickTimestamp = -1L
@Deprecated(
message = "onDebouncedClick should be overridden instead.",
replaceWith = ReplaceWith("onDebouncedClick(v)")
)
override fun onClick(v: View) {
val now = currentTimeMillis()
if (lastClickTimestamp == -1L || now >= (lastClickTimestamp + delayBetweenClicks)) {
onDebouncedClick(v)
}
lastClickTimestamp = now
}
abstract fun onDebouncedClick(v: View)
}
/** @author Aidan Follestad (@afollestad) */
fun View.onDebouncedClick(
delayBetweenClicks: Long = HALF_SECOND,
click: (view: View) -> Unit
) {
setOnClickListener(object : DebouncedOnClickListener(delayBetweenClicks) {
override fun onDebouncedClick(v: View) {
click(v)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment