In Jetpack Compose, How to find the width of each child of a Row
?
I tried using onGloballyPositioned
like below, but the size is wrong.
Also, not sure if this is the optimal one.
I need the width of each child and further processing will be done based on that, the below is a simplified code for example.
@Composable
fun MyTabSample() {
MyCustomRow(
items = listOf("Option 1 with long", "Option 2 with", "Option 3"),
)
}
@Composable
fun MyCustomRow(
modifier: Modifier = Modifier,
items: List<String>,
) {
val childrenWidths = remember {
mutableStateListOf<Int>()
}
Box(
modifier = modifier
.background(Color.LightGray)
.height(IntrinsicSize.Min),
) {
// To add more box here
Box(
modifier = Modifier
.widthIn(
min = 64.dp,
)
.fillMaxHeight()
.width(childrenWidths.getOrNull(0)?.dp ?: 64.dp)
.background(
color = DarkGray,
),
)
Row(
horizontalArrangement = Arrangement.Center,
) {
items.mapIndexed { index, text ->
Text(
modifier = Modifier
.widthIn(min = 64.dp)
.padding(
vertical = 8.dp,
horizontal = 12.dp,
)
.onGloballyPositioned {
childrenWidths.add(index, it.size.width)
},
text = text,
color = Black,
textAlign = TextAlign.Center,
)
}
}
}
}