javaandroidkotlinandroid-activityandroid-touch-event

Can't get time pressed in onTouch


I'm trying to get the time the user takes pressing a button. I'm doing like that:

var timeDown = 0L
when (event.actionMasked) {
    MotionEvent.ACTION_DOWN -> {
        timeDown = event.eventTime
        true
    }
    MotionEvent.ACTION_UP -> {
        val totalTime = event.eventTime - timeDown`

        if (totalTime <= 500) {
            do something
        }
    }
}

But it isn't subtracting, totalTime holds only the eventTime of Action_UP

Here's my LogCat:

2020-05-13 11:58:57.194 11259-11259/app D/timeDown: 34492026
2020-05-13 11:58:57.240 11259-11259/app D/timeUp: 34492083
2020-05-13 11:58:57.240 11259-11259/app D/totalTime: 34492083

Solution

  • Ensure var timeDown = 0L is outside the function that is being invoked on touch (onInterceptTouchEvent for example) because you assign = 0 on every event that you receive so you end up in "ACTION_UP ->" you end up with timeDown = 0 and totalTime becomes equal to event.eventTime.