早期我们在 android 中使用 XML 创建UI。现在,可以Google推出了 Jetpack Compose。它是声明式 UI,使开发和设计 UI 变得容易。
本文介绍一个简单的问题:如何在 Compose 中制作拥有样式的文本?
要在 Compose 中创建 TextView,我们使用 Text。
Text(text = "This is text")
Text 可以配置文本的样式,如颜色、字体、行高等。
Text(text = title, fontSize = 20.sp, fontWeight = FontWeight.Bold, lineHeight = 24.sp)
Text 显示富文本(多种样式文本)
在文本中我们常需要显示富文本,如某个词语(如:email地址)可以点击,或者某个词语需要修改颜色,加粗等,以前我们可以用TextView显示HTML内容来实现或使用SpannableString来实现。
与
TextView的SpanableString类似,Jetpack Compose 中使用AnnotatedString实现富文本。
@Composable
fun AnnotatedText() {
val annotatedString = buildAnnotatedString {
append("Hello")
withStyle(style = SpanStyle(Color.Blue)) {
append(" Jetpack Compose")
}
}
Text(text = annotatedString)
}
AnnotatedString 的更多用法将在其他文章中分享。