One solution could be to override touch listener of viewPager to perform the required actions. You can see how it is working in this Video ViewPager Example.
What I'm doing here is storing the touchDown x coordinate and comparing it with the touchUp x coordinate to find if it is a movement from left to right or right to left. As x starts from left with 0 and increases towards the right. So when downX is smaller than upX, it is moving from left to right and vice versa.
For Right to Left, I'm moving the viewPager forward, and if it is at the last position, move to first. And similarly, for Left to Right, I'm moving the viewPager backward and if it is at the first position, move to last.
To override the TouchListener return 'true' in the last line.
viewPager.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
// store the x coordinate of touch down
actionDownX = event.getX();
break;
case MotionEvent.ACTION_UP:
int currentPosition = viewPager.getCurrentItem();
// the x coordinate of action up
float actionUpX = event.getX();
// Swiped from Left to Right -> Move Backward
if (actionDownX < actionUpX) {
// Move to Last item
if (currentPosition == 0) {
viewPager.setCurrentItem(size - 1, true);
}
// Move Backward
else {
int nextPosition = Math.max(0, currentPosition - 1);
viewPager.setCurrentItem(nextPosition, true);
}
}
// Swiped from Right to Left -> Move Forward
else if (actionDownX > actionUpX) {
// Move to First item
if (currentPosition == size - 1) {
viewPager.setCurrentItem(0, true);
}
// Move Forward
else {
int nextPosition = Math.min(size - 1, currentPosition + 1);
viewPager.setCurrentItem(nextPosition, true);
}
}
}
// This is important. To override the default behavior, return true
return true;
}
});
NOTE: Please note that this is not a complete solution but just an idea of how you can perform your required actions. It does not behave exactly like a viewPager (you can see that in the video) when swiping. So it is advised not to just copy-paste this code instead you should expand/improve the cod and add all the necessary checks.