Jetpack Compose 深入浅出(二)——基础组件Text

在 Jetpack Compose 中,Text 是最基础也最常用的组件之一,用于在界面上显示文本内容。它提供了丰富的属性来定制文本的外观和行为,下面详细介绍其用法和关键属性:

1. 基本用法

最简化的使用方式只需传入文本内容:

scss 复制代码
Text("Hello, Jetpack Compose!")

也可以结合资源使用(推荐做法):

kotlin

vbnet 复制代码
Text(text = stringResource(id = R.string.app_name))

2. 核心属性详解

(1)文本内容相关

  • text: 要显示的文本内容(必填),类型为 StringAnnotatedString(富文本)

    scss 复制代码
    Text(text = "基础文本")
    
    // 富文本示例(带标注的文本)
    val annotatedText = buildAnnotatedString {
        append("这是")
        withStyle(style = SpanStyle(color = Color.Red, fontWeight = FontWeight.Bold)) {
            append("红色粗体")
        }
        append("文本")
    }
    Text(text = annotatedText)

(2)样式相关

  • style: 文本样式,类型为 TextStyle,用于统一设置字体、大小、颜色等

    kotlin

    ini 复制代码
    Text(
        text = "自定义样式",
        style = TextStyle(
            color = Color.Blue,
            fontSize = 20.sp,
            fontWeight = FontWeight.Bold,
            fontStyle = FontStyle.Italic,
            textDecoration = TextDecoration.Underline, // 下划线
            fontFamily = FontFamily.Serif, // 字体家族
            letterSpacing = 2.sp, // 字间距
            lineHeight = 30.sp // 行高
        )
    )
  • color: 文本颜色(可单独设置,优先级低于 TextStyle 中的 color

    ini 复制代码
    Text(text = "红色文本", color = Color.Red)
  • fontSize: 字体大小(需用 sp 单位,适配用户字体缩放设置)

    ini 复制代码
    Text(text = "20sp 字体", fontSize = 20.sp)
  • fontWeight: 字重(粗细),可选值:FontWeight.Normal(400)、Bold(700)等

    ini 复制代码
    Text(text = "粗体文本", fontWeight = FontWeight.Bold)
  • fontStyle: 字体样式,可选 FontStyle.NormalItalic(斜体)

    ini 复制代码
    Text(text = "斜体文本", fontStyle = FontStyle.Italic)

(3)布局相关

  • modifier: 修饰符,用于控制尺寸、边距、对齐等布局行为

    less 复制代码
    Text(
        text = "带边距的文本",
        modifier = Modifier
            .padding(16.dp) // 内边距
            .background(Color.LightGray) // 背景色
            .width(200.dp) // 宽度
    )
  • textAlign: 文本对齐方式,相对于父容器,可选 TextAlign.LeftCenterRight

    ini 复制代码
    Text(
        text = "居中对齐",
        textAlign = TextAlign.Center,
        modifier = Modifier.fillMaxWidth() // 占满宽度才能看到效果
    )
  • maxLines: 最大显示行数,超出部分会被截断

    ini 复制代码
    Text(
        text = "这是一段很长的文本...",
        maxLines = 2,
        overflow = TextOverflow.Ellipsis // 超出部分显示省略号
    )
  • overflow: 文本溢出时的处理方式,可选 TextOverflow.Clip(截断)、Ellipsis(省略号)、Visible(强制显示)

(4)交互相关

  • onClick: 点击事件(需设置 modifier.clickable 或直接使用该参数,Compose 1.4+ 支持)

    ini 复制代码
    Text(
        text = "可点击文本",
        modifier = Modifier.clickable { 
            // 处理点击事件
        }
    )
  • softWrap: 是否自动换行,默认 true;设为 false 时文本会单行显示并可能溢出

    ini 复制代码
    Text(text = "不自动换行的文本内容...", softWrap = false)

3. 高级用法

(1)使用 Material 主题样式

推荐通过主题统一管理文本样式,保持应用风格一致:

ini 复制代码
Text(
    text = "标题文本",
    style = MaterialTheme.typography.headlineMedium
)
Text(
    text = "正文文本",
    style = MaterialTheme.typography.bodyLarge
)

(2)支持多种语言和格式化

结合 stringResource 支持多语言和占位符:

xml

xml 复制代码
<!-- strings.xml -->
<string name="welcome_message">欢迎,%1$s!您有 %2$d 条消息</string>
arduino 复制代码
Text(
    text = stringResource(
        id = R.string.welcome_message,
        "张三", // 替换 %1$s
        5 // 替换 %2$d
    )
)

(3)富文本与标注

使用 AnnotatedString 实现复杂文本效果(如部分文本点击、颜色不同):

kotlin

ini 复制代码
val annotatedText = buildAnnotatedString {
    append("点击")
    // 添加可点击的文本片段
    pushStringAnnotation(tag = "URL", annotation = "https://example.com")
    withStyle(style = SpanStyle(color = Color.Blue, textDecoration = TextDecoration.Underline)) {
        append("这里")
    }
    pop()
    append("访问网站")
}

Text(
    text = annotatedText,
    modifier = Modifier.clickable {
        // 处理点击事件(需解析标注)
        val annotations = annotatedText.getStringAnnotations(
            tag = "URL",
            start = 0,
            end = annotatedText.length
        )
        annotations.firstOrNull()?.let { annotation ->
            // 打开链接等操作
        }
    }
)

4. 注意事项

  • 字体大小必须使用 sp 单位(20.sp),确保支持用户的字体缩放设置
  • 文本颜色尽量使用主题中的颜色(MaterialTheme.colorScheme.onSurface),适配深色 / 浅色模式
  • 长文本需设置 maxLinesoverflow,避免布局异常
  • 复杂文本效果优先考虑 AnnotatedString,而非多个 Text 组件拼接

通过灵活运用 Text 组件的属性,可以满足绝大多数文本展示需求,同时保持代码简洁和可维护性。

相关推荐
千里马学框架1 天前
一起学 Android 14:ShellTransition 屏幕旋转过程深度剖析
android·智能手机·性能优化·framework·性能·屏幕旋转·rotation
美狐美颜SDK开放平台1 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk
AFinalStone1 天前
Android7 SystemUI源码解析(七)Keyguard锁屏模块深度解析
android·systemui
致远ccc2 天前
Google Play 上架前如何测试 App?多国家 Android 环境测试
android·app测试·googleplay·多国家应用测试
ttyyttemo2 天前
Kotlin 协程中的 Job 结构化并发与取消
android
sun0077002 天前
tbox 4g/5g切换,导致wan ip 改变,导致车机旧网络不可用。需要重启车机才行
android
其实防守也摸鱼2 天前
内网穿透与反向代理:原理、工具与实战指南
android·大数据·运维·安全·网络安全·自动化·渗透
AFinalStone2 天前
Android7 SystemUI 源码解析(四)NavigationBar 导航栏与 SystemBars
android·systemui
JMchen2 天前
属性动画原理与高级动画实现
android·kotlin·canvas
AFinalStone2 天前
Android7 SystemUI 源码解析(二)启动流程深度解析
android·systemui