如果您不介意使用不稳定的 API,您可以使用LazyVerticalGrid
并使用参数item
获取全宽span
,正如@Mustafa指出的那样:
LazyVerticalGrid(
cells = GridCells.Fixed(spanCount),
) {
item(
span = { GridItemSpan(spanCount) }
) {
Text("Title")
}
items(10) {
Text(it.toString())
}
}
直到稳定为止,推荐
LazyColumn
使用像和一样的稳定组件Row
来达到相同的结果。
可以通过实现gridItems
与 一起使用来完成LazyColumn
。
fun LazyListScope.gridItems(
count: Int,
nColumns: Int,
horizontalArrangement: Arrangement.Horizontal = Arrangement.Start,
itemContent: @Composable BoxScope.(Int) -> Unit,
) {
gridItems(
data = List(count) { it },
nColumns = nColumns,
horizontalArrangement = horizontalArrangement,
itemContent = itemContent,
)
}
fun <T> LazyListScope.gridItems(
data: List<T>,
nColumns: Int,
horizontalArrangement: Arrangement.Horizontal = Arrangement.Start,
key: ((item: T) -> Any)? = null,
itemContent: @Composable BoxScope.(T) -> Unit,
) {
val rows = if (data.isEmpty()) 0 else 1 + (data.count() - 1) / nColumns
items(rows) { rowIndex ->
Row(horizontalArrangement = horizontalArrangement) {
for (columnIndex in 0 until nColumns) {
val itemIndex = rowIndex * nColumns + columnIndex
if (itemIndex < data.count()) {
val item = data[itemIndex]
androidx.compose.runtime.key(key?.invoke(item)) {
Box(
modifier = Modifier.weight(1f, fill = true),
propagateMinConstraints = true
) {
itemContent.invoke(this, item)
}
}
} else {
Spacer(Modifier.weight(1f, fill = true))
}
}
}
}
}
用法:
LazyColumn {
item {
Text(text = "My LazyColumn Title")
}
// with count
gridItems(10, nColumns = 4) { index ->
Box(
modifier = Modifier
.size(50.dp)
.padding(5.dp)
.background(Color.Gray)
)
}
// or with list of items
gridItems(listOf(1,2,3), nColumns = 4) { item ->
Box(
modifier = Modifier
.size(50.dp)
.padding(5.dp)
.background(Color.Gray)
)
}
}