When a user clicks, case MotionEvent.ACTION_DOWN is triggered. When the click is released, case MotionEvent.ACTION_UP is triggered.
I’m interested in determining if ACTION_UP hasn’t been triggered within 3 seconds of ACTION_DOWN. Meaning, If 3 seconds have passed since the user has clicked and has not yet released, I want to know, essentially trying to determine a long click.
Is there a way to do such a thing?
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_UP:
break;
}
Generally the right way to detect a long-click is by implementing
View.OnLongClickListener. This is easier and less error-prone that detecting it yourself, and it ensures that your app fits in well with the rest of the system.
For a custom
View, you would addimplements View.OnLongClickListenerto your class declaration, addsetOnLongClickListener(this);to the constructor, and add theonLongClick()method to your class:If your
Viewisn’t custom you can add the listener like this:Update: Okay, I’ve done some digging, and while this is the right way to do it for every View I’ve ever worked with, it in fact does not work for SeekBars, which is what the questioner is working with. This fact is not documented in the
SeekBardocumentation, but experimentation has shown it to be true, and digging through the source code shows why:SeekBar.onTouchEvent()does not callsuper.onTouchEvent(). It is inView.onTouchEvent()thatperformLongClick()is called, if appropriate.The way I would implement it if I had to is with
Handler.postDelayed(). On ACTION_DOWN, I would post (with e.g. 3000ms delay) aRunnablethat handles the long-press to aHandler, and I’d cancel it on ACTION_UP. So any press for less than the delay doesn’t end up calling theRunnable, but if ACTION_UP hasn’t occurred after the delay, it is.That said, I’d caution you to rethink doing this at all. What does it mean to long-press a
SeekBar? If the user is dragging the “thumb” for longer than the delay, suddenly you have a long-press that probably was not meant as one. You can cancel and reset the delay every time the thumb is moved, requiring a long-press to be several seconds in exactly one position. But it’s rare to be perfectly still; it’s in fact difficult to hold the thumb yet not move it for several seconds. So you could then have a minimum change in thumb position that resets the delay. That’s what I would do if I had to, but I must say it’s a very strange user experience.