user20393696
user20393696

Reputation:

How to create Viewpager Transformation in Jetpack Compose?

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

1

Upvotes: 0

Views: 598

Answers (1)

BenjyTec
BenjyTec

Reputation: 10887

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:

Upvotes: 2

Related Questions