How to make a ViewPager loop?

后端 未结 5 392
独厮守ぢ
独厮守ぢ 2020-12-02 19:34

I have a ViewPager with some views. I\'d like to go to the first one after right swiping on the last one.

I tried

@Override
public Fragment getItem(i         


        
5条回答
  •  时光说笑
    2020-12-02 20:23

    My solution is based on benkc, but first and last page scroll animation are disabled, and when pages "scrolled" to real page, scroll animation is enable again, this scheme can solve the first drawback.

    but my ViewPager.setCurrentItem(position, false) result is still have scroll animation, so i implements animation which is too fast to seen.

    the fast scrolling animation like this, don't mind the comment, just my code didn't use these method:

    public class FixedSpeedScroller extends Scroller {
        private int mDuration = 0;
    
        public FixedSpeedScroller(Context context) {
            super(context);
        }
    
        @Override
        public void startScroll(int startX, int startY, int dx, int dy, int duration) {
            super.startScroll(startX, startY, dx, dy, mDuration);
        }
    
        @Override
        public void startScroll(int startX, int startY, int dx, int dy) {
            super.startScroll(startX, startY, dx, dy, mDuration);
        }
    }
    

    and use this method to viewpager's activity

    private Scroller scroller;
    private void setViewPagerScroll(boolean instant) {
        try {
            Field mScroller = null;
            mScroller = ViewPager.class.getDeclaredField("mScroller");
            mScroller.setAccessible(true);
            if (scroller == null) {
                scroller = (Scroller) mScroller.get(mViewPager);
            }
            FixedSpeedScroller fss = new FixedSpeedScroller(mViewPager.getContext());
            mScroller.set(mViewPager, instant ? fss : scroller);
    
        } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
    

    and modify onPageScrollStateChanged like this, only first page or last page (i have 5 pages) would change animation to fast scrolling, otherwise has normal scrolling:

    public void onPageScrollStateChanged(int state) {
        if (state == ViewPager.SCROLL_STATE_IDLE) {
            if (position == 0) {
                setViewPagerScroll(true);
                mViewPager.setCurrentItem(3);
    
            } else if (position == 4) {
                setViewPagerScroll(true);
                mViewPager.setCurrentItem(1);
    
            } else {
                setViewPagerScroll(false);
            }
        }
    }
    

    FixedSpeedScroller references is here: http://blog.csdn.net/ekeuy/article/details/12841409

提交回复
热议问题