How to catch double tap events in Android using OnTouchListener

后端 未结 6 1757
孤独总比滥情好
孤独总比滥情好 2020-12-31 08:45

I am trying to catch double-tap events using OnTouchListener. I figure I would set a long for motionEvent.ACTION_DOWN, and a different long for a second motionEvent.ACTION_D

6条回答
  •  抹茶落季
    2020-12-31 09:08

    Another approach that supports both single click and double clicks using Kotlin Coroutine:

    var lastDown = 0L
    var clickCount = 0
    
    view.setOnTouchListener {v, event ->
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                val downTime = System.currentTimeMillis()
                clickCount++
                if (lastDown > 0 && downTime - lastDown < 300 && clickCount == 2) {
                    //double clicks happens here
                    clickCount = 0
                }
                lastDown = downTime
            }
            MotionEvent.ACTION_UP -> {
                CoroutineScope(Dispatchers.IO).launch {
                    //in case clickCount goes beyond than 1, here set it to 1
                    val upTime = System.currentTimeMillis()
                    if (upTime - lastDown <= 300 && clickCount > 0) {
                        clickCount = 1
                    }
                    delay(300)
                    if (System.currentTimeMillis() - lastDown > 300 && clickCount == 1) {
                        withContext(Dispatchers.Main) {
                            //single click happens here
                        }
                        clickCount = 0
                    }
                }
            }
        }
        true
    }
    

提交回复
热议问题