search
LoginSignup
0

More than 3 years have passed since last update.

Organization

View Listener to activate feature after N clicks within time limit

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() {}

}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0