BoxWithConstraints
来获取屏幕宽度。然后可以使用 Layout
来正确地定位列表中的项。@Composable
fun BigCarousel() {
val items = (0..10).map { "Item $it" }
BoxWithConstraints {
LazyRow {
itemsIndexed(items) { index, item ->
Layout(
content = {
// Here's the content of each list item.
Box(
Modifier
.size(200.dp)
.padding(8.dp)
.background(Color.Gray)
) {
Text(text = item, Modifier.align(Alignment.Center))
}
},
measurePolicy = { measurables, constraints ->
// I'm assuming you'll declaring just one root
// composable in the content function above
// so it's measuring just the Box
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 == items.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 = if (index == 0) startSpace else 0
placeable.place(x, 0)
}
}
)
}
}
}
}
这是结果:
在运行时计算设备宽度并除以2或任何您想要的比例。
查看此链接以进行运行时宽度计算:https://dev59.com/BGw15IYBdhLWcg3wqNqM#11755265
设置内容填充的起始位置。
LazyColumn( contentPadding = PaddingValues(start = (device_width/2).dp) )
这将在所有设备上保持相同。