Last active
August 6, 2021 13:05
-
-
Save kibotu/d949f8f4c0f095f9118c095b4c272232 to your computer and use it in GitHub Desktop.
ThrottleFirstClickListener
This file contains 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.view.View | |
/** | |
* An OnClickListener that sends only the first click of a given Time Interval | |
* | |
* @param defaultInterval time frame to skip until next click is send | |
* @param onThrottleFirstClick callback | |
*/ | |
class ThrottleFirstClickListener( | |
private var defaultInterval: Int = 100, | |
private val onThrottleFirstClick: (View) -> Unit | |
) : View.OnClickListener { | |
private var lastTimeClicked: Long = 0 | |
override fun onClick(view: View) { | |
val currentTime = System.currentTimeMillis() | |
if (currentTime - lastTimeClicked < defaultInterval) { | |
return | |
} | |
lastTimeClicked = System.currentTimeMillis() | |
onThrottleFirstClick(view) | |
} | |
} | |
fun View.setOnClickListenerThrottled(defaultInterval: Int = 100, onThrottleFirstClick: (View) -> Unit): ThrottleFirstClickListener { | |
val throttleFirstClickListener = ThrottleFirstClickListener(defaultInterval = defaultInterval) { | |
onThrottleFirstClick(it) | |
} | |
setOnClickListener(throttleFirstClickListener) | |
return throttleFirstClickListener | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment