Created
May 4, 2017 12:08
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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