我想获得一个LazyRow
看起来像这样:
|--aaa-b|bb-cccc|-dd... ...|w--x---|
|--------|是一屏宽度
元素的大小各不相同,但它们之间的间距是固定的。
我想我可以添加一些开始内容填充LazyRow
以便“aaa”可组合项与屏幕中心对齐,但我不知道它的宽度。
如果您认为我问的不清楚,请发表评论。
UPDATE
添加了 gif 以便更好地理解
您可以使用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)
}
}
)
}
}
}
}
结果如下:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)