Search code examples
androidandroid-viewpagergesture

Make ViewPager snap with shorter drag


Is there any way to make the support package ViewPager snap to the next page with a shorter drag? The default behaviour seems to be that even if I drag almost 75% the page still snaps back to the previous page when I let go. I'd like to make the snap threshold shorter and make the ViewPager snap to the next page instead.

Note that this applied to drag gesture. A fling gesture requires much shorter gesture already.


Solution

  • You can do this ad-hoc, without worrying too much about the internals of ViewPager as long as you want to increase the target zone:

    private class MyPageChangeListener implements OnPageChangeListener {
        private float mLastPositionOffset = 0f;
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            if(positionOffset < mLastPositionOffset && positionOffset < 0.9) {
                mViewPager.setCurrentItem(position);
            } else if(positionOffset > mLastPositionOffset && positionOffset > 0.1) {
                mViewPager.setCurrentItem(position+1);
            }
            mLastPositionOffset = positionOffset;
        }
    }