Android viewpager detect swipe beyond the bounds

后端 未结 4 821
自闭症患者
自闭症患者 2021-01-20 23:40

In my Android application, I am using a viewpager for image swiping. My requirement is, if a user swipes out of the first and last page, the activity should finish.

I ha

4条回答
  •  庸人自扰
    2021-01-21 00:20

    I changed M.A.Murali's code:

    public class CheckBoundsPager extends ViewPager {
        public CheckBoundsPager(Context context) {
            super(context);
        }
    
        public CheckBoundsPager(Context context, AttributeSet attrs) {
            super(context, attrs);
    
        }
    
        OnSwipeOutListener mListener;
    
        public void setOnSwipeOutListener(OnSwipeOutListener listener) {
            mListener = listener;
        }
    
        private float mStartDragX;
        private float mStartDragY;
        private float MIN_MOVE=50; //minimal movement in px - change it to you value
    
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            float x = ev.getX();
            float y = ev.getY();
            switch (ev.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    //here we set x and y on user start drag
                    mStartDragX = x;
                    mStartDragY = y;
    
                    }
                    break;
                case MotionEvent.ACTION_MOVE: {
    
                    //most important to check if x drag is more than y
                    float xDiff=Math.abs(mStartDragX-x);
                    float yDiff=Math.abs(mStartDragY-y);
    
                    //added condition if swipe y is less than x
                    if (mStartDragX < x-MIN_MOVE && xDiff>yDiff &&  getCurrentItem() == 0) {
                        mListener.onSwipeOutAtStart();
                    } else if (mStartDragX > x+MIN_MOVE
                            && xDiff>yDiff && getCurrentItem() == getAdapter().getCount() - 1) {
                        mListener.onSwipeOutAtEnd();
                    }
                    }
                    break;
            }
            return super.onInterceptTouchEvent(ev);
        }
    
        public interface OnSwipeOutListener {
    
            public void onSwipeOutAtStart();
    
            public void onSwipeOutAtEnd();
        }
    }
    

    This solutions checks if we drag left or right and our drag's movement is in the x-axis. Remember to change MIN_MOVE.

提交回复
热议问题