如何从刷卡在一个方向上禁用ViewPagerViewPager

2023-09-13 23:49:34 作者:灵魂检察官

我想允许在 ViewPager 只能由右至左用户刷卡。所以一旦他通过一个页面,他不能回来吧。如何才能做到这一点?

I want to allow the user swipe in a ViewPager only from right to left. So once he passed a page he can't come back to it. How can this be done?

我试过this解决办法:

I tried this solution:

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);
    }
}
}

但它仍然让我不好刷卡另一个方向。

But it still allows me to poorly swipe in the other direction.

推荐答案

尝试添加(同样的逻辑像的onTouchEvent)

Try to add (the same logic like in onTouchEvent )

@Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
    // allow/ not allow swiping to switch between pages
    return !lockScroll ;
}