GestureDetector.onTouchEvent(MotionEvent e) calling onLongPress on all gestures

旧城冷巷雨未停 提交于 2020-01-02 09:55:45

问题


I have a custom view on which I want to set long click listener. I am using following code to set the same.

final GestureDetector gestureDetector = (new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
    public void onLongPress(MotionEvent e) {
        Log.e("test", "Long press detected");
    }
}));

public boolean onTouchEvent(MotionEvent event) {
    return gestureDetector.onTouchEvent(event);
}

The problem is on all gestures whether it is a single tap, double tap onLongPress is getting called.

I can get the code to working by implementing onDown() method but why this is not working when it is not implemented? Shouldn't onLongPress() be called only when the gesture is onLongPress?


回答1:


in case someone is still getting stuck on this, i found out this was happening when i was doing the following :

return gestureDetector.onTouchEvent(event);

as opposed to this: (also mentioned in the link Mcloving has posted in the comment)

gestureDetector.onTouchEvent(event);
return true;

this and this perhaps explain it why:

Beware of creating a listener that returns false for the ACTION_DOWN event. If you do this, the listener will not be called for the subsequent ACTION_MOVE and ACTION_UP string of events. This is because ACTION_DOWN is the starting point for all touch events.




回答2:


Why are you using a GestureDetector for longClick? if you just need this Gesture then just set a LongClickListener for the view. http://developer.android.com/reference/android/view/View.html#setOnLongClickListener(android.view.View.OnLongClickListener)

If you still want to implement a GestureDetector follow the example here: https://developer.android.com/training/gestures/detector.html From a quick look it seems you implemented the on touch differently, this is how it's done in the example:

@Override 
public boolean onTouchEvent(MotionEvent event){ 
    this.mDetector.onTouchEvent(event);
    return super.onTouchEvent(event);
}


来源:https://stackoverflow.com/questions/32177573/gesturedetector-ontoucheventmotionevent-e-calling-onlongpress-on-all-gestures

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!