How can I recycle views using ViewPager?

3.3k Views Asked by At

I have an activity that shows a calendar of a month, and allows users to swipe left and right to previous/next month. I want to use ViewPager for the smooth scrolling effect, but it should allow users to scroll left/right infinitely, so there is no way to set an fixed adapter beforehand.

I am wondering if it is possible to recycle the pages like this: initially set the adapter to include only 3 pages, and show the middle page,

  • When user swipes left, recycle the 3rd page to create a new page before the current page, set new adapter, and set index to 1 (middle).
  • When user swipes right, recycle the 1st page to create a new page after the current page, set new adapter, and set index to 1 (middle).

Can I do this with setAdapter() and setCurrentIndex()? Will this cause unwanted consequences?

1

There are 1 best solutions below

1
On

In other support recycling for ViewPager and improve performance, you should use View instead of Fragment. Basically this is instantiateItem you are looking for.

@Override
public Object instantiateItem(ViewGroup parent, int position) {
  int viewType = getItemViewType(position);
  if (!mRecycleCacheMap.containsKey(viewType)) {
    mRecycleCacheMap.put(viewType, new RecycleCache(this, parent, viewType));
  }
  ViewHolder viewHolder = mRecycleCacheMap.get(viewType).getFreeViewHolder();
  viewHolder.mIsAttached = true;
  onBindViewHolder((VH) viewHolder, position);
  parent.addView(viewHolder.mItemView);
  if (DEBUG) {
    Log.i(TAG, String.format(Locale.US, "instantiateItem | position: %d | viewType: %d | cacheCount: %d",
        position, viewType, mRecycleCacheMap.get(viewType).mCaches.size()));
  }
  return viewHolder;
}

Check out my sample code here RecyclerPagerAdapter