Created
December 2, 2019 09:23
-
-
Save matpag/1d24841533944dd9fca5fb61e534ca17 to your computer and use it in GitHub Desktop.
ThrottleClickListener prevent double click using OnClickListener
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.os.SystemClock | |
import android.view.View | |
/** | |
* This is a custom clicklistener to prevent multiple click events to happens at the same time. | |
* | |
* Each click on a button is added in the internal event handler queue, there is no way to remove | |
* them from there so the only thing we can do is adding a filter to prevent them to run too | |
* frequently | |
* | |
* In RxJava this could be achieved using RxBinding and throttleFirst operator | |
* | |
* Base implementation took from here: https://stackoverflow.com/a/20672997/2910520 | |
*/ | |
abstract class OnThrottleClickListener @JvmOverloads constructor( | |
private val minClickInterval: Long = 600 //default value for minclick time | |
) : View.OnClickListener { | |
/** | |
* The time the last click was applied | |
*/ | |
private var mLastClickTime: Long = 0 | |
/** | |
* @param v The view that was clicked. | |
*/ | |
abstract fun onSingleClick(v: View?) | |
override fun onClick(v: View?) { | |
val currentClickTime: Long = SystemClock.elapsedRealtime() | |
val elapsedTime = currentClickTime - mLastClickTime | |
if (elapsedTime <= minClickInterval) return | |
mLastClickTime = currentClickTime | |
onSingleClick(v) | |
} | |
} | |
//Extension (optional but usefull): | |
fun View.setThrottleClickListener(action: (v: View?) -> Unit, millis: Long = 700) { | |
setOnClickListener(object : OnThrottleClickListener(millis) { | |
override fun onSingleClick(v: View?) { | |
action(v) | |
} | |
}) | |
} | |
//Usage with default millis timeout: | |
button.setThrottleClickListener({ | |
//my click logic | |
}) | |
//Usage with custom millis timeout: | |
button.setThrottleClickListener({ | |
//my click logic | |
}, 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment