Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
443 views
in Technique[技术] by (71.8m points)

android - Swipe gesture in all direction(Left,Right, Up, Down )

I need to detect swipe direction in my code. I can detect the direction but it comes like if I swipe right top right or left-top like that coming. same for the left, my requirement is without lifting finger if i swipe left it should come only left ,likewise all the direction. Can anyone help me out. Thanks in advance!

@Override public boolean onTouchEvent(MotionEvent touchevent) {

    switch (touchevent.getAction()) {
        // when the user first touches the screen we get x and y coordinate
        case MotionEvent.ACTION_DOWN: {
            x1 = touchevent.getX();
            y1 = touchevent.getY();
            break;
        }

        case MotionEvent.ACTION_MOVE: {


            x2 = touchevent.getX();
            y2 = touchevent.getY();


            float deltaX = x2 - x1;


            if (Math.abs(deltaX) > MIN_DISTANCE) {
                // Left to Right swipe action
                if (x2 > x1) {;
                    Log.e("RTL", "Right to Left Swap Performed");
                }

                else {
                    Log.e("LTR", "Left to Right Swap Performed");
                }

            } else {

                if (y2 > y1) {

                    Log.e("UTD", "UP to Down Swap Performed");
                }

                // Right to left swipe action
                else {
                    Log.e("DTU", "Down to UP Swap Performed");
                }
            }
        }
    }
    return false;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should calculate angle then decide with that. If the vector is bigger than your min distance value, then you can check for angle.

float angle = (float) Math.toDegrees(Math.atan2(y2 - y1, x2 - x1));
if(angle > 45 && angle <= 135) return UP;
else if(angle > 135 && angle <= 225) return LEFT;
else if(angle > 225 && angle <= 315) return DOWN;
else return RIGHT;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...