How to make the width of a Text equal to the width of another implicitly measured Text?

Viewed 220

There is a reader app with two Texts, one for the total number of pages and one for the current page. I want the width of the current page Text to be equal to the width of the total page Text, but the width of the total page Text is measured implicitly.

Currently, I can only specify the width like this:

Row {
    Text(modifier = Modifier.width(32.dp), text = "1000") // total page
    Slider(...)
    Text(modifier = Modifier.width(32.dp), text = "1") // current page
}
1 Answers

To get render text layout, you can use onTextLayout. It has all information you may need, including size.

Then you can pass this size to second Text modifier:

var totalPageTextWidth by remember { mutableStateOf<Int?>(null) }
val widthModifier = totalPageTextWidth?.let { width ->
    with(LocalDensity.current) { 
        Modifier.width(width.toDp()) 
    }
} ?: Modifier
Text(
    text = "1000",
    onTextLayout = { totalPageTextWidth = it.size.width }
)
Text(
    text = "1",
    modifier = widthModifier
)
Related