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?
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.
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