Infinite ViewPager

Jon Willis picture Jon Willis · Sep 16, 2011 · Viewed 19.3k times · Source

This seems possible, but I'm having a little trouble figuring out how to implement a ViewPager that can page indefinitely.

My use case is for a calendar that shows a month at a time, but would be able to switch to any month by paging enough times.

Currently I'm just extending PagerAdapter, and 3 custom MonthViews are added like so:

    @Override
    public Object instantiateItem(View collection, int position) {
        final MonthView mv = new MonthView(HistoryMonthActivity.this);
        mv.setLayoutParams(new ViewSwitcher.LayoutParams(
                android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                android.view.ViewGroup.LayoutParams.MATCH_PARENT));
        mv.setSelectedTime(mTime);

        ((DirectionalViewPager) collection).addView(mv, 0);

        return mv;
    }

I would like to keep only 3 MonthViews in memory at a time, so that there isn't a huge delay in displaying data from my database on each MonthView when the user is tabbing. So every time a new page is shown, I will need to remove one MonthView and add one MonthView. If anyone has a better idea for the same functionality , I'd love to hear it!

I'm thinking of trying to use a FragmentStatePagerAdapter.

Answer

Jon Willis picture Jon Willis · Sep 18, 2011

I was able to implement this using a little magic in my MonthViews, my PagerAdapter's OnPageChangeListener, as well as with editing the source code of ViewPager itself. If anyone is interested in how I achieved it, check out the source code or comment with a specific question.