How to detect onLongClick ACTION_UP event?

2020-02-13 08:09发布

问题:

I have an image which implements both OnClickListener and OnLongClickListener. In the OnLongClickListener at press down (ACTION_DOWN) I start a timer. I want to cancel it at ACTION_UP.

Now, if I implement OnTouchListener for this image, then I catch ACTION_DOWN for normal clicks. And I want to catch Long clicks ONLY.

Why does not long click fire ACTION_UP event? How can I detect this event and stop the timer.

If you need a code, I can post it, but I do not think it will help you as there is no errors in the code.

PS. I cannot stop the timer at any specific time or value as this long press continuously increase the value of another element. This increase process should stop only at image long press ACTION_UP.

回答1:

Just use OnTouchListener and forget about OnLongClickListener. You can detect a long click by checking coordinates and pressed time, you have all that info in MotionEvent object passed by OnTouch().

1- To check coordinates, use getX() and getY() from MotionEvent and getDrawingRect() from your ImageView container.

2- To check for pressed time, use getEventTime(), storing first time in ACTION_DOWN and then compute by substracting with time in ACTION_UP event. You could assume like 800mS for a long click.