Can LongPress trigger after move events?

2019-07-08 22:40发布

I am working on a simple android app, my Requirement is,

"After some move events(MotionEvent.ACTION_MOVE is true) on the screen, if the user stops moving for few seconds some where with out taking finger from the screen, then need to perform some action."

*I learnt that LongPress is something which triggers when user doesn't make any move after the down event is triggered(MotionEvent.ACTION_DOWN).*

So is there any way to trigger LongPress after Moving around in the screen?

Or should I create my own listener for the same functionality??

Any help is appreciated.

Thank you.

2条回答
干净又极端
2楼-- · 2019-07-08 23:24

Idea is to cancel the timer everytime you move finger on screen(MotionEvent.ACTION_MOVE). When you stop moving after some time, say after 3 seconds, timer code will get executed, in which you can do long press task. If you stop moving for some time and again start moving before elapse time (3 sec), again new timer is set and so on. Hope it helps you.

timer = new Timer();

public boolean onTouchEvent(MotionEvent event) 
{
    switch(event.getAction()) 
    {
        case MotionEvent.ACTION_DOWN:
             break;

        case MotionEvent.ACTION_MOVE:
             timer.cancel();
             timer = null;
             timer = new Timer();
             timer.schedule(new TimerTask() 
             {                  
                @Override
                public void run() {
                    // do your long press task here
                }
             }, 3000);
             break;

        case MotionEvent.ACTION_UP:
             timer.cancel();
             timer = null;
             break;
    }
    return super.onTouchEvent(event);
}
查看更多
▲ chillily
3楼-- · 2019-07-08 23:25

i'm afraid you will have to do it on your own. The default implementation is to trigger the long press event only if there is no Move event

the key is to use System.getCurrentTime() in onTouchEvent()

How?

in onTouch()

  • look for Motion_DOWN event,

    • note(set in a long variable) the time of touch event. (use System.getCurrentTime())
    • set a boolean (say isClicked to true)
    • start a timer task , to be executed after x miliseconds (where x is the duration for your longClick) if isClicked is still true. Think of it as your onLongClick Listener

--

  • on Motion_UP event
    • set isClicked as false.

EDIT: i missed one important step :

  • on Motion_MOVE event
    • restart the timer task (i.e cancel + start)
查看更多
登录 后发表回答