I ran into this issue and need to know the direction of the swipe as it was happening in order to prevent swiping in a certain direction. Here is how I solved my problem, hopefully it is helpful to someone. I found all of the previous examples inefficient for what I needed.
If you subclass your ViewPager, you can respond to the onInterceptTouchEvent(MotionEvent event)
and onTouchEvent(MotionEvent event)
methods of the ViewPager
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
boolean wasSwipeToRight = this.wasSwipeToRightEvent(event));
// Do what you want here with left/right swipe
return super.onInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean wasSwipeToRight = this.wasSwipeToRightEvent(event));
// Do what you want here with left/right swipe
return super.onTouchEvent(event);
}
Here is the method which is called to determine the direction of the event.
// Stores the starting X position of the ACTION_DOWN event
float downX;
/**
* Checks the X position value of the event and compares it to
* previous MotionEvents. Returns a true/false value based on if the
* event was an swipe to the right or a swipe to the left.
*
* @param event - Motion Event triggered by the ViewPager
* @return - True if the swipe was from left to right. False otherwise
*/
private boolean wasSwipeToRightEvent(MotionEvent event){
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
downX = event.getX();
return false;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
return downX - event.getX() > 0;
default:
return false;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…