如何使用 Jetpack compose 实现交错的网格布局? [英] How to achieve a staggered grid layout using Jetpack compose?
问题描述
据我所知,我们只能在 Jetpack Compose
中使用 Rows
和 Columns
来显示列表.如何实现如下图所示的交错网格布局?使用 Recyclerview
和交错网格布局管理器的正常实现非常简单.但是如何在 Jetpack Compose 中做同样的事情?
As far as I can see we can only use Rows
and Columns
in Jetpack Compose
to show lists. How can I achieve a staggered grid layout like the image below? The normal implementation of it using a Recyclerview
and a staggered grid layout manager is pretty easy. But how to do the same in Jetpack Compose ?
推荐答案
Google 的 Compose 示例之一 Owl 展示了如何进行交错的网格布局.这是用于编写此代码的代码片段:
One of Google's Compose sample Owl shows how to do a staggered grid layout. This is the code snippet that is used to compose this:
@Composable
fun StaggeredVerticalGrid(
modifier: Modifier = Modifier,
maxColumnWidth: Dp,
children: @Composable () -> Unit
) {
Layout(
children = children,
modifier = modifier
) { measurables, constraints ->
check(constraints.hasBoundedWidth) {
"Unbounded width not supported"
}
val columns = ceil(constraints.maxWidth / maxColumnWidth.toPx()).toInt()
val columnWidth = constraints.maxWidth / columns
val itemConstraints = constraints.copy(maxWidth = columnWidth)
val colHeights = IntArray(columns) { 0 } // track each column's height
val placeables = measurables.map { measurable ->
val column = shortestColumn(colHeights)
val placeable = measurable.measure(itemConstraints)
colHeights[column] += placeable.height
placeable
}
val height = colHeights.maxOrNull()?.coerceIn(constraints.minHeight, constraints.maxHeight)
?: constraints.minHeight
layout(
width = constraints.maxWidth,
height = height
) {
val colY = IntArray(columns) { 0 }
placeables.forEach { placeable ->
val column = shortestColumn(colY)
placeable.place(
x = columnWidth * column,
y = colY[column]
)
colY[column] += placeable.height
}
}
}
}
private fun shortestColumn(colHeights: IntArray): Int {
var minHeight = Int.MAX_VALUE
var column = 0
colHeights.forEachIndexed { index, height ->
if (height < minHeight) {
minHeight = height
column = index
}
}
return column
}
然后你可以传入你的可组合项:
And then you can pass in your item composable in it:
StaggeredVerticalGrid(
maxColumnWidth = 220.dp,
modifier = Modifier.padding(4.dp)
) {
// Use your item composable here
}
Link to snippet in the sample: https://github.com/android/compose-samples/blob/1630f6b35ac9e25fb3cd3a64208d7c9afaaaedc5/Owl/app/src/main/java/com/example/owl/ui/courses/FeaturedCourses.kt#L161
这篇关于如何使用 Jetpack compose 实现交错的网格布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!