检测滑动和点按手势

时间:2015-06-10 00:58:06

标签: android swipe gesture motionevent ontouch

如何在onTouch方法中检测滑动和点按?我希望当我轻扫时执行两个动作中的一个,而当我轻击时则执行其他动作。需要知道如何区分点按和滑动之间的区别。

这是我的代码:

@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_MOVE) {
    mGestureDetector.onTouchEvent(event);
}
switch(event.getAction()) {
    case MotionEvent.ACTION_DOWN:
        x1 = event.getX();
        y1 = event.getY();
        break;
    case MotionEvent.ACTION_UP:
        x2 = event.getX();
        y2 = event.getY();

        float deltaX = x2 - x1;
        float deltaY = y2 - y1;

        if (Math.abs(deltaX) > MIN_DISTANCE) {
            mGestureDetector.onTouchEvent(event);
        }else if (Math.abs(deltaX) < MIN_DISTANCE) {
            mGestureDetector.onTouchEvent(event);
        }else if (Math.abs(deltaY) > MIN_DISTANCE) {
            mGestureDetector.onTouchEvent(event);
        }else if (Math.abs(deltaY) < MIN_DISTANCE) {
            mGestureDetector.onTouchEvent(event);
        }
        break;
}
return true;

}

1 个答案:

答案 0 :(得分:0)

这是你可以做的,在this link上找到 在onCreate of activity中,添加此内容。

final GestureDetector gestureDetector = new GestureDetector(new GestureListener());
calendar.setOnTouchListener(new OnTouchListener() {
   @Override
   public boolean onTouch(final View view, final MotionEvent event) {
   if (gestureDetector.onTouchEvent(event)) {
      return false;
    }
    return true;
  }
});

这是GestureDetector Class

class GestureListener extends SimpleOnGestureListener {
    @Override
    public boolean onSingleTapConfirmed(MotionEvent event) {
    // Trigger the touch event on the calendar
      calendar.onTouchEvent(event);
      return super.onSingleTapUp(event);
    }

@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    ViewConfiguration viewConfiguration = ViewConfiguration.get(EventsActivity.this);
    int minSwipeDistance = viewConfiguration.getScaledPagingTouchSlop();
    int minSwipeVelocity = viewConfiguration.getScaledMinimumFlingVelocity();
    int maxSwipeOffPath = viewConfiguration.getScaledTouchSlop();
    if (Math.abs(e1.getY() - e2.getY()) > maxSwipeOffPath) {
        return false;
    }

   if (Math.abs(velocityX) > minSwipeVelocity) {
   // Right to left swipe
      if (e1.getX() - e2.getX() > minSwipeDistance) {
      calendar.nextMonth();
   }

   // Left to right
   else if (e2.getX() - e1.getX() > minSwipeDistance) {
        calendar.previousMonth();
   }

    // Call some app-related functions to update the display
    displayDate(calendar.getMonth(), calendar.getYear());
  }
  return false;
 }
}