Android: How to handle right to left swipe gestures

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

    Expanding on Mirek's answer, for the case when you want to use the swipe gestures inside a scroll view. By default the touch listener for the scroll view get disabled and therefore scroll action does not happen. In order to fix this you need to override the dispatchTouchEvent method of the Activity and return the inherited version of this method after you're done with your own listener.

    In order to do a few modifications to Mirek's code: I add a getter for the gestureDetector in the OnSwipeTouchListener.

    public GestureDetector getGestureDetector(){
        return  gestureDetector;
    }
    

    Declare the OnSwipeTouchListener inside the Activity as a class-wide field.

    OnSwipeTouchListener onSwipeTouchListener;
    

    Modify the usage code accordingly:

    onSwipeTouchListener = new OnSwipeTouchListener(MyActivity.this) {
        public void onSwipeTop() {
            Toast.makeText(MyActivity.this, "top", Toast.LENGTH_SHORT).show();
        }
        public void onSwipeRight() {
            Toast.makeText(MyActivity.this, "right", Toast.LENGTH_SHORT).show();
        }
        public void onSwipeLeft() {
            Toast.makeText(MyActivity.this, "left", Toast.LENGTH_SHORT).show();
        }
        public void onSwipeBottom() {
            Toast.makeText(MyActivity.this, "bottom", Toast.LENGTH_SHORT).show();
        }
    });
    
    imageView.setOnTouchListener(onSwipeTouchListener);
    

    And override the dispatchTouchEvent method inside Activity:

    @Override
        public boolean dispatchTouchEvent(MotionEvent ev){
            swipeListener.getGestureDetector().onTouchEvent(ev); 
                return super.dispatchTouchEvent(ev);   
        }
    

    Now both scroll and swipe actions should work.

提交回复
热议问题