使用 GestureDetector 对触屏事件监听
一、构造方法
GenstureDetector(GenstureDetector.OnGestureListener listener);
GenstureDetector(Context context,GenstureDetector.OnGestureListener listener);
GenstureDetector(Context context,GenstureDetector.SimpleOnGestureListener listener);
等等…
二、 OnGestureListener 监听单击
相关重写方法及作用:
方法名 | 作用 |
---|---|
public boolean onDown(MotionEvent e) | 用户按下就会触发 |
public void onShowPress(MotionEvent e) | 如果按下的事件超过一瞬间,且按下时没有松开或是拖动的情况下执行 |
public boolean onSingleTapUp(MotionEvent e) | 单击屏幕并立即抬起,触发该事件 |
public boolean onScroll(MotionEvent e1,MotionEvent e2) | 在屏幕上拖动事件,多次触发 |
public void onLongPress(MotionEvent e) | 长安触摸屏,超过一定时长,该事件触发 |
public boolean onFling(MotionEvent e1,MotionEvent e2,float velocityX,float velocityY) | 滑屏,用户按下触摸屏,移动并松开后执行 |
执行情况示例: |
- 长按屏幕:onDown() -> onShowPress() -> onLongPress();
- 快速单击屏幕(不滑动):onDown() -> onSingleTapUp() -> onSingleTapConfirmed()
- 缓慢点击(不滑动):onDown() -> onShowPress() -> onSingleTapUp() -> onSingleTapConfirmed();
- 滑动屏幕后立刻松开:onDown() -> onScroll() -> onScroll() -> onScroll() -> … -> onFoling();
三、OnGestureListener 使用
创建 GestureDetector 对象,在 控件发生的 onTouch() 方法中直接调用即可。
public boolean onTouch(View v,MotionEvent event) {
new GestureDetector(new OnGestureListener()).onTouch(event);
}
四、OnDoubleTapListener 监听双击
相关重写方法及作用:
方法名 | 作用 |
---|---|
public boolean onSingleTapConfirmed(MotionEvent e) | 单击事件,若只点击一次,且一段时间内未进行第二次点击,则该方法执行 |
public boolean onDoubleTap(MotionEvent e) | 双击事件触发 |
public boolean onDoubleTapEvent(MotionEvent e) | 双击间隔中发生的动作 |
方法示例说明: |
- onSingleTapConfirmed() :单击后一段事件没有点击,便会触发,与onSinlgleTapUp()不同,onSingleTapUp() 只要点击抬起就会触发;如单击情况下,onDown() -> onSingleTapUp() -> onSingleTapConfirmed()。
- onDoubleTapEvent() :双击结束后,执行双击期间发生的动作。
五、SimpleOnGestureListener 监听单双击
SimpleOnGestureListener 对 OnGestureListener 和 OnDoubleTapListener 进行了空实现,根据需求重写方法即可。