LoginSignup
2
3

More than 5 years have passed since last update.

[Android] ジェスチャー取得のコードをスッキリ書く

Last updated at Posted at 2017-06-28

ジェスチャーを取得するコードは、一旦GestureDetectorのインスタンスを作成して各イベントを全てOverrideし、さらにTouchイベントを定義してイベントを渡す、といった感じで長くなりがちです。Activiy/Fragment等にこれらのコードを書くと長くなり可読性が落ちてしまいます。

解決策として次のようなUtilクラスを用意しておくと、ジェスチャーを取得するコードを短く書くことができます。

GestureUtils.java
public abstract class GestureUtils {

    public static void setListener(Context context, View view, GestureListenerAdapter adapter) {
        final GestureDetector gestureDetector = new GestureDetector(context, adapter);
        view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent e) {
                return gestureDetector.onTouchEvent(e);
            }
        });
    }

    public static abstract class GestureListenerAdapter implements GestureDetector.OnGestureListener {
        @Override
        public boolean onDown(MotionEvent e) {
            return false;
        }

        @Override
        public void onShowPress(MotionEvent e) {

        }

        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            return false;
        }

        @Override
        public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
            return false;
        }

        @Override
        public void onLongPress(MotionEvent e) {

        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            return false;
        }
    }
}

例として、あるView(コード例中のsomeView)に対するonSingleTapUpイベントを取得するコードは次のようになります。

GestureUtils.setListener(someContext, someView, new GestureUtils.GestureListenerAdapter() {
    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        // .. do someThing
        return false;
    }
});

スッキリ!

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3