SpiralDev
SpiralDev

Reputation: 7331

OffscreenPageLimit behaviour for ViewPager from Accompanist

I am using HorizontalViewPager from Accompanist to show an image in each page of the viewpager. I am loading images with Coil. Here's the code:

val pagerState = rememberPagerState()

HorizontalPager(count = photos.size, state = pagerState) {
    idx ->
    photos[idx].let { cur ->
        Image(
            painter = rememberImagePainter(url),
            contentDescription = null,
            modifier - Modifier.fillMaxSize(), 
            contentScale = ContentScale.FillHeight,
            alignment = Alignment.Center
        )
    }
}

It is working fine. But, Images are being loaded only after the page is opened. I was wondering if there is a way to preload the content of the adjacent pages of viewpager before they are opened.

ViewPager from AndroidX offers similar behavior with setOffscreenPageLimit method.

Upvotes: 3

Views: 1518

Answers (1)

AI Shakil
AI Shakil

Reputation: 1772

Adding beyondBoundsPageCount in the HorizontalPager will solve you.

HorizontalPager(
    state = pagerState,
    modifier = Modifier
        .fillMaxWidth()
        .padding(top = 24.dp),
         beyondBoundsPageCount = pageCount.intValue // Default : 0
    ) { page ->    

      // **-- PAGE ITEMS --** //

}

Note: Be aware that using a large value for beyondBoundsPageCount will cause a lot of pages to be composed, measured and placed which will defeat the purpose of using lazy loading.

Upvotes: 0

Related Questions