Skip to content

Instantly share code, notes, and snippets.

@TimoPtr
Created November 25, 2018 11:09
Show Gist options
  • Save TimoPtr/66073007b71bad1ecba9793eec2f924b to your computer and use it in GitHub Desktop.
Save TimoPtr/66073007b71bad1ecba9793eec2f924b to your computer and use it in GitHub Desktop.
DebounceClickListener
import android.view.View
/**
* Created by timoptr on 25/11/2018.
*/
/**
* This class is an Helper to avoid double click (spam) on a view click listener
* It will avoid it by dismiss click which are not separate by at least [DOUBLE_CLICK_TIMEOUT]
*
* @param click the clickListener to apply when ot respect the constraint of time
*/
class DebouncedClickListener(val click: (v: View) -> Unit) : View.OnClickListener {
private val DOUBLE_CLICK_TIMEOUT = 500L
private var lastClick: Long = 0
/**
* Checker method, the first click is done (call [click] and store the last click time into [lastClick])
* when a second click arrived verify that the minimum time [DOUBLE_CLICK_TIMEOUT] is pass otherwise drop the click
*
* @param v the view where the click appear
*/
override fun onClick(v: View) {
if (getLastClickTimeout() > DOUBLE_CLICK_TIMEOUT) {
lastClick = System.currentTimeMillis()
click(v)
}
}
private fun getLastClickTimeout(): Long {
return System.currentTimeMillis() - lastClick
}
}
import android.view.View
fun View.setDebouncedClickListener(click: (v: View) -> Unit) {
setOnClickListener(DebouncedClickListener(click))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment