Image Carousel In Jetpack Compose — material3
Grab a coffee ☕, and let’s implement an image carousel using material3 and Jetpack Compose.
Dependency
Go ahead in your build.gradle
from app
module.
dependencies {
implementation("androidx.compose.material3:material3:1.3.0-beta04")
}
Implementation
Let’s start by creating the MyCarousel
composable. And inside let’s firstly create the carouselState
.
@Composable
fun MyCarousel() {
val carouselState = rememberCarouselState { 3 }
}
After that, let’s create the carousel. For that, we will use the HorizontalMultiBrowseCarousel
.
HorizontalMultiBrowseCarousel(
state = carouselState,
preferredItemWidth = 300.dp,
itemSpacing = 10.dp
) { page ->
// ...
}
Now let’s add the images. Firstly add a Box
that will have a size of 300.dp
and inside add the image.
Box(modifier = Modifier.size(300.dp)) {
Image(
painter = painterResource(
id = when (page) {
0 -> R.drawable.capp_1
1 -> R.drawable.capp_2
else -> R.drawable.capp_3
}
),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)
}
The last thing we have to do is to call this function in the MainActivity.kt
and run the app.
setContent {
MyAppTheme {
MyCarousel()
}
}
So that’s it. For the latest updates, follow me and subscribe to the newsletter. If you want to see more content, make sure to follow me on X and subscribe to my YouTube channel! Thanks for reading! 😊☕️