Issue
So, I've created a Chip composable and using it in a LazyRow like this:
LazyRow(
modifier = modifier,
horizontalArrangement = Arrangement.spacedBy(16.dp),
){
items.forEach { it ->
item {
CustomChip(
item = it,
isSelected = it == currentItem,
onItemChanged = {
onItemChanged(it)
}
)
}
}
}
But, I want to attain a layout like the above mentioned image. I.e, If number of chips reaches end of screen, then the new chips should come in new line.
Solution
Update. Now you can use Accompanist FlowRow
:
FlowRow(
modifier = modifier,
mainAxisSpacing = 16.dp,
crossAxisSpacing = 16.dp,
) {
items.forEach { it ->
CustomChip(
item = it,
isSelected = it == currentItem,
onItemChanged = {
onItemChanged(it)
}
)
}
}
Original answer. If you are interested in building something like this yourself, you can do it with Layout
:
@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)
}
}
}
}
Usage:
val words = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
.split(" ")
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)
)
}
}
Result:
Answered By - Pylyp Dukhov
Answer Checked By - Timothy Miller (JavaFixing Admin)