How do I make my page always in the center with th...
# compose
d
How do I make my page always in the center with the new
HorizontalPager
(foundation)? it is aligning the current item always on the left, I want it always in the center see screenshot, code in thread
the code to get this
Copy code
@OptIn(ExperimentalFoundationApi::class)
@Preview
@Composable
private fun TestPager() {
    val state = rememberPagerState(
        pageCount = { 10 },
    )
    HorizontalPager(
        state = state,
        modifier = Modifier
            .fillMaxWidth()
            .background(Color.White),
        pageSize = PageSize.Fixed(150.dp),
        pageSpacing = 16.dp,
        contentPadding = PaddingValues(horizontal = 16.dp),
    ) { page ->
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .aspectRatio(1f)
                .clip(RoundedCornerShape(16.dp))
                .background(Color.Green)
        ) {
            Text(
                text = page.toString(),
                modifier = Modifier.align(Alignment.Center),
                fontSize = 50.sp,
            )
        }
    }
}
the first video in the official doc for the pager showcase exactly what I need https://developer.android.com/jetpack/compose/layouts/pager you can see the current page always visible and neighbour pages peaking in
I can “kinda” achieve it by playing with negative spacing between items…. but that can’t be the way to do this, right?
I see I need to use the content padding for that, computing the correct amount
Not sure if this is the intended way of using the API but this works
Copy code
@OptIn(ExperimentalFoundationApi::class)
@Preview
@Composable
private fun TestPager() {
    val state = rememberPagerState(
        pageCount = { 10 },
    )
    BoxWithConstraints(
        Modifier.fillMaxWidth(),
    ) {
        val horizontalPadding = (maxWidth - 150.dp) / 2
        HorizontalPager(
            state = state,
            modifier = Modifier
                .fillMaxWidth()
                .background(Color.White),
            pageSize = PageSize.Fixed(150.dp),
            pageSpacing = 16.dp,
            contentPadding = PaddingValues(horizontal = horizontalPadding),
        ) { page ->
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .aspectRatio(1f)
                    .clip(RoundedCornerShape(16.dp))
                    .background(Color.Green)
            ) {
                Text(
                    text = page.toString(),
                    modifier = Modifier.align(Alignment.Center),
                    fontSize = 50.sp,
                )
            }
        }
    }
}
r
335 Views