Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

android - Swipe Direction in ViewPager

I have an Android app that uses ViewPager and FragmentStatePagerAdapter. I however need to add a new feature in which I have to know the swipe direction to move from one fragment view to another, left or right. (i.e, when I swipe left, I would do one thing, and when I swipe right I would do something else).

Please note, I do not need the events to happen AFTER the swipe is over. I have to do those events as the swipe occurs. I thought of using setOnPageChangeListener() but it does not tell me swipe direction. Can you advise me please on how to figure out swipe direction?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...