在 Jetpack Compose 中为文本指定最少行数

Yan*_*ick 6 android android-jetpack-compose

出于各种原因,aText应该始终至少具有等于x文本行的高度,无论它的文本行数是否少于 x 行。在TextBasicTextComposable组件只有一个maxLines参数,但没有minLines

我尝试了以下(x = 3):

Text(
    modifier = Modifier.sizeIn(minHeight = with(LocalDensity.current) {
       (42*3).sp.toDp()
    }),
    color = MaterialTheme.colors.onPrimary,
    text = "Sample", textAlign = TextAlign.Center,
    style = MaterialTheme.typography.h2 /* fontSize = 42 */,
    lineHeight = 42.sp
)
Run Code Online (Sandbox Code Playgroud)

结果高度小于如果文本包含 3 行

回到 View World Android,我们可以简单地使用minLines=3,我们如何在 Jetpack Compose 中实现这一点?

Spa*_*atz 12

您的代码几乎是正确的,只需将lineHeight设置为fontSize*4/3

var lineHeight = MaterialTheme.typography.h2.fontSize*4/3

Text(
    modifier = Modifier.sizeIn(minHeight = with(LocalDensity.current) {
       (lineHeight*3).toDp()
    }),
    color = MaterialTheme.colors.onPrimary,
    text = "Sample", textAlign = TextAlign.Center,
    style = MaterialTheme.typography.h2,
    lineHeight = lineHeight
)
Run Code Online (Sandbox Code Playgroud)

但是您可以使用onTextLayout回调执行类似的操作,而无需进行计算:

fun main() = Window {
    var text by remember { mutableStateOf("Hello, World!") }
    var lines by remember { mutableStateOf(0) }

    MaterialTheme {
        Button(onClick = {
            text += "\nnew line"
        }) {
            Column {
                Text(text,
                    maxLines = 5,
                    style = MaterialTheme.typography.h2,
                    onTextLayout = { res -> lines = res.lineCount })
                for (i in lines..2) {
                    Text(" ", style = MaterialTheme.typography.h2)
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Gab*_*tti 9

从 M21.4.0-alpha02和 M3开始,1.1.0-alpha02您可以在以下位置使用该minLines属性Text

   Text(
       text = "MinLines = 3",
       modifier = Modifier.fillMaxWidth().background(Yellow),
       minLines = 3
   )
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

请注意,这minLines是以最小可见线数表示的最小高度。要求1 <= minLines <= maxLines.

您可以将其与 M2 和 M3 一起使用。

  • 仅供参考:此功能请求的谷歌跟踪器 https://issuetracker.google.com/issues/122476634 (2认同)

Rar*_*rap 7

当我们等待 Google 实现此功能时,您可以使用以下解决方法:

@Preview
@Composable
fun MinLinesPreview() {
    lateinit var textLayoutResult: TextLayoutResult

    val text = "Title\ntitle\nTITLE\nTitle"
//    val text = "title\ntitle\ntitle\ntitle"
//    val text = "title\ntitle"
//    val text = "title"

    Text(
        modifier = Modifier.fillMaxWidth(),
        text = text.addEmptyLines(3), // ensures string has at least N lines,
        textAlign = TextAlign.Center,
        maxLines = 4,
    )
}

fun String.addEmptyLines(lines: Int) = this + "\n".repeat(lines)
Run Code Online (Sandbox Code Playgroud)

现在,Text无论字符串内容如何,​​您的高度都相同:

1 行文本高度 2行文字高度 4行文字高度 文本高度为 4 行,带大写锁定

Text这个解决方案比根据行高计算 的底部偏移要容易得多onTextLayout(剧透:开始、中心和最后一行具有不同的高度)