Search code examples
androidandroid-activityswipe

Swipe run by Activity Do OnBackPress


It can capture the left swipe action to right and run a command by the activity? In the case of an activity would identify the swipe (left to right) and run the command onBackPress(); I need to identify swipe at the view and I hold other components in the activity and do not know how to identify whether the action is the activity or component.


Solution

  • With the following code it can have a listener that responds to the back gesture. It is possible with a View setOnTouchListener have this ability to identify the movement and perform the action.

    Execution

            android.view.GestureDetector gestureDetector = new android.view.GestureDetector(this, new GestureDetector(Activity.this));
            View.OnTouchListener gestureListener = new View.OnTouchListener() {
                public boolean onTouch(View v, MotionEvent event) {
                    return gestureDetector.onTouchEvent(event);
                }
            };
    
            view.setOnTouchListener(gestureListener);
    

    GestureDetector.java

    public class GestureDetector extends android.view.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 final Activity activity;
    
        public GestureDetector(Activity activity){
            this.activity = activity;
        }
    
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    activity.onBackPressed();
                }
            } catch (Exception e) {
                // nothing
            }
            return false;
        }
    
        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }
    }