Viewpage stop swiping in a certain direction

后端 未结 1 1745
野性不改
野性不改 2020-12-10 18:19

How can I stop viewpager from scrolling in one direction only. For example, allow swipes only to the right, but not to the left. I am absolutely stuck, any help would be gre

相关标签:
1条回答
  • 2020-12-10 18:46

    You will have to make your own ViewPager that extends the original ViewPager and override the onTouchEvent method

    public class CustomViewPager extends ViewPager {
    
        float lastX = 0;
    
        boolean lockScroll = false;
    
        public CustomViewPager(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public CustomViewPager(Context context) {
            super(context);
        }
    
        @Override
        public boolean onTouchEvent(MotionEvent ev) {
    
            switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX = ev.getX();
                lockScroll = false;
                return super.onTouchEvent(ev);
            case MotionEvent.ACTION_MOVE:
    
                if (lastX > ev.getX()) {
                    lockScroll = false;
                } else {
                    lockScroll = true;
                }
    
                lastX = ev.getX();
                break;
            }
    
            lastX = ev.getX();
    
            if(lockScroll) {
                return false;
            } else {
                return super.onTouchEvent(ev);
            }
    
        }
    
    
    
    }
    
    0 讨论(0)
提交回复
热议问题