Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ViewPager detect when user is trying to swipe out of bounds

Tags:

android

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?

like image 719
Nicklas Avatar asked Nov 12 '12 15:11

Nicklas


2 Answers

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();     }  } 
like image 131
Flávio Faria Avatar answered Sep 22 '22 04:09

Flávio Faria


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(); } 
like image 30
tjlian616 Avatar answered Sep 19 '22 04:09

tjlian616