更新。现在您可以使用系统FlowRow
:
val words = LoremIpsum(10).values.first()
.split(" ", "\n")
FlowRow(
horizontalArrangement = Arrangement.spacedBy(7.dp),
verticalArrangement = Arrangement.spacedBy(7.dp),
modifier = Modifier
.padding(7.dp)
) {
words.forEach { word ->
Text(
word,
modifier = Modifier
.background(color = Color.Gray, shape = CircleShape)
.padding(vertical = 3.dp, horizontal = 5.dp)
)
}
}
@Composable
fun ChipVerticalGrid(
modifier: Modifier = Modifier,
spacing: Dp,
content: @Composable () -> Unit
) {
Layout(
content = content,
modifier = modifier
) { measurables, constraints ->
var currentRow = 0
var currentOrigin = IntOffset.Zero
val spacingValue = spacing.toPx().toInt()
val placeables = measurables.map { measurable ->
val placeable = measurable.measure(constraints)
if (currentOrigin.x > 0f && currentOrigin.x + placeable.width > constraints.maxWidth) {
currentRow += 1
currentOrigin = currentOrigin.copy(x = 0, y = currentOrigin.y + placeable.height + spacingValue)
}
placeable to currentOrigin.also {
currentOrigin = it.copy(x = it.x + placeable.width + spacingValue)
}
}
layout(
width = constraints.maxWidth,
height = placeables.lastOrNull()?.run { first.height + second.y } ?: 0
) {
placeables.forEach {
val (placeable, origin) = it
placeable.place(origin.x, origin.y)
}
}
}
}
使用方法:
val words = LoremIpsum(10).values.first()
.split(" ", "\n")
ChipVerticalGrid(
spacing = 7.dp,
modifier = Modifier
.padding(7.dp)
) {
words.forEach { word ->
Text(
word,
modifier = Modifier
.background(color = Color.Gray, shape = CircleShape)
.padding(vertical = 3.dp, horizontal = 5.dp)
)
}
}
结果:
截至2022年11月10日,除非有其他建议,Google工程师建议使用
FlowRow {
// row contents
}
FlowColumn {
// column contents
}
来自 https://github.com/google/accompanist/tree/main/flowlayout
Android 开发者峰会 22 https://youtu.be/TqbzXC1xtko?t=5146
[2023] Google 官方:
https://developer.android.com/jetpack/compose/layouts/flow
FlowRow(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(16.dp),
) {
items.forEach { it ->
item {
CustomChip(
item = it,
isSelected = it == currentItem,
onItemChanged = {
onItemChanged(it)
}
)
}
}
}
.verticalScroll(scrollState)
添加到flowLayout的修饰符(modifier)中即可。 - kuzdu