ViewPager detect when user is trying to swipe out of bounds

后端 未结 5 1054
生来不讨喜
生来不讨喜 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:33

    Thanks a lot to @Flavio, although i had to do some changes to his code because the callbacks methods were firing twice, also I added code to check if there was any registered listener, to avoid app crashing when there is no listener registered. This is the code I used to make it work, with both onSwipeOutAtStart and onSwipeOutAtEnd:

    public class CustomViewPager extends android.support.v4.view.ViewPager {
    
        float mStartDragX;
        OnSwipeOutListener mOnSwipeOutListener;
    
        public CustomViewPager(Context context) {
            super(context);
        }
    
        public CustomViewPager(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public void setOnSwipeOutListener(OnSwipeOutListener listener) {
            mOnSwipeOutListener = listener;
        }
    
        private void onSwipeOutAtStart() {
            if (mOnSwipeOutListener!=null) {
                mOnSwipeOutListener.onSwipeOutAtStart();
            }
        }
    
        private void onSwipeOutAtEnd() {
            if (mOnSwipeOutListener!=null) {
                mOnSwipeOutListener.onSwipeOutAtEnd();
            }
        }
    
        @Override
        public boolean onInterceptTouchEvent(MotionEvent ev) {
            switch(ev.getAction() & MotionEventCompat.ACTION_MASK){
                case MotionEvent.ACTION_DOWN:
                    mStartDragX = ev.getX();
                    break;
            }
            return super.onInterceptTouchEvent(ev);
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent ev){
    
            if(getCurrentItem()==0 || getCurrentItem()==getAdapter().getCount()-1){
                final int action = ev.getAction();
                float x = ev.getX();
                switch(action & MotionEventCompat.ACTION_MASK){
                    case MotionEvent.ACTION_MOVE:
                        break;
                    case MotionEvent.ACTION_UP:
                        if (getCurrentItem()==0 && x>mStartDragX) {
                            onSwipeOutAtStart();
                        }
                        if (getCurrentItem()==getAdapter().getCount()-1 && x

提交回复
热议问题