Skip to content

Instantly share code, notes, and snippets.

@NezSpencer
Created March 25, 2021 07:43
Show Gist options
  • Save NezSpencer/1e99bfdbdeeaae5c640d376a128def91 to your computer and use it in GitHub Desktop.
Save NezSpencer/1e99bfdbdeeaae5c640d376a128def91 to your computer and use it in GitHub Desktop.
Using a blocking ClickListener to prevent multiple clicks within a specified waitTime
package com.nezspencer.navigationtest
import android.os.Bundle
import android.os.SystemClock
import android.util.Log
import android.view.View
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import kotlinx.android.synthetic.main.fragment_one.*
class FragmentOne : Fragment(R.layout.fragment_one) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btn_open_screen_two.blockingClickListener {
findNavController().navigate(FragmentOneDirections.actionFragmentOneToFragmentTwo())
}
btn_double_click.setOnClickListener {
performDoubleClick()
}
}
private fun performDoubleClick() {
for (i in 1 downTo 0) {
btn_open_screen_two.performClick()
}
}
private val clickTag = "__click__"
fun View.blockingClickListener(debounceTime: Long = 1200L, action: () -> Unit) {
this.setOnClickListener(object : View.OnClickListener {
private var lastClickTime: Long = 0
override fun onClick(v: View) {
val timeNow = SystemClock.elapsedRealtime()
val elapsedTimeSinceLastClick = timeNow - lastClickTime
Log.d(clickTag, """
DebounceTime: $debounceTime
Time Elapsed: $elapsedTimeSinceLastClick
Is within debounce time: ${elapsedTimeSinceLastClick < debounceTime}
""".trimIndent())
if (elapsedTimeSinceLastClick < debounceTime) {
Log.d(clickTag, "Double click shielded")
return
}
else {
Log.d(clickTag, "Click happened")
action()
}
lastClickTime = SystemClock.elapsedRealtime()
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment