thehayro thehayro - 1 year ago 793
Android Question

Changing ViewPager to enable infinite page scrolling

Jon Willis has posted on how to enable an infinite scrolling with his code.
In there he said that he made some changes in the ViewPager class int the android support library. Which changes have been made and how is it possible to "recompile" the library with the ViewPager change?


Answer Source

Thank you for your answer Shereef.

I solved it a little bit differently.

I changed the code of the ViewPager class of the android support library. The method setCurrentItem(int)

changes the page with animation. This method calls an internal method that requires the index and a flag enabling smooth scrolling. This flag is boolean smoothScroll. Extending this method with a second parameter boolean smoothScroll solved it for me. Calling this method setCurrentItem(int index, boolean smoothScroll) allowed me to make it scroll indefinitely.

Here is a full example:

Please consider that only the center page is shown. Moreover did I store the pages seperately, allowing me to handle them with more ease.

private class Page {
  View page;
  List<..> data;
// page for predecessor, current, and successor
Page[] pages = new Page[3];

mDayPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        public void onPageSelected(int position) {

        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

        public void onPageScrollStateChanged(int state) {

            if (state == ViewPager.SCROLL_STATE_IDLE) {

                if (mFocusedPage == 0) {
                    // move some stuff from the 
                                            // center to the right here
                    moveStuff(pages[1], pages[2]);

                    // move stuff from the left to the center 
                    moveStuff(pages[0], pages[1]);
                    // retrieve new stuff and insert it to the left page
                else if (mFocusedPage == 2) {

                    // move stuff from the center to the left page
                    moveStuff(pages[1], pages[0]); 
                    // move stuff from the right to the center page
                    moveStuff(pages[2], pages[1]); 
                    // retrieve stuff and insert it to the right page

                // go back to the center allowing to scroll indefinitely
                mDayPager.setCurrentItem(1, false);

However, without Jon Willis Code I wouldn't have solved it myself.

EDIT: here is a blogpost about this:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download