Android: How to handle right to left swipe gestures

前端 未结 22 1200
日久生厌
日久生厌 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:24

    This issue still exists. An OnTouchListener with an OnSwipeTouchListener solves it in a simple way:

    myView.setOnTouchListener(
        new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                if(!swipe.onTouch(v, event)) {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        // your code here
    
                        return true;
                    } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        // your code here
    
                        return true;
                    }
                }
                return false;
            }
    
        }
    );
    

    where swipe refers to a class which records whether swipe methods have been invoked, then forwards events to the delegate OnSwipeTouchListener.

    private class DirtyOnSwipeTouchListener extends OnSwipeTouchListener {
        private boolean dirty = false;
        private OnSwipeTouchListener delegate;
    
        public DirtyOnSwipeTouchListener(Context ctx, OnSwipeTouchListener delegate) {
            super(ctx);
    
            this.delegate = delegate;
        }
    
        private void reset() {
            dirty = false;
        }
    
        public void onSwipeTop() {
            dirty = true;
            delegate.onSwipeTop();
        }
    
        public void onSwipeRight() {
            dirty = true;
            delegate.onSwipeRight();
        }
    
        public void onSwipeLeft() {
            dirty = true;
            delegate.onSwipeLeft();
        }
    
        public void onSwipeBottom() {
            dirty = true;
            delegate.onSwipeBottom();
        }
    
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            try {
                super.onTouch(v, event);
    
                return dirty;
            } finally {
                dirty = false;
            }
    
        }
    };
    

提交回复
热议问题