1

我尝试检测android中的手势并且它一直崩溃,我在创建构造函数时遇到问题,我在使用类方面并不那么先进

这是 GestureDetector 类,包含 OnGestureListener 的所有必要方法:

public class GestureDetectorClass implements OnGestureListener {

      @Override
      public boolean onDown(MotionEvent arg0) {
          Log.d("Gesture", "onDown");
       return false;
      }

      @Override
      public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,  float velocityY) {
          Log.d("Gesture", "onFling");
      return true;
      }

      @Override
      public void onLongPress(MotionEvent e) {
          Log.d("Gesture", "onLongPress");
      }

      @Override
      public boolean onScroll(MotionEvent e1, MotionEvent e2,
        float distanceX, float distanceY) {
          Log.d("Gesture", "onScroll");
       return false;
      }

      @Override
      public void onShowPress(MotionEvent e) { 
          Log.d("Gesture", "onShowPress");
      }

      @Override
      public boolean onSingleTapUp(MotionEvent e) {
          Log.d("Gesture", "onSingleTapUp");
          return false;
      }

}

主要是我现在尝试调用尝试以下代码的类/方法:

public class MainActivity extends Activity  {


    GestureDetectorClass myGestureClass = new GestureDetectorClass();
    GestureDetector myDector = new GestureDetector(this, myGestureClass);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    public boolean onTouch(MotionEvent e) {
        return myDector.onTouchEvent(e);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

在日志中我发现了这个错误:

    11-13 11:15:02.615: E/AndroidRuntime(1127): Caused by: java.lang.NullPointerException
11-13 11:15:02.615: E/AndroidRuntime(1127):     at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:125)
4

1 回答 1

1

建议我在设置内容视图后创建 myDetector 的新对象,因为您thisnew GestureDetector(this, myGestureClass);此使用可能是 nullpointerexception 的原因

GestureDetector myDector;
GestureDetectorClass myGestureClass;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    myGestureClass = new GestureDetectorClass();
    myDector = new GestureDetector(this, myGestureClass);

}

这是示例 http://android-er.blogspot.com/2012/07/implement-gesturedetectorongestureliste.html

于 2013-11-13T11:24:34.820 回答