使用
Compose
创建 3 列垂直列表,但有时我需要插入一个横跨所有 3 列的组件,例如填充整个屏幕宽度的横幅。我确信应该有一个最佳实践方法来做到这一点,但我似乎找不到它。
有什么想法吗?
您可以将
LazyVerticalGrid
与自定义 GridItemSpan
一起用于您的物品。对于常规项目,请使用 1,对于横幅,请使用与列数匹配的数字:
如何使用跨度的简单示例:
//Total column count fro the grid
val columnCount = 3
//Dummy data
val items = remember { listOf(1, 2, 3, 4, 5) }
LazyVerticalGrid(
columns = GridCells.Fixed(columnCount),
horizontalArrangement = Arrangement.spacedBy(space = 10.dp),
verticalArrangement = Arrangement.spacedBy(space = 10.dp)
) {
//Regular items
items(
items = items,
span = { item -> GridItemSpan(currentLineSpan = 1) }
) { item ->
Text(
text = item.toString(),
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
}
//Full width banner item
item(
span = { GridItemSpan(currentLineSpan = columnCount) }
) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(80.dp)
.background(color = Color.Red)
) {
Text(
text = "Banner",
modifier = Modifier.align(alignment = Alignment.Center),
color = Color.White
)
}
}
}
由于您不时需要它,我建议您找到如何根据数据提供 lineSpan 的方法,我更喜欢为此使用密封类:
示例数据类:
//Using sealed class for items
sealed class Item constructor(
val lineSpan: Int
) {
//For reguar items set smaller span
class Category(val name: String) : Item(lineSpan = 1)
//For full width items set same span as column count
class Banner(val text: String) : Item(lineSpan = 3)
}
可组合:
//Total column count fro the grid
val columnCount = 3
//Dummy data
val items = remember {
listOf(
Item.Category(name = "Favorites"),
Item.Category(name = "Most popular"),
Item.Category(name = "Most rated"),
Item.Banner(text = "Banner 1"),
Item.Category(name = "Comedy"),
Item.Category(name = "Action"),
Item.Category(name = "Drama"),
Item.Banner(text = "Banner 2"),
)
}
LazyVerticalGrid(
columns = GridCells.Fixed(columnCount),
horizontalArrangement = Arrangement.spacedBy(space = 10.dp),
verticalArrangement = Arrangement.spacedBy(space = 10.dp)
) {
//Regular items
items(
items = items,
//Setting line span based on data item
span = { item -> GridItemSpan(currentLineSpan = item.lineSpan) }
) { item ->
when (item) {
is Item.Category -> {
Text(
text = item.name,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
}
is Item.Banner-> {
Box(
modifier = Modifier
.fillMaxWidth()
.height(height = 80.dp)
.background(color = Color.Red)
) {
Text(
text = item.text,
textAlign = TextAlign.Center,
color = Color.White,
modifier = Modifier.align(Alignment.Center)
)
}
}
}
}
}
通过此功能,您可以将数据项与横幅结合起来。