ViewPager detect when user is trying to swipe out of bounds

后端 未结 5 1044
生来不讨喜
生来不讨喜 2020-11-27 04:05

I am using the ViewPager consisting of 6 pages to display some data. I want to be able to call a method when the user is at position 0 and tries to swipe to the right (backw

5条回答
  •  一整个雨季
    2020-11-27 04:29

    Extend ViewPager and override onInterceptTouchEvent() like this:

    public class CustomViewPager extends ViewPager {
    
        float mStartDragX;
        OnSwipeOutListener mListener;
    
    
        public void setOnSwipeOutListener(OnSwipeOutListener listener) {
            mListener = listener;
        }
    
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            float x = ev.getX();
            switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mStartDragX = x;
                break;
            case MotionEvent.ACTION_MOVE:
                if (mStartDragX < x && getCurrentItem() == 0) {
                    mListener.onSwipeOutAtStart();
                } else if (mStartDragX > x && getCurrentItem() == getAdapter().getCount() - 1) {
                    mListener.onSwipeOutAtEnd();
                }
                break;
            }
            return super.onInterceptTouchEvent(ev);
        }
    
        public interface OnSwipeOutListener {
            public void onSwipeOutAtStart();
            public void onSwipeOutAtEnd();
        }
    
    }
    

提交回复
热议问题