鸿蒙Harmony实战开发教学(No.3)-Text组件基础到高阶介绍篇
·
鸿蒙系统Text组件全面解析:从基础到高阶应用
本文基于鸿蒙官方文档最新版本,按照API分类详细解析Text组件的完整使用方法,每个API都配有具体示例和实际应用场景。
快速指引-往期鸿蒙实战系列文档合集
前言
在鸿蒙应用开发中,Text组件是最基础也是最常用的UI组件之一。从API version 7开始支持,后续版本不断新增功能特性。本文将先罗列所有API,再逐一详细讲解每个API的用法和注意事项。
📑 目录导航
一、Text组件API完整列表
1.1 基础API概览
根据鸿蒙官方文档,Text组件提供以下主要API:
文本内容与初始化:
Text(content?: string | Resource, value?: TextOptions)- 构造函数TextOptions- 初始化参数对象TextController- 文本控制器
布局与对齐API:
textAlign(value: TextAlign)- 水平对齐textVerticalAlign(value: Optional<TextVerticalAlign>)- 垂直对齐(API 20+)maxLines(value: number)- 最大行数lineHeight(value: number | string | Resource)- 行高设置
字体样式API:
fontSize(value: number | string | Resource)- 字体大小fontColor(value: ResourceColor)- 字体颜色fontWeight(value: number | FontWeight | ResourceStr)- 字体粗细fontStyle(value: FontStyle)- 字体样式fontFamily(value: string | Resource)- 字体家族textCase(value: TextCase)- 文本大小写
文本效果API:
letterSpacing(value: number | ResourceStr)- 字符间距decoration(value: DecorationStyleInterface)- 文本装饰线textShadow(value: ShadowOptions | Array<ShadowOptions>)- 文本阴影shaderStyle(value: ShaderStyle)- 渐变效果(API 20+)
文本溢出处理API:
textOverflow(options: TextOverflowOptions)- 溢出处理ellipsisMode(value: EllipsisMode)- 省略位置(API 12+)marqueeOptions(options: Optional<TextMarqueeOptions>)- 跑马灯配置(API 18+)
交互功能API:
copyOption(value: CopyOptions)- 复制选项textSelectable(mode: TextSelectableMode)- 文本选择draggable(value: boolean)- 拖拽功能enableDataDetector(enable: boolean)- 实体识别enableHapticFeedback(isEnabled: boolean)- 触觉反馈
高级特性API:
baselineOffset(value: number | ResourceStr)- 基线偏移minFontSize(value: number | string | Resource)- 最小字号maxFontSize(value: number | string | Resource)- 最大字号fontFeature(value: string)- 字体特性privacySensitive(supported: boolean)- 隐私敏感(API 12+)
二、API详细解析与示例
2.1 letterSpacing - 字符间距设置
API定义:
letterSpacing(value: number | ResourceStr): TextAttribute
参数说明:
value: 字符间距值,支持数字或资源字符串- 默认值: 0
- 单位: fp
- 支持版本: API 9+
基础用法示例:
// 设置固定间距
Text('鸿蒙开发').letterSpacing(2)
// 使用字符串单位
Text('HarmonyOS').letterSpacing('1vp')
// 负值效果(文字压缩)
Text('压缩文本').letterSpacing(-1)
实际应用场景:
// 场景1:标题美化
Text('欢迎使用鸿蒙系统')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.letterSpacing(2) // 增加字符间距提升质感
.fontColor('#1A1A1A')
// 场景2:艺术字效果
Text('艺术字')
.fontSize(18)
.letterSpacing(3)
.fontColor('#FF6B35')
.decoration({
type: TextDecorationType.Underline,
color: '#FF6B35',
style: TextDecorationStyle.WAVY
})
// 场景3:多语言适配
Text('Hello 世界')
.fontFamily('HarmonyOS Sans SC')
.letterSpacing(0.5) // 统一中英文间距
注意事项:
- 对每个字符生效,包括行尾字符
- 负值过小时会将组件内容区大小压缩为0
- 设置百分比时按默认值显示
- 支持Resource类型(API 20+)
2.2 textAlign - 水平对齐
API定义:
textAlign(value: TextAlign): TextAttribute
参数说明:
value: 对齐方式枚举- 默认值: TextAlign.Start
- Wearable默认: TextAlign.Center
对齐方式枚举:
enum TextAlign {
Start = 0, // 起始对齐
Center = 1, // 居中对齐
End = 2, // 末尾对齐
JUSTIFY = 3 // 两端对齐
}
使用示例:
// 起始对齐(默认)
Text('起始对齐文本').textAlign(TextAlign.Start)
// 居中对齐
Text('居中对齐文本').textAlign(TextAlign.Center)
// 末尾对齐
Text('末尾对齐文本').textAlign(TextAlign.End)
// 两端对齐(需要配合wordBreak)
Text('两端对齐文本').textAlign(TextAlign.JUSTIFY)
实际应用:
// 新闻标题居中对齐
Text('华为发布鸿蒙5.0系统')
.textAlign(TextAlign.Center)
.fontSize(20)
.fontWeight(FontWeight.Bold)
// 价格右对齐显示
Text('¥1999')
.textAlign(TextAlign.End)
.fontSize(24)
.fontColor('#FF6B35')
2.3 textOverflow + maxLines - 文本溢出处理
API定义:
textOverflow(options: TextOverflowOptions): TextAttribute
maxLines(value: number): TextAttribute
溢出处理方式:
TextOverflow.None- 不处理溢出TextOverflow.Clip- 截断显示TextOverflow.Ellipsis- 显示省略号TextOverflow.MARQUEE- 跑马灯效果
使用示例:
// 显示省略号
Text('超长文本内容...')
.maxLines(2)
.textOverflow({ overflow: TextOverflow.Ellipsis })
// 截断显示
Text('超长文本内容...')
.maxLines(2)
.textOverflow({ overflow: TextOverflow.Clip })
// 跑马灯效果
Text('需要滚动的长文本...')
.textOverflow({ overflow: TextOverflow.MARQUEE })
.marqueeOptions({
start: true,
step: 4.0,
loop: -1
})
2.4 copyOption + textSelectable - 文本选择复制
API定义:
copyOption(value: CopyOptions): TextAttribute
textSelectable(mode: TextSelectableMode): TextAttribute
复制选项枚举:
enum CopyOptions {
None = 0, // 不可复制
InApp = 1, // 应用内复制
LocalDevice = 2, // 本地设备复制
CROSS_DEVICE = 3 // 跨设备复制
}
选择模式枚举:
enum TextSelectableMode {
UNSELECTABLE = 0, // 不可选择
SELECTABLE_UNFOCUSABLE = 1, // 可选择但不可获焦
SELECTABLE_FOCUSABLE = 2 // 可选择且可获焦
}
使用示例:
// 基础复制功能
Text('可复制文本')
.copyOption(CopyOptions.LocalDevice)
.textSelectable(TextSelectableMode.SELECTABLE_FOCUSABLE)
// 带回调的复制功能
Text('带回调的文本')
.copyOption(CopyOptions.InApp)
.onCopy((value: string) => {
console.info('复制的内容:', value)
})
// 设置选中区域
Text('预设选中文本')
.selection(5, 10) // 选中第5-10个字符
.copyOption(CopyOptions.LocalDevice)
2.5 fontSize + fontColor + fontWeight - 字体样式控制
API定义:
fontSize(value: number | string | Resource): TextAttribute
fontColor(value: ResourceColor): TextAttribute
fontWeight(value: number | FontWeight | ResourceStr): TextAttribute
字体大小单位:
- 默认单位:fp
- Wearable默认:15fp
- 其他设备默认:16fp
字体粗细设置:
// 数字设置(100-900,间隔100)
Text('字体粗细').fontWeight(700)
// 枚举设置
Text('字体粗细').fontWeight(FontWeight.Bold)
// 字符串设置
Text('字体粗细').fontWeight('bold')
使用示例:
// 完整的字体样式控制
Text('完整的字体样式')
.fontSize(18) // 字体大小
.fontColor('#333333') // 字体颜色
.fontWeight(FontWeight.Bold) // 字体粗细
.fontStyle(FontStyle.Italic) // 字体样式
.fontFamily('HarmonyOS Sans') // 字体家族
// 响应式字体设置
@State currentFontSize: number = 16
Text('动态字体大小')
.fontSize(this.currentFontSize)
.onClick(() => {
this.currentFontSize += 2 // 点击增大字体
})
2.6 decoration - 文本装饰线
API定义:
decoration(value: DecorationStyleInterface): TextAttribute
装饰线样式接口:
interface DecorationStyleInterface {
type: TextDecorationType; // 装饰线类型
color: ResourceColor; // 颜色
style: TextDecorationStyle; // 样式
}
装饰线类型枚举:
enum TextDecorationType {
None = 0, // 无装饰线
Underline = 1, // 下划线
Overline = 2, // 上划线
LineThrough = 3 // 删除线
}
装饰线样式枚举:
enum TextDecorationStyle {
SOLID = 0, // 实线
DOTTED = 1, // 点线
DASHED = 2, // 虚线
WAVY = 3 // 波浪线
}
使用示例:
// 下划线效果
Text('下划线文本')
.decoration({
type: TextDecorationType.Underline,
color: Color.Red,
style: TextDecorationStyle.SOLID
})
// 删除线效果(原价显示)
Text('¥1999')
.decoration({
type: TextDecorationType.LineThrough,
color: '#999999',
style: TextDecorationStyle.SOLID
})
// 波浪线上划线
Text('重点内容')
.decoration({
type: TextDecorationType.Overline,
color: '#FF6B35',
style: TextDecorationStyle.WAVY
})
2.7 textShadow - 文本阴影效果
API定义:
textShadow(value: ShadowOptions | Array<ShadowOptions>): TextAttribute
阴影选项接口:
interface ShadowOptions {
radius: number; // 阴影半径
color: ResourceColor; // 阴影颜色
offsetX: number; // X轴偏移
offsetY: number; // Y轴偏移
}
使用示例:
// 单层阴影
Text('阴影效果')
.textShadow({
radius: 10,
color: Color.Black,
offsetX: 2,
offsetY: 2
})
// 多重阴影(API 11+)
Text('多重阴影')
.textShadow([
{
radius: 5,
color: Color.Red,
offsetX: 2,
offsetY: 2
},
{
radius: 10,
color: Color.Blue,
offsetX: -2,
offsetY: -2
}
])
三、高级API特性解析
3.1 marqueeOptions - 跑马灯效果(API 18+)
API定义:
marqueeOptions(options: Optional<TextMarqueeOptions>): TextAttribute
跑马灯选项:
interface TextMarqueeOptions {
start: boolean; // 是否开始播放
step: number; // 滚动步长(默认4.0vp)
loop: number; // 循环次数(-1为无限)
fromStart: boolean; // 从头开始滚动
delay: number; // 时间间隔(毫秒)
fadeout: boolean; // 渐隐效果
marqueeStartPolicy: MarqueeStartPolicy; // 启动策略
}
使用示例:
// 基础跑马灯
Text('需要滚动的长文本内容...')
.textOverflow({ overflow: TextOverflow.MARQUEE })
.marqueeOptions({
start: true,
step: 4.0,
loop: -1,
fromStart: true,
delay: 0,
fadeout: false
})
// 带状态监听的跑马灯
Text('带监听的跑马灯文本...')
.textOverflow({ overflow: TextOverflow.MARQUEE })
.marqueeOptions({
start: true,
step: 6.0,
loop: 3
})
.onMarqueeStateChange((state: MarqueeState) => {
switch (state) {
case MarqueeState.START:
console.info('跑马灯开始')
break
case MarqueeState.BOUNCE:
console.info('完成一次滚动')
break
case MarqueeState.FINISH:
console.info('跑马灯结束')
break
}
})
3.2 enableDataDetector - 实体识别(API 11+)
API定义:
enableDataDetector(enable: boolean): TextAttribute
dataDetectorConfig(config: TextDataDetectorConfig): TextAttribute
实体识别配置:
interface TextDataDetectorConfig {
types: TextDataDetectorType[]; // 识别类型
onDetectResultUpdate?: (result: string) => void; // 结果回调
}
使用示例:
// 开启所有实体识别
Text('电话:13800138000,网址:www.example.com')
.enableDataDetector(true)
// 自定义识别类型
Text('特定实体识别')
.enableDataDetector(true)
.dataDetectorConfig({
types: [TextDataDetectorType.PHONE_NUMBER, TextDataDetectorType.URL],
onDetectResultUpdate: (result) => {
console.info('识别结果:', result)
}
})
3.3 privacySensitive - 隐私敏感信息(API 12+)
API定义:
privacySensitive(supported: boolean): TextAttribute
使用示例:
// 隐私敏感信息(手机号)
Text('138****8888')
.privacySensitive(true)
.copyOption(CopyOptions.None) // 禁止复制
// 非敏感信息
Text('用户名:张三')
.privacySensitive(false)
.copyOption(CopyOptions.LocalDevice)
四、实战应用场景
4.1 新闻类应用标题实现
// 新闻标题组件
@Component
struct NewsTitle {
private title: string = '华为发布鸿蒙5.0系统:全新分布式体验'
build() {
Text(this.title)
.fontSize(20)
.fontWeight(FontWeight.Medium)
.fontColor('#1A1A1A')
.letterSpacing(0.5)
.lineHeight(28)
.maxLines(2)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.wordBreak(WordBreak.BREAK_WORD)
.copyOption(CopyOptions.LocalDevice)
.margin({ bottom: 8 })
}
}
4.2 电商价格显示组件
// 价格显示组件
@Component
struct PriceDisplay {
private price: number = 1999
private originalPrice: number = 2999
build() {
Column() {
// 当前价格
Text(`¥${this.price}`)
.fontSize(24)
.fontWeight(FontWeight.Bold)
.fontColor('#FF6B35')
.letterSpacing(1)
// 原价(带删除线)
if (this.originalPrice > this.price) {
Text(`¥${this.originalPrice}`)
.fontSize(14)
.fontColor('#999999')
.decoration({
type: TextDecorationType.LineThrough,
color: '#999999',
style: TextDecorationStyle.SOLID
})
}
}
}
}
4.3 聊天应用消息气泡
// 消息气泡组件
@Component
struct MessageBubble {
private message: string = '你好,这是聊天消息内容'
private isMe: boolean = true
build() {
Text(this.message)
.fontSize(16)
.fontColor(this.isMe ? Color.White : Color.Black)
.backgroundColor(this.isMe ? '#007AFF' : '#F0F0F0')
.padding({ left: 12, right: 12, top: 8, bottom: 8 })
.borderRadius(16)
.maxLines(0)
.textAlign(this.isMe ? TextAlign.End : TextAlign.Start)
.margin({
left: this.isMe ? 60 : 12,
right: this.isMe ? 12 : 60
})
}
}
4.4 跑马灯公告组件
// 跑马灯公告组件
@Component
struct MarqueeNotice {
private notice: string = '重要公告:系统将于今晚22:00-24:00进行维护升级,请提前做好准备。'
@State isPlaying: boolean = true
build() {
Row() {
// 公告图标
Image($r('app.media.notice_icon'))
.width(16)
.height(16)
.margin({ right: 8 })
// 跑马灯文本
Text(this.notice)
.fontSize(14)
.fontColor('#FF6B35')
.textOverflow({ overflow: TextOverflow.MARQUEE })
.marqueeOptions({
start: this.isPlaying,
step: 3.0,
loop: -1,
fromStart: true
})
.onClick(() => {
this.isPlaying = !this.isPlaying // 点击暂停/播放
})
}
.padding(12)
.backgroundColor('#FFF8E6')
.borderRadius(8)
}
}
4.5 带阴影的卡片标题
// 带阴影的卡片标题
@Component
struct ShadowCardTitle {
private title: string = '特色功能推荐'
build() {
Text(this.title)
.fontSize(18)
.fontWeight(FontWeight.Bold)
.fontColor('#FFFFFF')
.textShadow({
radius: 8,
color: Color.Black,
offsetX: 2,
offsetY: 2
})
.padding({ left: 16, right: 16, top: 12, bottom: 12 })
.backgroundColor('#4A90E2')
.borderRadius(12)
.width('100%')
}
}
五、性能优化与最佳实践
5.1 文本渲染性能优化
避免频繁重绘:
// 不推荐:每次渲染都重新计算
Text(`当前时间:${new Date().toLocaleTimeString()}`)
.fontSize(16)
// 推荐:使用状态管理
@State currentTime: string = new Date().toLocaleTimeString()
Text(`当前时间:${this.currentTime}`)
.fontSize(16)
// 定时更新
aboutToAppear() {
setInterval(() => {
this.currentTime = new Date().toLocaleTimeString()
}, 1000)
}
合理使用maxLines:
// 限制最大行数,避免文本过长影响性能
Text('长文本内容...')
.maxLines(3)
.textOverflow({ overflow: TextOverflow.Ellipsis })
// 动态行数控制
@State showFullText: boolean = false
Text('长文本内容...')
.maxLines(this.showFullText ? 0 : 3)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.onClick(() => {
this.showFullText = !this.showFullText
})
5.2 内存优化策略
避免字符串拼接:
// 不推荐:频繁字符串拼接
Text('用户:' + this.username + ',积分:' + this.points)
// 推荐:使用模板字符串
Text(`用户:${this.username},积分:${this.points}`)
// 推荐:使用资源文件
Text($r('app.string.welcome_message'))
合理使用资源管理:
// 使用资源引用而非硬编码
Text($r('app.string.app_name'))
.fontSize($r('app.float.title_font_size'))
.fontColor($r('app.color.primary_text'))
// 动态资源切换
@State isDarkMode: boolean = false
Text('主题文本')
.fontColor(this.isDarkMode ?
$r('app.color.dark_text') :
$r('app.color.light_text'))
5.3 兼容性处理
API版本适配:
// 版本兼容性检查
Text('高级功能文本')
.fontSize(16)
.if(apiVersion >= 11, (text: Text) => {
text.enableDataDetector(true)
})
.if(apiVersion >= 12, (text: Text) => {
text.privacySensitive(true)
})
// 条件编译(使用宏)
// #if API_VERSION >= 11
Text('API 11+功能').enableDataDetector(true)
// #endif
设备适配:
// 响应式字体大小
Text('自适应文本')
.fontSize(deviceType === 'phone' ? 16 :
deviceType === 'tablet' ? 18 : 14)
// 使用响应式单位
Text('响应式文本')
.fontSize(16) // 默认fp单位,自动适配
.margin({
top: deviceType === 'phone' ? 8 : 12,
bottom: deviceType === 'phone' ? 8 : 12
})
六、常见问题与解决方案
6.1 文本显示异常问题
文本截断问题:
// 问题:文本被意外截断
Text('长文本内容...').width(100)
// 解决方案:明确设置溢出处理
Text('长文本内容...')
.width(100)
.maxLines(1)
.textOverflow({ overflow: TextOverflow.Ellipsis })
// 或者使用自动换行
Text('长文本内容...')
.width(100)
.wordBreak(WordBreak.BREAK_WORD)
字体渲染问题:
// 问题:字体显示异常
Text('特殊字体文本').fontFamily('CustomFont')
// 解决方案:字体回退机制
Text('特殊字体文本')
.fontFamily('CustomFont, HarmonyOS Sans, sans-serif')
// 或者使用系统字体
Text('系统字体文本')
.fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
6.2 交互功能问题
复制功能失效:
// 问题:复制功能不生效
Text('可复制文本').copyOption(CopyOptions.LocalDevice)
// 解决方案:确保文本可选择
Text('可复制文本')
.copyOption(CopyOptions.LocalDevice)
.textSelectable(TextSelectableMode.SELECTABLE_FOCUSABLE)
// 添加复制回调
Text('带回调的文本')
.copyOption(CopyOptions.LocalDevice)
.onCopy((value: string) => {
promptAction.showToast({ message: `已复制:${value}` })
})
点击事件冲突:
// 问题:复制与点击事件冲突
Text('多功能文本')
.onClick(() => { /* 点击处理 */ })
.copyOption(CopyOptions.LocalDevice)
// 解决方案:合理处理事件优先级
Text('多功能文本')
.copyOption(CopyOptions.LocalDevice)
.onClick(() => {
// 短点击处理,不影响长按复制
})
.onLongPress(() => {
// 长按触发复制菜单
})
七、总结与最佳实践
7.1 关键要点总结
- letterSpacing属性:合理使用提升可读性,注意负值压缩效果
- 文本溢出处理:正确组合maxLines和textOverflow实现各种显示效果
- 多语言适配:使用enableAutoSpacing和合适的字体家族
- 性能优化:合理使用文本选择、跑马灯等高级功能
- 兼容性考虑:注意不同API版本的特性支持情况
7.2 版本兼容性指南
| 特性 | 支持版本 | 注意事项 |
|---|---|---|
| letterSpacing | API 9+ | 支持Resource类型(API 20+) |
| textVerticalAlign | API 20+ | 垂直对齐新特性 |
| marqueeOptions | API 18+ | 跑马灯完整配置 |
| enableAutoSpacing | API 20+ | 中西文自动间距 |
| shaderStyle | API 20+ | 文本渐变效果 |
如果你觉得这篇文章够详细,可以一键三连(关注不迷路,收藏留备用,你的点赞是我持续更新的动力),后续Text组件开发过程中可直接参考,提升开发效率。若有技术疑问,可在评论区留言,我将针对新手常见问题进行详细解答。
更多推荐

所有评论(0)