1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

View Listener to activate feature after N clicks within time limit

Posted at

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

}
1
0
0

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
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?