How to create image slider with Jetpack Compose

HariAgusWidakdo
2 min readMay 17, 2023

Bismillah. Hello everyone, in this short article i will write about how to create image slider with jetpack compose. First I would like to thank those who made the design above.

First of all we need a library, to make an image scrollable and have indicators below it :

implementation "com.google.accompanist:accompanist-pager:0.28.0"
implementation "com.google.accompanist:accompanist-pager-indicators:0.28.0"

Next, we create an image data, here I only try 3 images :

val pagerState = rememberPagerState(initialPage = 0)
val imageSlider = listOf(
painterResource(id = R.drawable.img_banner1),
painterResource(id = R.drawable.img_banner2),
painterResource(id = R.drawable.img_banner3)
)

Next, since we need the effect to run asynchronously, we use LaunchEffect() to set up the scrolling :

LaunchedEffect(Unit) {
while (true) {
yield()
delay(2600)
pagerState.animateScrollToPage(
page = (pagerState.currentPage + 1) % (pagerState.pageCount)
)
}
}

Lastly, we make a design :

 Column {
HorizontalPager(
count = imageSlider.size,
state = pagerState,
contentPadding = PaddingValues(horizontal = DIMENS_16dp),
modifier = modifier
.height(DIMENS_114dp)
.fillMaxWidth()
) { page ->
Card(
shape = RoundedCornerShape(DIMENS_12dp),
modifier = Modifier
.graphicsLayer {
val pageOffset = calculateCurrentOffsetForPage(page).absoluteValue

lerp(
start = 0.85f,
stop = 1f,
fraction = 1f - pageOffset.coerceIn(0f, 1f)
).also { scale ->
scaleX = scale
scaleY = scale
}

alpha = lerp(
start = 0.5f,
stop = 1f,
fraction = 1f - pageOffset.coerceIn(0f, 1f)
)
}
) {
Image(
painter = imageSlider[page],
contentDescription = stringResource(R.string.image_slider),
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)
}
}

HorizontalPagerIndicator(
pagerState = pagerState,
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(DIMENS_16dp)
)
}

Finally, we use very little code using jetpack compose, right? Yapss… Jetpack Compose is very effective for creating modern applications today.

Okay, maybe that’s all in this short article, I hope it can help those who read it. If anyone needs the complete code, check the link below :

https://github.com/HariAgus/GroceriesApp-Compose

--

--

HariAgusWidakdo

Mobile Developer | Kotlin Developer | SwiftUI 📱. Sometimes write my story 📚