android - How to lock ViewPager to allow only a single page swipe at once

By default, when you swipe over a ViewPager, you can swipe over as many pages as you can until your finger reaches the end of the screen. So, is it possible to force the ViewPager to only allow one page change no matter how much the user swipes?

This is what I mean by swiping over pager until your finger reaches the end of the screen: what I have

And this is what I mean by locking the ViewPager to allow only a single page swipe at a time: this is what I want to achieve

Thanks.

2 Answers

  1. Lee- Reply

    2019-11-14

    Okay, I think the answer is: Extend ViewPager and override onTouchEvent(MotionEvent ev).

    private Rect viewRect = new Rect();
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
    
        getHitRect(viewRect);
    
        if (viewRect.contains(
            Math.round(view.getX() + event.getX()),
            Math.round(view.getY() + event.getY()))) {
    
            // touch is inside, do normal behavior
            return super.onTouchEvent(event);
        } else {
            // touch is outside, consume the event & do nothing
            return true;
        }
    }
    

    Unfortunately, don't have time to really test it out right now, I'll update later.

  2. Leo- Reply

    2019-11-14

    In the end, I ended up doing it in the adapter. What I did was returning 2 in the getCount method, rearranging items after a selection, and specially handling cases when an item from the dataset was to be accessed using the current position (0 or 1).

Leave a Reply

Your email address will not be published. Required fields are marked *

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>