Android ScaleGestureDetector 和 GestureDetector 手势检测
- ScaleGestureDetector.SimpleOnScaleGestureListener 静态内部类,实现了 OnScaleGestureListener 接口,方法都是默认空实现
- GestureDetector.SimpleOnGestureListener 静态内部类,实现了 OnGestureListener, OnDoubleTapListener, OnContextClickListener,方法都是默认空实现
ScaleGestureDetector 缩放手势检测
- 可以接管 View 的 onTouchEvent 方法或者 OnTouchListener 的 onTouch 方法
override fun onTouchEvent(event: MotionEvent?): Boolean {
return scaleGestureDetector.onTouchEvent(event) || super.onTouchEvent(event)
}
ScaleGestureDetector.OnScaleGestureListener
- OnScaleGestureListener 接口包括 onScale、onScaleBegin 和 onScaleEnd 方法
public interface OnScaleGestureListener {
public boolean onScale(@NonNull ScaleGestureDetector detector);
public boolean onScaleBegin(@NonNull ScaleGestureDetector detector);
public void onScaleEnd(@NonNull ScaleGestureDetector detector);
}
GestureDetector 手势检测
- 可以接管 View 的 onTouchEvent 方法或者 OnTouchListener 的 onTouch 方法
override fun onTouchEvent(event: MotionEvent?): Boolean {
return gestureDetector.onTouchEvent(event) || super.onTouchEvent(event)
}
- GestureDetector.OnContextClickListener 接口,外接键盘、蓝牙外设等事件
GestureDetector.OnGestureListener
- OnGestureListener 接口包括 onScroll 滑动、onFling 抛、onSingleTapUp 短按和 onLongPress 长按等
public interface OnGestureListener {
boolean onDown(@NonNull MotionEvent e);
void onShowPress(@NonNull MotionEvent e);
boolean onSingleTapUp(@NonNull MotionEvent e);
boolean onScroll(@Nullable MotionEvent e1, @NonNull MotionEvent e2, float distanceX, float distanceY);
void onLongPress(@NonNull MotionEvent e);
boolean onFling(@Nullable MotionEvent e1, @NonNull MotionEvent e2, float velocityX, float velocityY);
}
GestureDetector.OnDoubleTapListener
- OnDoubleTapListener 接口包括 onSingleTapConfirmed 单击和 onDoubleTap 双击等
public interface OnDoubleTapListener {
boolean onSingleTapConfirmed(@NonNull MotionEvent e);
boolean onDoubleTap(@NonNull MotionEvent e);
boolean onDoubleTapEvent(@NonNull MotionEvent e);
}
GestureDetector 和 ScaleGestureDetector 组合使用
- 双指缩放:主要通过 ScaleGestureDetector#onScale 配合 Matrix#postScale 实现
- 拖动滑动:主要通过 GestureDetector#onScroll 配合 Matrix#postTranslate 实现
override fun onTouchEvent(event: MotionEvent): Boolean {
scaleGestureDetector.onTouchEvent(event)
gestureDetector.onTouchEvent(event)
return true
}