1

イメージビューにフリング ジェスチャを追加しようとしています。このコードを使用しています

public class MyActivity extends Activity {
private void onCreate() {
    final GestureDetector gdt = new GestureDetector(new GestureListener());
    final ImageView imageView  = (ImageView) findViewById(R.id.image_view);
    imageView.setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(final View view, final MotionEvent event) {
            gdt.onTouchEvent(event);
            return true;
        }
    });
}               

private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;

private class GestureListener extends SimpleOnGestureListener {
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            return false; // Right to left
        }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            return false; // Left to right
        }

        if(e1.getY() - e2.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
            return false; // Bottom to top
        }  else if (e2.getY() - e1.getY() > SWIPE_MIN_DISTANCE && Math.abs(velocityY) > SWIPE_THRESHOLD_VELOCITY) {
            return false; // Top to bottom
        }
        return false;
    }
}
}

しかし、それはうまくいきません。ログには nullpointerexception と表示され、この行を参照しています imageView.setOnTouchListener(new OnTouchListener() {

私の間違いはどこですか?何か不足していますか?

4

1 に答える 1

1

実際にイメージビューを取得する前に U が setContentView() を設定していないため、imageView は null を返します

setContentView(R.layout.yourlayout)imageview を取得する前に onCreate で

于 2013-02-16T14:30:32.377 に答える