前言
在Android中要想检测手势就需要使用GestureDetector类 是在android.view包中,详细资料可以查阅官方文档
使用步骤如下
1.创建一个GestureDetector实例,创建时需要两个参数,分别是Context和OnGestureListener。
OnGestureListener是当手势操作被检测到时的回调函数,这个接口有你所需要的常用的手势操作:点击,双击,滑动以及速动(fling)。
代码如下:
//声明一个引用
private GestureDetector detector;
private float mScale = 1.0f;
public TView(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
for (int i = 0; i < MAX; i++) {
pointers[i] = new Pointer();
}
paint = new Paint();
paint.setAntiAlias(true);
paint.setTextSize(fontSize);
//创建GestureDetector实例
detector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
private boolean normal = true;
//要检测双击 所以这里重写onDoubleTap方法
@Override
public boolean onDoubleTap(MotionEvent e) {
mScale = normal ? 3f : 1f;
paint.setTextSize(mScale * fontSize);
normal = ! normal;
invalidate();
return true;
}
});
}
2.在视图的onTouchEvent方法中调到GestureDetector的onTouchEvent方法接受触摸事件,
这样才能判断触摸事件是否是双击,进而调用回调方法。
代码如下:
@Override
public boolean onTouchEvent(MotionEvent event) {
detector.onTouchEvent(event);
}
到此就介绍完毕了。
完整demo 下载地址:http://download.csdn.net/detail/hu285279904/9754571