如何在Jetpack Compose中实现多行Chip组?
Ah, I get it—you're using LazyRow which is built for horizontal scrolling, so it won't automatically wrap your Chips to a new line when they reach the screen edge. To achieve that wrapped, flow-style layout you're targeting, you'll want to replace LazyRow with FlowRow, a component designed exactly for this kind of dynamic line-wrapping behavior.
Step 1: Replace LazyRow with FlowRow
Here's how to adjust your code to use FlowRow (note: this uses the Material3 implementation, which is widely recommended for modern Compose projects):
FlowRow( modifier = modifier, horizontalArrangement = Arrangement.spacedBy(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp), // Optional: adds spacing between rows verticalAlignment = Alignment.CenterVertically ) { items.forEach { item -> CustomChip( item = item, isSelected = item == currentItem, onItemChanged = { onItemChanged(it) } ) } }
Key Details:
FlowRowautomatically calculates available screen width and wraps items to a new line when there's no more space in the current row.- Use
verticalArrangementto add spacing between rows for better visual hierarchy (this is optional but recommended). - If you haven't already, make sure your project includes the Material3 dependency in your module-level
build.gradle:implementation "androidx.compose.material3:material3:1.2.0" // Adjust version to match your project
Bonus: Add Vertical Scrolling (If Needed)
If your list of Chips might grow long enough to exceed the screen height, wrap the FlowRow in a LazyColumn to enable vertical scrolling:
LazyColumn( modifier = modifier, verticalArrangement = Arrangement.spacedBy(12.dp) ) { item { FlowRow( horizontalArrangement = Arrangement.spacedBy(16.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { items.forEach { item -> CustomChip( item = item, isSelected = item == currentItem, onItemChanged = { onItemChanged(it) } ) } } } }
This way, your Chips will wrap horizontally and you can scroll vertically if the content overflows the screen.
内容的提问来源于stack exchange,提问作者imn

