I’m working on an app which uses many pages to swipe through, however at some pages I would like to be able to prevent scrolling to the next page until they’ve selected something.
At the moment I’ve extended ViewPager:
/* (non-Javadoc)
* @see android.support.v4.view.ViewPager#onInterceptTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.canGoLeft || this.canGoRight) {
return super.onInterceptTouchEvent(event);
}
return false;
}
/* (non-Javadoc)
* @see android.support.v4.view.ViewPager#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean lockScroll = false;
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = ev.getX();
lockScroll = false;
return super.onTouchEvent(ev);
case MotionEvent.ACTION_MOVE:
if (canGoLeft && lastX < ev.getX()) {
lockScroll = false;
} else if (canGoRight && lastX > ev.getX()) {
lockScroll = false;
} else {
lockScroll = true;
}
lastX = ev.getX();
break;
}
lastX = ev.getX();
if (lockScroll) {
//make callback to prevent movement
if (mOnPreventCallback != null) {
mOnPreventCallback.onPreventMovement();
}
return false;
} else {
return super.onTouchEvent(ev);
}
}
Note: I’ve tried to implement prevent swiping to previous however you can still swipe to the previous page but you need to swipe from the uttermost left side and swipe right a bit. It’s temperamental but it does not prevent swiping completely.
Three things I want to do here:
- Prevent scrolling to next screen until they have selected an item or something
- Prevent scrolling to previous screen throughout (partially implemented)
- Give feedback to the user to show that scrolling is disabled, like the way Android shows the top and bottom screens with a gradient.
When I faced a similar problem, I made my own Listener with a gestureDetector and made it not respond to swiping at all, you can easily adjust it to not respond to swiping to the right only under some condition. This should answer your numbers 1 and 2.
This is the listener:
and this is an example of use :
There might be a simpler and more elegant solution, but this worked well for me.