Jetpack Compose - 让LazyRow中的第一个元素居中对齐屏幕

3
我想获得一个类似于这样的LazyRow:

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

|-------| 是一个屏幕宽度

元素的大小不同,但它们之间有固定的间距。我认为我可以给LazyRow添加一些起始内容填充,使"aaa"组合对齐到屏幕的中心,但我不知道它的宽度。

如果您认为我的问题不清楚,请留言说明。

更新

添加一个GIF以便更好地理解:

enter image description here

2个回答

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)
                        }
                    }
                )
            }
        }
    }
}

这是结果:

在此输入图像描述


0

在运行时计算设备宽度并除以2或任何您想要的比例。

查看此链接以进行运行时宽度计算:https://dev59.com/BGw15IYBdhLWcg3wqNqM#11755265

设置内容填充的起始位置。

LazyColumn( contentPadding = PaddingValues(start = (device_width/2).dp) )

这将在所有设备上保持相同。


1
这将项目的起始点对齐到屏幕中心。 - daniyelp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接