Text
Compose 中的Text ,对标TextView
Text属性列表
属性 | 作用 | 示例 |
---|---|---|
text | 文本内容 | "普通文本" |
fontSize | 字体大小 | 20.sp |
fontFamily | 字体 | FontFamily.SasSerif |
fontStyle | 字体样式 | FontStyle.Italic(斜体) |
fontWeight | 字体粗细 | FontWeight.Medium |
letterSpacing | 字符间距 | TextUnit.Sp(10) |
textAlign | text显示样式 | TextAlign.Justify(拉伸填充整个容器) |
maxLines | 最大显示行数 | 10 |
textDecoration | 划线样式 | TextDecoration.Underline(下划线),TextDecoration.LineThrough(中划线) |
style | text样式 | TextStyle.Default |
onTextLayout | 文本计算完成回调 | {} |
overflow | 文本溢出样式 | TextOverflow.Ellipsis |
上述属性中text除了可以直接设置一个字符串,还可以通过AnnotatedString类来进行构建文本内容实现一个Text中显示不同大小字体和不同颜色的文本
AnnotatedString代码示例:
AnnotatedString.Builder().run {
pushStyle(
SpanStyle(
color = Color.Blue,
fontSize = 30.sp,
fontStyle = FontStyle.Italic,
fontFamily = FontFamily.Cursive
)
)
append("四大名著")
pop()//取消上面修改的样式对下文本的影响
append("水浒传")
append("三国演义")
append("红楼梦")
append("西游记")
toAnnotatedString()
}
Text 代码示例:
class TextActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ShowText()
}
}
@Composable
fun ShowText() {
Text(
fontStyle = FontStyle.Italic,//设置字体 Normal 是正常,Italic 斜体
text = AnnotatedString.Builder().run {
pushStyle(
SpanStyle(
color = Color.Blue,
fontSize = 30.sp,
fontStyle = FontStyle.Italic,
fontFamily = FontFamily.Cursive
)
)
append("四大名著")
pop()//取消上面修改的样式对下文本的影响
append("水浒传")
append("三国演义")
append("红楼梦")
append("西游记")
toAnnotatedString()
}, //显示的内容
color = Color.Yellow, //text颜色
modifier = Modifier
.padding(10.dp)
.fillMaxWidth()
.height(100.dp)
.background(color = Color.Red)
.alpha(1f)
.clickable(onClick = {
toast("hello")
}),
fontSize = 20.sp,//字体大小
fontFamily = FontFamily.SansSerif,//修改字体
fontWeight = FontWeight.Medium,//修改字重(字体粗细)
letterSpacing = TextUnit.Sp(10),//字符间距
textAlign = TextAlign.Justify,//Justify 拉伸填充整个容器, Start Left 左对齐 End Right 右对齐
maxLines = 10,//最大行数
textDecoration = TextDecoration.Underline,//LineThrough 中间划线 Underline 下划线
style = TextStyle.Default,//text样式
onTextLayout = {
},//计算完成回调
overflow = TextOverflow.Ellipsis
)
}
}
效果展示:
Mi8 屏幕指纹版 MIUI12 稳定版(显示效果符合预期)

Mi8 MIUI12 开发版(显示效果FontStyle.Italic,字体倾斜无效)

网友评论