Android OnTouch swipe up/down direction change

这一生的挚爱 提交于 2019-12-11 06:34:38

问题


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...


来源:https://stackoverflow.com/questions/38570917/android-ontouch-swipe-up-down-direction-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!