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
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
}