1

我创建了一个活动来监视屏幕向右和向左滑动。这是我已经实现的代码。

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 页面中没有文本视图,上面的代码可以正常工作。但是如果有一些文本视图并尝试在运行时设置文本值,那么我的应用程序强制关闭,并且错误显示为 java.lang.nullpointerexception。我在这里做错了什么??

4

1 回答 1

0

尝试将 Touch 事件委托给您的手势检测器。例如像这样:

@Override
public boolean onTouchEvent(MotionEvent event) {

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

}
于 2014-03-18T07:38:56.233 回答