Android OnTouch swipe up/down direction change

2019-07-31 15:39发布

问题:

I'm trying to detect when an swipe direction was changed while the user still swipes on the screen.

I have something like this (very basic) for detecting the swipe direction:

@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
    int action = motionEvent.getActionMasked();

    switch (action) {
        case MotionEvent.ACTION_DOWN: {
            Log.d(TAG, "onTouch: DOWN _Y = " + motionEvent.getRawY());
            mLastTouchY = mPrevTouchY = motionEvent.getRawY();

            break;
        }
        case MotionEvent.ACTION_MOVE: {
            Log.d(TAG, "onTouch: MOVE _Y = " + motionEvent.getRawY());

            final float dy = motionEvent.getRawY();
            if (dy >= mLastTouchY) {
                /* Move down */

            } else {
                /* Move up */

            }

            break;
        }
        case MotionEvent.ACTION_CANCEL:
        case MotionEvent.ACTION_OUTSIDE:
        case MotionEvent.ACTION_UP: {
            Log.d(TAG, "onTouch: UP _Y = " + motionEvent.getRawY());

            // snap page

            break;
        }
    }

    return true;
}

What I need is to actually detect when the user changed the direction of the swipe. For example, the code above fails to detect some edge cases:

  1. Start from Y = 100,
  2. move down until 150,
  3. move up until 50,
  4. move down again until 90

This will be detected as an swipe up because initial Y is higher than the last Y

回答1:

Should you want to detect the direction change of the swipe there is a simple way:

    private GestureDetector gestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        findViewById(R.id.myView).setOnTouchListener(this);
        gestureDetector = new GestureDetector(this, this);
    }

And you implement OnTouch and GestureListeners like this:

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        if (distanceY > 0){
            // you are going up
        } else {
            // you are going down
        }
        return true;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return true;
    }
    //the rest of the methods you must implement...