Skip to content

Instantly share code, notes, and snippets.

@rajeefmk
Created May 4, 2017 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajeefmk/f8b171e7cd2fd2f1e2ff15ba4277e8ce to your computer and use it in GitHub Desktop.
Save rajeefmk/f8b171e7cd2fd2f1e2ff15ba4277e8ce to your computer and use it in GitHub Desktop.
View pager which gives call back when user has reached the first or last item and tried swiping left or right.
public class CustomViewPager extends ViewPager {
float mStartDragX;
OnSwipeOutListener mOnSwipeOutListener;
public CustomViewPager(Context context) {
super(context);
}
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setOnSwipeOutListener(OnSwipeOutListener listener) {
mOnSwipeOutListener = listener;
}
private void onSwipeOutAtStart() {
if (mOnSwipeOutListener != null) {
mOnSwipeOutListener.onSwipeOutAtStart();
}
}
private void onSwipeOutAtEnd() {
if (mOnSwipeOutListener != null) {
mOnSwipeOutListener.onSwipeOutAtEnd();
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction() & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mStartDragX = ev.getX();
break;
}
return super.onInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (getCurrentItem() == 0 || getCurrentItem() == getAdapter().getCount() - 1) {
final int action = ev.getAction();
float x = ev.getX();
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
if (getCurrentItem() == 0 && x > mStartDragX) {
onSwipeOutAtStart();
}
if (getCurrentItem() == getAdapter().getCount() - 1 && x < mStartDragX) {
onSwipeOutAtEnd();
}
break;
}
} else {
mStartDragX = 0;
}
return super.onTouchEvent(ev);
}
public interface OnSwipeOutListener {
void onSwipeOutAtStart();
void onSwipeOutAtEnd();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment