How to do circular scrolling on ViewPager?

后端 未结 10 1550
别那么骄傲
别那么骄傲 2020-11-28 04:31

I would like to set my ViewPager to do circular scrolling. I want the first page to be able to scroll to page 2 AND the last page. And I would like my last page to scroll to

10条回答
  •  悲哀的现实
    2020-11-28 05:19

    The answer of @tobi_b is not totally successful, since it doesn't slide smoothly from the last to the first(At least in my trial). But I was really inspired by his answer. My solution is when it's time to jump from the fake last to the real first, wait until last scroll finished. Here is my code, it's very simple,

    private final class MyPageChangeListener implements OnPageChangeListener {
    
        private int currentPosition;
    
        @Override
        public void onPageScrollStateChanged(int state) {
            if (state == ViewPager.SCROLL_STATE_IDLE) {
                if (currentPosition == viewPager.getAdapter().getCount() - 1) {
                    viewPager.setCurrentItem(1, false);
                }
                else if (currentPosition == 0) {
                    viewPager.setCurrentItem(viewPager.getAdapter().getCount() - 2, false);
                }
            }
        }
    
        @Override
        public void onPageScrolled(int scrolledPosition, float percent, int pixels) {
            //empty
        }
    
        @Override
        public void onPageSelected(int position) {
            currentPosition = position;
        }
    
    }
    

    However, this solution is not perfect. It has a little flaw when slide fast from the last to the first. If we slide twice in a very short time, the second slide will invalidate. This problem need to be solved.

提交回复
热议问题