@Override
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
return true;
}
return super.onTouchEvent(event);
}
private void onLeftSwipe() {
// Do something
System.out.println("left swipe");
}
private void onRightSwipe() {
// Do something
System.out.println("right swipe");
}
// Private class for gestures
private class SwipeGestureDetector extends SimpleOnGestureListener {
// Swipe properties, you can change it to make the swipe
// longer or shorter and speed
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_MAX_OFF_PATH = 200;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
try {
float diffAbs = Math.abs(e1.getY() - e2.getY());
float diff = e1.getX() - e2.getX();
if (diffAbs > SWIPE_MAX_OFF_PATH)
return false;
// Left swipe
if (diff > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
SlidingMenuActivity.this.onLeftSwipe();
// Right swipe
} else if (-diff > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
SlidingMenuActivity.this.onRightSwipe();
}
} catch (Exception e) {
Log.e("YourActivity", "Error on gestures");
}
return false;
}
}
我有,但它没有工作,我无法检测向左或向右滑动 . 我已经在我的 class 和 onCreate
活动方法中声明了 private GestureDetector gestureDetector;
.
gestureDetector = new GestureDetector(new SwipeGestureDetector());
但它不起作用,没有印刷?我正在使用kitkat nexus 4 .
2 回答
您必须将侦听器应用于您希望处理的视图,例如: