Maybe I’ve been up too long, but I can’t seem to f...
# compose
j
Maybe I’ve been up too long, but I can’t seem to figure out my HorizontalPager. I want the first item to be centered in the screen, with the next item visible by 25%. I’ve tried a bunch of things but can’t get it to work. I have this code:
Copy code
Column(
    horizontalAlignment = Alignment.CenterHorizontally,
    verticalArrangement = Arrangement.Center,
    modifier = Modifier.fillMaxSize(),
) {
    HorizontalPager(
        state = pagerState,
        beyondBoundsPageCount = 1,
        contentPadding = PaddingValues(horizontal = 32.dp),
        pageSpacing = 16.dp,
    ) { page ->
        Box(
            modifier = Modifier
                .size(200.dp)
                .background(if (page % 2 == 0) Color.Red else Color.Blue),
        )
    }
}
But it produces something like the attached image. Can anyone help me out?
I was able to get it to work by doing:
Copy code
val density = LocalDensity.current
var componentHeight by remember { mutableStateOf(200.dp) }

Column(
    horizontalAlignment = Alignment.CenterHorizontally,
    verticalArrangement = Arrangement.Center,
    modifier = Modifier.fillMaxSize(),
) {
    HorizontalPager(
        state = pagerState,
        beyondBoundsPageCount = 1,
        pageSize = PageSize.Fixed(componentHeight),
        contentPadding = PaddingValues(horizontal = componentHeight / 2),
        pageSpacing = 32.dp,
    ) { page ->
        Box(
            modifier = Modifier
                .size(200.dp)
                .background(if (page % 2 == 0) Color.Red else Color.Blue)
                .onGloballyPositioned { coordinates ->
                    componentHeight = with(density) {
                        coordinates.size.height.toDp()
                    }
                },
        )
    }
}
But how hacky is that?
Nevermind, that works in Preview but not on an actual device..
a
If this can help

https://www.youtube.com/watch?v=6BVPFyms2iE