I am trying to create a UI which looks very similar to the one at the top of the Material3 Chip page.
It appears that the best way to do so is to construct a LazyVerticalStaggeredGrid
, whose content consists of FilteredChip
composables.
A single FilteredChip in a Column displays just fine. But when I wrap it in a LazyVerticalStaggeredGrid instead, it is ignoring the text size constraints and reducing the width of each chip, and giving a very large height. According to Layout Inspector, the text has width 0dp and height 140dp. In addition, it’s ignoring my theming color scheme.
I expected it to measure the size of the text within the Text composable, and pass that up to determine the width of each chip and the height of each row. If that’s not how LazyGrids work, how should I approach this?
Here’s a very simple example that illustrates my problem:
@Composable
fun VerticalGrid(
contentList: List<String>,
modifier: Modifier = Modifier,
) {
LazyVerticalStaggeredGrid(
horizontalArrangement = Arrangement.spacedBy(16.dp),
columns = StaggeredGridCells.Adaptive(minSize = 4.dp),
verticalItemSpacing = 8.dp,
modifier = modifier.fillMaxSize()
) {
var selected = false
items(contentList) { text ->
Chip(text, selected, { selected = !selected }, modifier)
}
}
}
@Composable
fun Chip(
text: String,
selected: Boolean,
onClick: () -> (Unit),
modifier: Modifier = Modifier,
) {
FilterChip(
onClick = onClick,
label = { Text(text = text) },
selected = selected,
modifier = modifier
)
}
object Content {
val contentList = mutableListOf<String>()
init {
for (i in 10..50) {
contentList.add("Label$i")
}
}
}
@Preview(showBackground = true)
@Composable
fun ChipPreview1() {
StaggeredGridOfChipsTheme {
Column(
verticalArrangement = Arrangement.Top,
modifier = Modifier.fillMaxSize()
) {
Chip("Hello", true, {})
}
}
}
@Preview(showBackground = true)
@Composable
fun VerticalGridPreview1() {
StaggeredGridOfChipsTheme {
VerticalGrid(Content.contentList, Modifier.fillMaxSize())
}
}
It results in the following behavior:
Any tips that would have helped me troubleshoot this would also be welcome.