Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Viewpage stop swiping in a certain direction

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 greatly appreciated. To note that I need to get this to work for Android version 2.2, so I am using the compatibilty library for ViewPager.

Thanks in advance

like image 585
Barry Steyn Avatar asked Sep 01 '12 03:09

Barry Steyn


People also ask

How do you stop swipe in ViewPager?

To enable / disable the swiping, just overide two methods: onTouchEvent and onInterceptTouchEvent . Both will return "false" if the paging was disabled. You just need to call the setPagingEnabled method with false and users won't be able to swipe to paginate.

Is ViewPager deprecated?

This function is deprecated.

How do I turn off swipe on Android?

You can easily do that by creating a custom class inherits from viewPager and override two methods: “onTouchEvent()” and “onInterceptTouchEvent()” and return true or false to disable and enable the swiping on certain touch events i.e say swiping.

What is difference between ViewPager and ViewPager2?

ViewPager2 is an improved version of the ViewPager library that offers enhanced functionality and addresses common difficulties with using ViewPager . If your app already uses ViewPager , read this page to learn more about migrating to ViewPager2 .


1 Answers

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

    }



}
like image 104
Ali Alnoaimi Avatar answered Nov 11 '22 17:11

Ali Alnoaimi