Jetpack Compose Image Pager/Viewer (Side Scroll One by One)

December 17, 2021

Dependencies

dependencies {
    implementation "com.google.accompanist:accompanist-pager:0.20.2"
}

Screen

@ExperimentalPagerApi
@Composable
fun PhotoPagerScreen(
    images: List<Any>,
    page: Int,
    onContentChange: (String, String) -> Unit,
    onShortChange: (String, String) -> Unit
) {
    val pagerState = rememberPagerState()

    HorizontalPager(count = images.size, state = pagerState) { page ->
        val image = images[page]


        val painter = rememberImagePainter(
            data = image // ?: R.drawable.error,
            builder = {
                // size(64)
                placeholder(R.drawable.placeholder)
                // transition when placeholder -> image
                crossfade(true)
                error(R.drawable.error)
            }
        )

        Box {
            Image(
                painter = painter,
                contentDescription = null,
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.Fit
            )
        }
    }

    LaunchedEffect(page) {
        pagerState.scrollToPage(page)
    }
}

NOTE: Refer Jetpack Compose Load Image With Coil

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.