Mobile Development 16 min read

Understanding ViewPager2 OffscreenPageLimit and Its Performance Impact

This article explains the OffscreenPageLimit attribute of ViewPager2, how it controls off‑screen page loading, compares its default values with ViewPager, shows code implementations, analyzes performance trade‑offs, and provides practical recommendations for choosing an appropriate limit.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Understanding ViewPager2 OffscreenPageLimit and Its Performance Impact

From this point onward we formally begin the ViewPager2 series, using animated diagrams to illustrate concepts. The focus of this article is the off‑screen loading mechanism of ViewPager2, which is configured via the OffscreenPageLimit attribute.

What is OffscreenPageLimit? It represents the number of pages that should be retained on either side of the currently visible page. For horizontal paging this means pages to the left and right; for vertical paging, pages above and below.

The extra pages are kept by extending the layout space. In LinearLayoutManager this is achieved by overriding calculateExtraLayoutSpace :

/**
 * Calculate extra layout space
 */
@Override
protected void calculateExtraLayoutSpace(@NonNull RecyclerView.State state,
        @NonNull int[] extraLayoutSpace) {
    int pageLimit = getOffscreenPageLimit();
    if (pageLimit == OFFSCREEN_PAGE_LIMIT_DEFAULT) {
        // Only pre‑fetch when needed
        super.calculateExtraLayoutSpace(state, extraLayoutSpace);
        return;
    }
    // Allocate space for pageLimit * 2 pages
    final int offscreenSpace = getPageSize() * pageLimit;
    extraLayoutSpace[0] = offscreenSpace;
    extraLayoutSpace[1] = offscreenSpace;
}

/**
 * Get the size of a single page
 */
int getPageSize() {
    final RecyclerView rv = mRecyclerView;
    return getOrientation() == ORIENTATION_HORIZONTAL
            ? rv.getWidth() - rv.getPaddingLeft() - rv.getPaddingRight()
            : rv.getHeight() - rv.getPaddingTop() - rv.getPaddingBottom();
}

The method computes the extra layout space (in pixels) that LinearLayoutManager should allocate. The default space equals one page size; the additional space equals OffscreenPageLimit * 2 page sizes, stored in the extraLayoutSpace array where index 0 applies to the top/left side and index 1 to the bottom/right side.

Although these extra pages are not visible, they are added to the view hierarchy, reducing view creation and layout time during page switches and improving overall scrolling smoothness.

Comparing mechanisms:

Cache reuse: reuses already created pages.

Pre‑fetch: creates the next page during UI thread idle time.

Off‑screen loading: expands layout space to create and keep pages on both sides.

From a method‑call perspective, off‑screen loading also triggers an additional onViewAttachedToWindow call for each pre‑created page.

ViewPager2 inherits this mechanism from the original ViewPager, but differs in default values and constraints. ViewPager forces a default OffscreenPageLimit of 1 and disallows values below 1, effectively always enabling off‑screen loading. ViewPager2 sets the default to -1 , meaning off‑screen loading is disabled unless a positive value is supplied.

// ViewPager default
private static final int DEFAULT_OFFSCREEN_PAGES = 1;
public void setOffscreenPageLimit(int limit) {
    if (limit < DEFAULT_OFFSCREEN_PAGES) {
        Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " + DEFAULT_OFFSCREEN_PAGES);
        limit = DEFAULT_OFFSCREEN_PAGES;
    }
    if (limit != mOffscreenPageLimit) {
        mOffscreenPageLimit = limit;
        populate();
    }
}
// ViewPager2 default
public static final int OFFSCREEN_PAGE_LIMIT_DEFAULT = -1;
public void setOffscreenPageLimit(@OffscreenPageLimit int limit) {
    if (limit < 1 && limit != OFFSCREEN_PAGE_LIMIT_DEFAULT) {
        throw new IllegalArgumentException("Offscreen page limit must be OFFSCREEN_PAGE_LIMIT_DEFAULT or a number > 0");
    }
    mOffscreenPageLimit = limit;
    mRecyclerView.requestLayout();
}

In practice many developers set the limit to total pages ‑ 1 , which forces all pages to be loaded off‑screen, leading to high memory usage and longer initial load times.

Different OffscreenPageLimit values affect behavior:

Limit = -1 (default, off‑screen loading disabled)

Only RecyclerView’s cache reuse and pre‑fetch mechanisms operate. Pages are added to the hierarchy as the user scrolls, and pre‑fetch creates the next page without adding it to the hierarchy.

Limit = 1

One page on each side is kept off‑screen. The current and adjacent pages stay in the hierarchy, while the next page is pre‑fetched.

Limit = 3

Three pages on each side are retained, providing the smoothest scrolling at the cost of higher memory consumption.

Limit = totalPages ‑ 1

All pages are loaded during initialization, eliminating cache reuse and pre‑fetch but heavily taxing memory and startup time.

Performance impact analysis (white‑screen time, smoothness, memory usage) shows that larger limits improve scrolling smoothness but increase initial rendering time and memory footprint. A balanced choice is typically 3‑4 pages kept active, which offers good responsiveness without excessive memory pressure.

In scenarios where pages have mutually exclusive logic, keeping the default (off‑screen loading disabled) and relying on pre‑fetch may be preferable.

Finally, when ViewPager2 is combined with TabLayout for direct tab navigation, the off‑screen loading behavior changes, which will be covered in the next article.

PerformanceandroidFragmentRecyclerViewOffscreenPageLimitViewPager2
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.