参考Android中的双击事件使用如下代码对TextView
进行双击监听,发现怎么也触发不了双击事件。
GestureDetector gestureDetector;
gestureDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDoubleTap(MotionEvent e) {
Toast.makeText(mContext, "这是双击事件", Toast.LENGTH_SHORT).show();
return super.onDoubleTap(e);
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Toast.makeText(mContext, "单击击事件 onSingleTapConfirmed", Toast.LENGTH_SHORT).show();
return super.onSingleTapConfirmed(e);
}
});
tv.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
});
查阅资料之后发现,需要进行如下修改:
GestureDetector gestureDetector;
gestureDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener() {
@Override
public boolean onDoubleTap(MotionEvent e) {
Toast.makeText(mContext, "这是双击事件", Toast.LENGTH_SHORT).show();
return super.onDoubleTap(e);
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
Toast.makeText(mContext, "单击击事件 onSingleTapConfirmed", Toast.LENGTH_SHORT).show();
return super.onSingleTapConfirmed(e);
}
@Override
public boolean onDown(MotionEvent e) {
return true;
}
});
tv.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
});
需重写GestureDetector.SimpleOnGestureListener()
中的onDown()
返回true
原因:
https://developer.android.com/training/gestures/detector.html 中的描述:
Whether or not you use GestureDetector.OnGestureListener, it's best practice to implement an onDown() method that returns true. This is because all gestures begin with an onDown() message. If you return false from onDown(), as GestureDetector.SimpleOnGestureListener does by default, the system assumes that you want to ignore the rest of the gesture, and the other methods of GestureDetector.OnGestureListener never get called. This has the potential to cause unexpected problems in your app. The only time you should return false from onDown() is if you truly want to ignore an entire gesture.
onDown()
是所有方法的开始,只有onDown()
返回true
,后续的手势监听才会被触发
网友评论