You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Jetpack Compose中如何让Text组件仅显示最后3行文本?

Jetpack Compose 实现Text始终展示最后3行、对齐底部方案

以下两种方案可根据你的使用场景选择:

方案1:文本裁剪方案(适配动态高度场景)

不需要给Text设置固定高度,文本更新时自动裁剪只保留最后3行内容:

val maxShowLines = 3
var finalText by remember { mutableStateOf(originText) }

Text(
    text = finalText,
    maxLines = maxShowLines,
    onTextLayout = { layoutResult ->
        val totalLines = layoutResult.lineCount
        if (totalLines > maxShowLines) {
            // 取倒数第maxShowLines行的起始位置,裁剪前面的内容
            val startCharIndex = layoutResult.getLineStart(totalLines - maxShowLines)
            finalText = originText.substring(startCharIndex)
        } else {
            finalText = originText
        }
    },
    modifier = Modifier.fillMaxWidth()
)

方案2:自定义布局对齐方案(适配固定高度场景)

如果你的Text容器有固定高度,不需要修改文本内容,直接通过自定义布局实现和TextView android:gravity="bottom" 完全一致的效果,内容超出时自动裁剪顶部内容、始终展示底部3行:

val fixedTextHeight = 120.dp // 替换为你的Text容器实际高度
val maxShowLines = 3

Layout(
    content = {
        Text(
            text = originText,
            maxLines = maxShowLines,
            modifier = Modifier.fillMaxWidth()
        )
    },
    modifier = Modifier.height(fixedTextHeight)
) { measurables, constraints ->
    val textPlaceable = measurables.first().measure(constraints)
    layout(constraints.maxWidth, constraints.maxHeight) {
        // 文本坐标靠底部对齐
        val offsetY = constraints.maxHeight - textPlaceable.height
        textPlaceable.place(x = 0, y = offsetY.coerceAtLeast(0))
    }
}

注意事项

  • 动态更新文本时只需修改originText即可,两种方案都会自动调整展示内容
  • 若需要保留省略号,可在裁剪文本时自行在头部添加省略号标记

内容的提问来源于stack exchange,提问作者Quontas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 23:57:02