手势探测器不在android中工作

时间:2014-03-18 07:23:54

标签: android gesture swipe-gesture gesturedetector onfling

我创建了一个用于监视屏幕向右和向左滑动的活动。这是我实施的代码。

public class YourActivity extends Activity {
private GestureDetector gestureDetector;

@Override
public void onCreate(Bundle savedInstanceState) {
// ...

gestureDetector = new GestureDetector(
                  new SwipeGestureDetector());
}

/* ... */

@Override
public boolean onTouchEvent(MotionEvent event) {
if (gestureDetector.onTouchEvent(event)) {
  return true;
}
return super.onTouchEvent(event);
}

private void onLeftSwipe() {

// Here I have used a toast to check whether it's detectecting my swipe to left.
// But it is not working.
}

private void onRightSwipe() {
// Here I have used a toast to check whether it's detectecting my swipe to right.
// But it is not working.
}

 // 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) {
       YourActivity.this.onLeftSwipe();

    // Right swipe
    } else if (-diff > SWIPE_MIN_DISTANCE
    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
      YourActivity.this.onRightSwipe();
    }
  } catch (Exception e) {
    Log.e("YourActivity", "Error on gestures");
  }
  return false;
}
}
}

当我运行此代码时,当我向左或甚至向右滑动时没有任何事情发生。 onRightSwipe() onLeftSwipe 上的祝酒词根本不起作用。如果我的代码中的任何地方出错,有人可以纠正我。在此先感谢您的帮助..

编辑::如果我的活动布局xml页面中没有文本视图,则上述代码可以正常工作。但是如果有一些textviews并尝试在运行时设置文本值,那么我的应用程序强制关闭,错误显示为java.lang.nullpointerexception。我在这做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试将Touch事件委派给您的手势检测器。例如:

@Override
public boolean onTouchEvent(MotionEvent event) {

    // delegate the touch event to your gestureDetector 
    gestureDetector.onTouchEvent(event);
    return false;

}