Skip to content

Instantly share code, notes, and snippets.

@Alezhka
Created July 2, 2018 10:29
Show Gist options
  • Save Alezhka/b4ea4bf4b7d2612e1234c7e8a3d443dc to your computer and use it in GitHub Desktop.
Save Alezhka/b4ea4bf4b7d2612e1234c7e8a3d443dc to your computer and use it in GitHub Desktop.
Swipe control ViewPager
public class SwipeViewPager extends ViewPager {
public enum SwipeDirection {
all, left, right, none
}
private float initialXValue;
private SwipeDirection direction;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.direction = SwipeDirection.all;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
performClick();
return this.IsSwipeAllowed(event) && super.onTouchEvent(event);
}
@Override
public boolean performClick() {
return super.performClick();
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
return this.IsSwipeAllowed(event) && super.onInterceptTouchEvent(event);
}
private boolean IsSwipeAllowed(MotionEvent event) {
if (this.direction == SwipeDirection.all) return true;
if (direction == SwipeDirection.none)//disable any swipe
return false;
if (event.getAction() == MotionEvent.ACTION_DOWN) {
initialXValue = event.getX();
return true;
}
if (event.getAction() == MotionEvent.ACTION_MOVE) {
try {
float diffX = event.getX() - initialXValue;
if (diffX > 0 && direction == SwipeDirection.right) {
// swipe from left to right detected
return false;
} else if (diffX < 0 && direction == SwipeDirection.left) {
// swipe from right to left detected
return false;
}
} catch (Exception exception) {
exception.printStackTrace();
}
}
return true;
}
public void setAllowedSwipeDirection(SwipeDirection direction) {
this.direction = direction;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment