The following subclass of View.OnClickListener can be set as a listener to any View. When the user clicks on that view enough times within a defined time limit (here, the target is defined as 7 clicks within 2 seconds), the onCompletion handler is called.
This is a useful feature in some cases e.g. defining a double-click handler, activating a hidden debug mode while the app is running.
class MultipleClickListener : View.OnClickListener {
val maxDuration: Long = 2000 // in milliseconds
val minTaps: Int = 7 // minimum number of clicks to complete
var iconTapCount: Int = 0
var start: Long = 0
val now: Long
get() = System.currentTimeMillis()
override fun onClick(v: View?) {
// This method returns a ViewPropertyAnimator object, which we could use to
// animate the View per click for visual feedback.
val animator = v?.animate()
if(0 == iconTapCount || now - start > maxDuration) {
iconTapCount = 0
start = now
}
if(now - start < maxDuration) {
iconTapCount += 1
}
if(iconTapCount == minTaps) {
onCompletion()
}
}
// do something e.g. open a new view, switch on debug mode etc
fun onCompletion() {}
}