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
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.
This function is deprecated.
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.
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 .
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With