I want to create a horizontal scroll and always view the center screen when scrolling. I found it was created with viewpager2, but when working with Jetpack Composer, I don't know how to create it. I also tried to watch on YouTube and search in a few other places, but I haven't found any solutions. Can someone help me or suggest how to make a view like this? Thanks a lot.
It's looking like
You can use a HorizontalPager
and specify the contentPadding
and snapPosition
as follows:
@Composable
fun PagerExample() {
Column {
val state = rememberPagerState { 10 }
HorizontalPager(
state = state,
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(horizontal = 25.dp),
snapPosition = SnapPosition.Center
) { page ->
Box(
modifier = Modifier
.background(if (page % 2 == 0) Color.Cyan else Color.LightGray)
.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Text(text = page.toString(), fontSize = 32.sp)
}
}
}
}
Alternatively, there also is the pageSize
attribute where you can explicitly set the width of each of your pages in dp
.
Output: