Android SimpleOnPageChangeListener - Determine swipe direction
Asked Answered
C

2

7

I have a class that extends SimpleOnPageChangeListener and in my onPageScrollStateChanged method I want to be able to determine whether the user has swiped forwards or backwards through the ViewPager. I.e. Whether they have swiped left-to-right or right-to-left.

I've done a lot of googling on this but I can't find anything about it. I was expecting the onPageScrollStateChanged method would provide a parameter stating which direction the swipe was but it doesn't.

    @Override
    public void onPageScrollStateChanged(int state) {

        // Determine whether the user is swiping forwards or backwards through the ViewPager
    }

Does anyone have any ideas?

Cheers Mike

Caning answered 8/8, 2012 at 8:42 Comment(0)
R
3

Use the ViewPager.SimpleOnPageChangeListener and keep a instance var with the current tab pos, that way you can work out which way it's been swiped.

private final ViewPager.SimpleOnPageChangeListener mPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {

        @Override
        public void onPageSelected(final int position) {
            onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
            mCurrentTabPosition = position;
        }
    };

 protected void onTabChanged(final PagerAdapter adapter, final int oldPosition, final int newPosition) {
        //Calc if swipe was left to right, or right to left
         if (oldPosition>newPosition){
           // left to right
         }
         else{
           //right to left 
         }

    }
Rank answered 8/8, 2012 at 8:54 Comment(1)
Hi Scottyab.Thanks for the quick reply. I've implemented this solution but it only fires after the page has already changed. I want to perform some validation to stop the user moving forward but to allow them moving backwards. With this solution the page has already changed.Caning
G
0
        int prevPage;

        @Override
        public void onPageSelected(int position) {
            // went back a page
            if (position-1 == prevPage) {
                Log.i("Swipped", "Swipped Left");
            }
            // went up a page
            if (position+1 == prevPage) {
                Log.i("Swipped", "Swipped Right");
            }
            prevPage = position;


        }
Grimbal answered 9/3, 2015 at 0:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.