xip
xip

Reputation: 2662

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.

Upvotes: 1

Views: 1485

Answers (2)

xip
xip

Reputation: 2662

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).

Upvotes: 1

kris larson
kris larson

Reputation: 30985

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.

Upvotes: 1

Related Questions