Search code examples
androidandroid-viewpager

Circular ViewPager for continuous scrolling


I am displaying a ViewPager containing only ImageViews. But, I need it to happen continuously in a circular manner. For Ex : ...c > B > A > B > c...


Solution

  • Just implement the ViePager.OnPageChangeListener:

    YOUR_VIEWPAGER.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
          currentPage = position;
        }
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
          // not needed
        }
        @Override
        public void onPageScrollStateChanged(int state) {
          if (state == ViewPager.SCROLL_STATE_IDLE) {
            int pageCount = pages.size();
    
            if (currentPage == 0){
              YOUR_VIEWPAGER.setCurrentItem(pageCount-2,false);
            } else if (currentPage == pageCount-1){
              YOUR_VIEWPAGER.setCurrentItem(1,false);
            }
          }
        }
      });