I am trying to develop carousel UI that starts in the middle of the screen at the bottom and when we click on next item it automatically come in the middle. I am using LazyRow
and using Layout
with measurePolicy
.
Layout(
content = { itemContent(item, itemModifier) },
measurePolicy = { measurables, constraints ->
val placeable = measurables.first().measure(constraints)
// maxWidth is from the BoxWithConstraints
val maxWidthInPx = maxWidth.roundToPx()
// Box width
val itemWidth = placeable.width
// Calculating the space for the first and last item
val startSpace =
if (index == 0) (maxWidthInPx - itemWidth) / 2 else 0
val endSpace =
if (index == data.lastIndex) (maxWidthInPx - itemWidth) / 2 else 0
// The width of the box + extra space
val width = startSpace + placeable.width + endSpace
layout(width, placeable.height) {
// Placing the Box in the right X position
val x = startSpace
placeable.place(x, 0)
}
})
}
This is working for first element but clicking on next element, the selected element go to the start of the screen, instead it should be in the middle.