Implementing Swipe action on ViewFlipper with multiple GridViews

前端 未结 3 578
Happy的楠姐
Happy的楠姐 2021-02-06 19:49

I have the following code to listen to Swipe action to navigate between GridViews in my ViewFlipper. However, it detects the Swipe inconsistently. I added the Gesture Listener t

3条回答
  •  半阙折子戏
    2021-02-06 20:10

    I keep seeing the same swipe gesture detection code all over StackOverflow, so I have attempted to clean it up a bit. This is a generic listener which can fire events for right or left swipes (easily extended to other

    public class SwipeListener extends GestureDetector.SimpleOnGestureListener {
    
        private static final int SWIPE_MIN_DISTANCE = 120;
        private static final int SWIPE_MAX_OFF_PATH = 250;
        private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    
        private SwipeHandler handler;
    
        public SwipeHandler getHandler() {
            return handler;
        }
    
        public void setHandler(SwipeHandler handler) {
            this.handler = handler;
        }
    
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    
            if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                return false;
    
            // left
            if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
    
                if (handler != null) {
                    handler.onLeft();
    
                    return true;
                }
    
            // right
            } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                    && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
    
                if (handler != null) {
                    handler.onRight();
    
                    return true;
                }
            }
    
            return super.onFling(e1, e2, velocityX, velocityY);
        }
    
        public static abstract class SwipeHandler{
            public void onLeft() {}
            public void onRight() {}
        }
    }
    

    And then to use this anywhere, just create an instance, setup your swipe event handlers, and attach it:

        SwipeListener swipeListener = new SwipeListener();
        swipeListener.setHandler(new SwipeListener.SwipeHandler() {
            @Override
            public void onRight() {
                doSomething();
            }
        });
    
        someView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return gestureDetector.onTouchEvent(event);
            }
        });
    

提交回复
热议问题