Skip to content

Instantly share code, notes, and snippets.

@nadar71
Created October 21, 2020 09:38
Show Gist options
  • Save nadar71/d4b1faccb9551df7d7f001c5dda305ce to your computer and use it in GitHub Desktop.
Save nadar71/d4b1faccb9551df7d7f001c5dda305ce to your computer and use it in GitHub Desktop.
Avoid single click
import android.view.View
// * for issue 1189:
// https://stackoverflow.com/questions/51060762/illegalargumentexception-navigation-destination-xxx-is-unknown-to-this-navcontr
class OnSingleClickListener : View.OnClickListener {
private val onClickListener: View.OnClickListener
constructor(listener: View.OnClickListener) {
onClickListener = listener
}
constructor(listener: (View) -> Unit) {
onClickListener = View.OnClickListener { listener.invoke(it) }
}
override fun onClick(v: View) {
val currentTimeMillis = System.currentTimeMillis()
if (currentTimeMillis >= previousClickTimeMillis + DELAY_MILLIS) {
previousClickTimeMillis = currentTimeMillis
onClickListener.onClick(v)
}
}
companion object {
// Tweak this value as you see fit. In my personal testing this
// seems to be good, but you may want to try on some different
// devices and make sure you can't produce any crashes.
private const val DELAY_MILLIS = 200L
private var previousClickTimeMillis = 0L
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment