Jetpack Compose:查找文本在合成之前需要多少行

pax*_*cow 13 android-jetpack-compose

我试图确定某个文本在合成之前将在屏幕上占据多少行。有没有办法做到这一点?

Thr*_*ian 27

您可以使用onTextLayoutonText来获取行数和一些其他功能。

var lineCount = 1
Text(text= "", onTextLayout = {textLayoutResult: TextLayoutResult ->
    lineCount = textLayoutResult.lineCount
})
Run Code Online (Sandbox Code Playgroud)

如果您使用的是 Jetpack Compose 1.4.1 或更高版本,您可以使用 TextMeasurer 来测量您提供的任何样式的文本

    val textMeasurer = rememberTextMeasurer()

    val textToDraw = "Some text to measure\nSomething something"

    val style = TextStyle(
        fontSize = 150.sp,
        color = Color.Black,
        background = Color.Red.copy(alpha = 0.2f)
    )

    // You can get many information since it's TextLayoutResult as in callback
    val textLayoutResult = remember(textToDraw) {
        textMeasurer.measure(textToDraw, style)
    }
Run Code Online (Sandbox Code Playgroud)

  • 在确定文本长度和行数后,我用它将该值发送给子级,没有任何问题。但最好的测试方法是在 onTextLayout、`Modifier.layout{}` 和 `Modifier.drawWithContent` 或 `Modifier.drawBehind{}` 中设置日志,以查看设置的顺序值或阶段 (2认同)

dip*_*dip 5

虽然接受的答案是正确的,但还有一种替代方法,它甚至不需要可组合函数:

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
Run Code Online (Sandbox Code Playgroud)

如果需要事先知道 lineCount,这可能更适合。