Android: How to handle right to left swipe gestures

前端 未结 22 1236
日久生厌
日久生厌 2020-11-21 06:18

I want my app to recognize when a user swipes from right to left on the phone screen.

How to do this?

22条回答
  •  忘掉有多难
    2020-11-21 07:13

    @Mirek Rusin answeir is very good. But, there is small bug, and fix is requried -

    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                boolean result = false;
                try {
                    float diffY = e2.getY() - e1.getY();
                    float diffX = e2.getX() - e1.getX();
                    if (Math.abs(diffX) > Math.abs(diffY)) {
                        if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                            if (diffX > 0) {
                                if (getOnSwipeListener() != null) {
                                    getOnSwipeListener().onSwipeRight();
                                }
                            } else {
                                if (getOnSwipeListener() != null) {
                                    getOnSwipeListener().onSwipeLeft();
                                }
                            }
                            result = true;
                        }
                    }
                    else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffY > 0) {
                            if (getOnSwipeListener() != null) {
                                getOnSwipeListener().onSwipeBottom();
                            }
                        } else {
                            if (getOnSwipeListener() != null) {
                                getOnSwipeListener().onSwipeTop();
                            }
                        }
                        result = true;
                    }
    

    What the difference? We set result = true, only if we have checked that all requrinments (both SWIPE_THRESHOLD and SWIPE_VELOCITY_THRESHOLD are Ok ). This is important if we discard swipe if some of requrinments are not achieved, and we have to do smth in onTouchEvent method of OnSwipeTouchListener!

提交回复
热议问题