由于各种原因,Text
应始终至少具有等于 x
的高度文本行,无论它是否少于 x 行文本。 Text
和 BasicText
可组合项只有 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
)
结果高度小于文本包含 3 行时的高度回到 View World Android,我们可以简单地使用
minLines=3
,我们如何在 Jetpack Compose 中实现这一点?
最佳答案
您的代码几乎是正确的,只需设置 线高 至字体大小*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
)
但是您可以使用 进行类似的操作而无需计算。 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)
}
}
}
}
}
关于android - 为 Jetpack Compose 中的文本指定最少行数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66394624/