Jetpack Compose - 使 LazyRow 中的第一个元素与屏幕中心对齐

dan*_*elp 3 android android-jetpack-compose android-jetpack-compose-list

我想获得一个LazyRow看起来像这样的:

|--aaa-b|bb-cccc|-dd... ...|w--x---|

|--------| 是一屏宽度

元素的大小各不相同,但它们之间的间距是固定的。我想我可以添加一些开始内容填充,以便LazyRow“aaa”可组合项与屏幕中心对齐,但我不知道它的宽度。

如果您认为我问的不清楚,请发表评论。

更新

添加了 gif 以便更好地理解

在此输入图像描述

ngl*_*ber 7

您可以使用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)
                        }
                    }
                )
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此输入图像描述