I am using the ViewPager consisting of 6 pages to display some data. I want to be able to call a method when the user is at position 0 and tries to swipe to the right (backwards), or at position 5 and tries to swipe to the left (forward), even though no more pages exist for these directions. Is there any way I can listen for these scenarios?
Extend ViewPager and override onInterceptTouchEvent()
like this:
public class CustomViewPager extends ViewPager { float mStartDragX; OnSwipeOutListener mListener; public void setOnSwipeOutListener(OnSwipeOutListener listener) { mListener = listener; } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { float x = ev.getX(); switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: mStartDragX = x; break; case MotionEvent.ACTION_MOVE: if (mStartDragX < x && getCurrentItem() == 0) { mListener.onSwipeOutAtStart(); } else if (mStartDragX > x && getCurrentItem() == getAdapter().getCount() - 1) { mListener.onSwipeOutAtEnd(); } break; } return super.onInterceptTouchEvent(ev); } public interface OnSwipeOutListener { public void onSwipeOutAtStart(); public void onSwipeOutAtEnd(); } }
The answer from Flávio Faria doesn't work for me. The only event I get in onInterceptTouchEvent() is ACTION_DOWN event. So I override the onTouchEvent() method to get it work.
Here is the code. Note that I only have onSwipeOutAtEnd() in the listener. You can add your code to support swiping left on first vier.
public class CustomViewPager extends ViewPager { float mStartDragX; OnSwipeOutListener mListener; public void setOnSwipeOutListener(OnSwipeOutListener listener) { mListener = listener; } @Override public boolean onTouchEvent(MotionEvent ev){ if(getCurrentItem()==getAdapter().getCount()-1){ final int action = ev.getAction(); float x = ev.getX(); switch(action & MotionEventCompat.ACTION_MASK){ case MotionEvent.ACTION_DOWN: mStartDragX = x; break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: if (x<mStartDragX){ mListener.onSwipeOutAtEnd(); }else{ mStartDragX = 0; } break; } }else{ mStartDragX=0; } return super.onTouchEvent(ev); } public interface OnSwipeOutListener { public void onSwipeOutAtEnd(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With