Jetpack Compose: Find how many lines a text will take before composition

Viewed 861

I am trying to determine how many lines a certain text will occupy on the screen before composition. Is there a way to do this?

2 Answers

You can use onTextLayout on Text to get line count and some other features.

var lineCount = 1
Text(text= "", onTextLayout = {textLayoutResult: TextLayoutResult ->
    lineCount = textLayoutResult.lineCount
})

While the accepted answer is correct there is an alternative way, which doesn't even require a Composable function:

val paragraph = androidx.compose.ui.text.Paragraph(
    text = "Foo",
    style = MaterialTheme.typography.body1,
    constraints = Constraints(maxWidth = maxWidthInPx),
    density = LocalDensity.current,
    fontFamilyResolver = LocalFontFamilyResolver.current,
)
paragraph.lineCount

This might be better suited if it's required to know the lineCount beforehand.

Related