Text 组件入门:创建文本、样式设置、字体与颜色、行高与对齐测试
在 Jetpack Compose 中,Text 是最基础、最常用的组件,负责在界面上显示静态或动态文本。与 Android View 系统中的 TextView 不同,Compose 的 Text 采用声明式 API,所有样式属性通过参数直接传入,无需 XML 或 findView。本章将带你从零上手:创建文本、设置字体/颜色/行高/对齐,并通过可运行代码和结构图理解其工作方式。
1.1 创建文本
调用 Text 函数,传入一个字符串,即可在屏幕上渲染文字:
@Composable
fun SimpleText() {
Text(text = "Hello, Compose!")
}
如果需要根据状态动态更新文本,只需改变传入的字符串:
@Composable
fun DynamicText() {
var counter by remember { mutableIntStateOf(0) }
Column {
Text(text = "点击次数:$counter")
Button(onClick = { counter++ }) {
Text("增加")
}
}
}
1.2 样式设置
Text 的样式通过 style 参数控制,内部为 TextStyle 对象。常用样式属性包括:
| 属性 | 类型 | 说明 | 默认值 |
|---|---|---|---|
fontSize |
TextUnit |
字体大小,常用 sp 单位 |
16.sp |
fontWeight |
FontWeight |
字重,如 Bold、Normal |
FontWeight.Normal |
fontStyle |
FontStyle |
斜体或正常 | FontStyle.Normal |
fontFamily |
FontFamily |
字体族,如 Serif、SansSerif |
FontFamily.Default |
color |
Color |
文字颜色 | Color.Unspecified(由主题决定) |
lineHeight |
TextUnit |
行高,影响多行文本行间距 | 随字体大小自适应 |
textAlign |
TextAlign |
水平对齐方式 | TextAlign.Start |
示例:同时设置多个样式属性:
@Composable
fun StyledText() {
Text(
text = "样式组合测试",
style = TextStyle(
fontSize = 20.sp,
fontWeight = FontWeight.Bold,
fontStyle = FontStyle.Italic,
fontFamily = FontFamily.Serif,
color = Color(0xFF2E86C1),
lineHeight = 28.sp,
textAlign = TextAlign.Center
),
modifier = Modifier.fillMaxWidth()
)
}
1.3 字体与颜色
字体通过 fontFamily 指定,可以引用系统字体或自定义字体。颜色使用 Color 类的工厂方法或十六进制值:
// 系统字体族
Text("Serif 字体", fontFamily = FontFamily.Serif)
Text("Monospace 字体", fontFamily = FontFamily.Monospace)
// 自定义字体(需将字体文件放入 res/font)
val customFont = FontFamily(Font(R.font.my_custom_font))
Text("自定义字体", fontFamily = customFont)
// 颜色使用
Text("红色文字", color = Color.Red)
Text("半透明蓝", color = Color(0x800000FF)) // ARGB
提示: Compose 中
Color.Unspecified 表示不覆盖主题颜色;若显式指定 color,会覆盖 Material Design 主题的默认文本颜色。1.4 行高与对齐
行高(lineHeight) 控制多行文本的行间距。当文本只有一行时,行高不影响布局,但会参与基线对齐计算。示例:
Text(
text = "第一行\n第二行\n第三行",
style = TextStyle(lineHeight = 40.sp, fontSize = 18.sp)
)
对齐(textAlign) 作用于文本在容器宽度内的水平位置。常用值:Start、End、Center、Justify。注意:Justify 仅在多行文本且宽度固定时生效。
常见错误: 在
Text 上直接使用 Modifier.align() 并不能控制文本对齐,textAlign 才是正确方式。另外,lineHeight 的单位必须与 fontSize 一致(推荐 sp)。1.5 Text 组件内部结构示意
下面这张结构图展示了 Text 组件的参数分层与数据流向。从最外层 Compose 函数到最终渲染的文本栅格,每个参数通过 TextStyle 组装,最终由 Paint 和 Canvas 绘制。
1.6 完整测试代码
将以下代码复制到 Composable 函数中,即可预览所有基本属性效果:
@Composable
fun TextDemo() {
Column(
modifier = Modifier
.padding(16.dp)
.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
Text("默认文本")
Text("蓝色粗体 Serif", style = TextStyle(
color = Color(0xFF2E86C1),
fontWeight = FontWeight.Bold,
fontFamily = FontFamily.Serif
))
Text("居中 + 行高 36sp",
style = TextStyle(lineHeight = 36.sp),
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth()
)
Text("红色斜体", color = Color.Red, fontStyle = FontStyle.Italic)
}
}
调试提示: 若文本不显示或显示异常,请检查:①
text 参数是否非空;② 是否在 Column 或 Box 等父容器中(否则可能不可见);③ 如果使用自定义字体,确认字体文件路径和 FontFamily 注册正确。