您的位置:首页 > 移动开发 > Android开发

Android手势识别

2015-08-22 20:47 423 查看
GestureDetector —— 手势识别类

sdk源代码:

public class GestureDetector {

public interface OnGestureListener {

boolean onDown(MotionEvent e);

void onShowPress(MotionEvent e);

boolean onSingleTapUp(MotionEvent e);

boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY);

void onLongPress(MotionEvent e);

boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);
}

public interface OnDoubleTapListener {

boolean onSingleTapConfirmed(MotionEvent e);

boolean onDoubleTap(MotionEvent e);

boolean onDoubleTapEvent(MotionEvent e);
}


SimpleOnGestureListener

/**
* A convenience class to extend when you only want to listen for a subset
* of all the gestures. This implements all methods in the
* {@link OnGestureListener} and {@link OnDoubleTapListener} but does
* nothing and return {@code false} for all applicable methods.
*/

//touch down后又没有滑动(onScroll),又没有长按(onLongPress),然后Touchup时触发
public boolean onSingleTapUp(MotionEvent e) {
return false;
}

public void onLongPress(MotionEvent e) {
}

public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return false;
}

//Touch了滑动一点距离后,up时触发
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
return false;
}

//Touch了还没有滑动时触发
public void onShowPress(MotionEvent e) {
}

//Touch down时触发
public boolean onDown(MotionEvent e) {
return false;
}

//双击的第二下Touch down时触发
public boolean onDoubleTap(MotionEvent e) {
return false;
}

//双击的第二下Touch down和up都会触发,可用e.getAction()区分。
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}

//touch down后又没有滑动(onScroll),又没有长按(onLongPress),然后Touchup时触发
public boolean onSingleTapConfirmed(MotionEvent e) {
return false;
}
}


点击一下非常快的(不滑动)Touchup:

onDown->onSingleTapUp->onSingleTapConfirmed

点击一下稍微慢点的(不滑动)Touchup:

onDown->onShowPress->onSingleTapUp->onSingleTapConfirmed

部分示例代码:

GestureDetector detector new GestureDetector(this, new SimpleOnGestureListener() {
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2,
float velocityX, float velocityY) {
if(Math.abs(e2.getRawY() - e1.getRawY()) > 100) {
return true;
}

if(e2.getRawX() - e1.getRawX() > 200) {
//显示上一个页面,从左往右滑动
showLast();
return true;

}
if(e1.getRawX() - e2.getRawX() > 200) {
//显示下一个页面,从右往左滑动
showNext();
return true;
}
return super.onFling(e1, e2, velocityX, velocityY);

}

});


使用GestureDetector需要在View中重写onTouchEvent事件。

@Override
public boolean onTouchEvent(MotionEvent event) {
detector.onTouchEvent(event);
return super.onTouchEvent(event);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 手势