找回密码
 立即注册
首页 业界区 业界 鸿蒙应用开发UI基础第十四节:文本显示组件Text核心讲解 ...

鸿蒙应用开发UI基础第十四节:文本显示组件Text核心讲解与实战演示

灼巾 2 小时前
【学习目标】


  • 理解Text组件只读展示的核心定位,明确与可编辑文本组件(TextInput/TextArea)的边界;
  • 掌握Text基础样式、Span混排、排版溢出、交互事件、自适应字号等核心能力及底层规则;
  • 熟练运用Text属性完成样式定制、交互绑定、文本选择等实战开发,解决热搜榜、可复制文本等典型场景问题;
  • 独立实现文本展示的各类个性化、适配性需求。
一、Text组件核心认知

1.1 组件定义与定位

Text是鸿蒙ArkUI中用于展示只读文本的基础UI组件,是界面文字信息的核心载体,与TextInput/TextArea的核心区别是无编辑能力,仅聚焦文本展示,同时具备三大特性:

  • 只读性:仅用于文本展示,无任何编辑、输入能力;
  • 灵活性:支持单行/多行展示、样式定制、多格式混排、基础交互、系统原生文本选择;
  • 适配性:可通过属性控制溢出、行高、对齐、自适应字号,完美适配不同屏幕尺寸。
1.2 典型适用场景

场景类型具体示例核心应用要点静态文本展示页面标题、说明文字、标签基础样式配置 + 排版优化多格式文本展示价格标签、强调文案Span子组件实现多样式混排长文本展示协议内容、商品详情溢出处理 + 1.5~2倍行高优化轻交互文本可点击提示、文本链接交互事件绑定 + 视觉可操作标识可复制文本验证码、链接、编号copyOption配置系统原生选择能力自适应文本卡片动态文案、自适应标题minFontSize/maxFontSize组合适配特殊格式文本热搜榜、状态标签constraintSize + 溢出精准控宽二、工程结构

创建TextApplication工程,基于鸿蒙API 21 / Stage模型,核心目录结构清晰划分页面与功能,便于分模块学习调试:
  1. TextApplication/
  2. ├── AppScope/
  3. │   └── app.json5  // 应用全局配置
  4. ├── entry/
  5. │   ├── src/
  6. │   │   ├── main/
  7. │   │   │   ├── ets/
  8. │   │   │   │   ├── entryability/
  9. │   │   │   │   │   └── EntryAbility.ets  // 应用入口
  10. │   │   │   │   ├── pages/  // 所有功能演示页面
  11. │   │   │   │   │   ├── Index.ets          // 导航主页面(跳转各示例)
  12. │   │   │   │   │   ├── TextBasicPage.ets  // 基础样式演示
  13. │   │   │   │   │   ├── TextSpanPage.ets   // Span混排演示
  14. │   │   │   │   │   ├── TextLayoutPage.ets // 排版与溢出演示
  15. │   │   │   │   │   ├── TextEventPage.ets  // 交互事件演示
  16. │   │   │   │   │   └── TextAdvancedPage.ets // 进阶能力演示
  17. │   │   │   ├── resources/  // 图片、字体等资源目录
  18. │   │   │   └── module.json5  // 模块配置
  19. │   └── build-profile.json5  // 模块构建配置
  20. └── build-profile.json5  // 工程全局构建配置
复制代码
导航主页面(Index.ets)

工程入口页,提供所有功能演示页面的跳转入口:
  1. import { router } from '@kit.ArkUI';
  2. interface RouterButton {
  3.   title: string; // 按钮显示文本(必选)
  4.   url: string;   // 路由跳转路径(必选)
  5. }
  6. @Entry
  7. @Component
  8. struct Index {
  9.   // 跳转按钮配置数组,统一管理所有功能页面
  10.   private buttonList: RouterButton[] = [
  11.     { title: "基础样式", url: 'pages/TextBasicPage' },
  12.     { title: "Span 多格式混排", url: 'pages/TextSpanPage' },
  13.     { title: "排版与溢出处理", url: 'pages/TextLayoutPage' },
  14.     { title: "文本交互事件", url: 'pages/TextEventPage' },
  15.     { title: "进阶能力演示", url: 'pages/TextAdvancedPage' }
  16.   ];
  17.   build() {
  18.     Column({ space: 20 }) {
  19.     Text("文本显示组件Text核心讲解与实战演示")
  20.         .fontSize(20)
  21.         .fontWeight(FontWeight.Bold)
  22.         .margin({ bottom: 40 });
  23.       // 遍历生成跳转按钮,url作为唯一标识避免渲染错乱
  24.       ForEach(
  25.         this.buttonList,
  26.         (item:RouterButton) => {
  27.           Button(item.title)
  28.             .width('80%')
  29.             .height(50)
  30.             .backgroundColor($r('sys.color.brand'))
  31.             .fontColor(Color.White)
  32.             .borderRadius(8)
  33.             .onClick(() => router.pushUrl({ url: item.url }));
  34.         },
  35.         (item:RouterButton) => item.url
  36.       );
  37.     }
  38.     .width('100%')
  39.     .height('100%')
  40.     .justifyContent(FlexAlign.Center)
  41.     .backgroundColor('#F5F5F5');
  42.   }
  43. }
复制代码
运行效果

1.png

三、Text 基础样式配置

基础样式是文本视觉表现的核心,涵盖字体、间距、装饰线、基线偏移等维度。
3.1 核心样式属性解析

属性名功能说明取值规则与最佳实践fontSize设置字体大小12~24fp(24fp适配性差)fontWeight设置字体粗细支持100~900(百为单位),常用Normal(400)、Bold(700)fontColor设置字体颜色优先主题色/十六进制,保证对比度≥4.5:1fontStyle设置字体样式Normal(常规)/Italic(斜体)letterSpacing字符间距-2~4vp(负值重叠、0默认、正值扩大)decoration文本装饰线含type(Underline/LineThrough/Overline)和color子属性baselineOffset文本基线偏移-30~30vp(正值上移做上标,负值下移做下标)textCase大小写转换Normal/LowerCase(全小写)/UpperCase(全大写)3.2 基础样式示例(TextBasicPage.ets)
  1. @Entry
  2. @Component
  3. struct TextBasicPage {
  4.   build() {
  5.     Column({ space: 15}) {
  6.       // 页面标题
  7.       Text("Text 基础样式演示")
  8.         .fontSize(24)
  9.         .fontWeight(FontWeight.Bold)
  10.         .width('100%')
  11.         .textAlign(TextAlign.Center);
  12.       // 1. 基础字体样式(加粗+品牌色+字符间距)
  13.       Text("1. 基础字体样式")
  14.         .fontSize(14)
  15.         .fontColor('#666666')
  16.         .width('90%')
  17.         .margin({ top: 10, bottom: 5 });
  18.       Text("鸿蒙应用开发 - Text 组件")
  19.         .fontSize(18)
  20.         .fontWeight(FontWeight.Bold)
  21.         .fontColor($r('sys.color.brand'))
  22.         .letterSpacing(2)
  23.         .width('90%')
  24.         .padding(10)
  25.         .backgroundColor(Color.White)
  26.         .borderRadius(8);
  27.       // 2. 斜体样式
  28.       Text("2. 斜体 + 字符间距优化")
  29.         .fontSize(14)
  30.         .fontColor('#666666')
  31.         .width('90%')
  32.         .margin({ top: 5, bottom: 5 });
  33.       Text("斜体文本示例 - 字符间距优化")
  34.         .fontStyle(FontStyle.Italic)
  35.         .letterSpacing(2)
  36.         .width('90%')
  37.         .padding(10)
  38.         .backgroundColor(Color.White)
  39.         .borderRadius(8);
  40.       // 3. 文本装饰线(下划线/删除线/上划线)
  41.       Text("3. 文本装饰线")
  42.         .fontSize(14)
  43.         .fontColor('#666666')
  44.         .width('90%')
  45.         .margin({ top: 5, bottom: 5 });
  46.       Row({ space: 20}) {
  47.         // 下划线(链接标识)
  48.         Text("文档链接")
  49.           .fontSize(16)
  50.           .fontColor($r('sys.color.brand'))
  51.           .decoration({ type: TextDecorationType.Underline, color: '#007DFF' });
  52.         // 删除线(原价/失效内容)
  53.         Text("¥1999")
  54.           .fontSize(14)
  55.           .fontColor('#999999')
  56.           .decoration({ type: TextDecorationType.LineThrough, color: '#999999' });
  57.         // 上划线(特殊标记)
  58.         Text("上划线文本")
  59.           .fontSize(16)
  60.           .decoration({ type: TextDecorationType.Overline, color: '#FF9900' });
  61.       }.width('90%')
  62.       .padding(10)
  63.       .backgroundColor(Color.White)
  64.       .borderRadius(8);
  65.       // 4. 基线偏移 + 大小写转换
  66.       Text("4. 基线偏移 + 大小写转换")
  67.         .fontSize(14)
  68.         .fontColor('#666666')
  69.         .width('90%')
  70.         .margin({ top: 10, bottom: 5 });
  71.       Row({ space: 20 }) {
  72.         Text("文本上标").fontSize(16).baselineOffset(15).fontColor($r('sys.color.brand')).backgroundColor(Color.White).padding(8).borderRadius(4);
  73.         Text("文本下标").fontSize(16).baselineOffset(-10).fontColor('#FF3333').backgroundColor(Color.White).padding(8).borderRadius(4);
  74.         Text("lowercase to uppercase").fontSize(16).textCase(TextCase.UpperCase).fontColor('#333333').backgroundColor(Color.White).padding(8).borderRadius(4);
  75.       }
  76.     }
  77.     .backgroundColor('#F5F5F5')
  78.     .width('100%')
  79.     .height('100%')
  80.   }
  81. }
复制代码
运行效果

2.png

四、图文混排


  • Span是Text组件的专属子组件,无独立生命周期,仅能嵌套在Text内使用,核心用于实现单段文本内的多格式混排,是精细化控制文本样式的关键能力。
  • ImageSpan子组件,可实现文本与图片的同行混排,ImageSpan仅支持width、height、verticalAlign三个属性。
4.1 核心规则


  • 继承性:Span默认继承外层Text的所有样式(fontSize、fontColor等);
  • 覆盖性:Span单独设置的样式,会优先覆盖继承的外层Text样式,实现局部定制;
  • 唯一性:仅能嵌套在Text内,无法独立渲染;
  • 交互性:支持onClick事件,文本选择能力继承外层Text的copyOption配置。
4.2 混排与交互示例(TextSpanPage.ets)
  1. import { promptAction } from '@kit.ArkUI';
  2. @Entry
  3. @Component
  4. struct TextSpanPage {
  5.   build() {
  6.     Column({ space: 15}) {
  7.       // 页面标题
  8.       Text("Span 多格式混排演示")
  9.         .fontSize(24)
  10.         .fontWeight(FontWeight.Bold)
  11.         .width('100%')
  12.         .textAlign(TextAlign.Center);
  13.       // 1. 基础多格式混排(继承+覆盖,含ImageSpan)
  14.       Text("1. 基础多格式混排")
  15.         .fontSize(14)
  16.         .fontColor('#666666')
  17.         .width('90%')
  18.         .margin({ bottom: 5 });
  19.       Text() {
  20.         Span("鸿蒙OS ").fontSize(20).fontWeight(FontWeight.Bold).fontColor($r('sys.color.brand')); // 覆盖样式
  21.         Span("是面向万物互联时代的分布式操作系统,").fontSize(16).fontColor('#333333'); // 继承基础样式
  22.         Span("核心特性").fontSize(16).fontWeight(FontWeight.Bold).fontColor('#FF3333'); // 覆盖样式
  23.         Span(":分布式架构、天生流畅、内核安全。").fontSize(16).fontColor('#333333'); // 继承基础样式
  24.         // ImageSpan:文本内图片混排,居中对齐
  25.         ImageSpan($r('app.media.startIcon'))
  26.           .width(30).height(30)
  27.           .verticalAlign(ImageSpanAlignment.CENTER)
  28.       }
  29.       .width('90%')
  30.       .padding(15)
  31.       .backgroundColor(Color.White)
  32.       .borderRadius(8);
  33.       // 2. Span点击事件
  34.       Text("2. Span 点击事件")
  35.         .fontSize(14)
  36.         .fontColor('#666666')
  37.         .width('90%')
  38.         .margin({ top: 15, bottom: 5 });
  39.       Text() {
  40.         Span("点击我触发Span事件")
  41.           .fontSize(18)
  42.           .fontColor($r('sys.color.brand'))
  43.           .fontWeight(FontWeight.Bold)
  44.           .onClick(() => {
  45.             promptAction.showToast({ message: "Span组件被点击!" });
  46.           });
  47.       }
  48.       .width('90%')
  49.       .padding(15)
  50.       .backgroundColor(Color.White)
  51.       .borderRadius(8);
  52.     }
  53.     .padding(15)
  54.     .backgroundColor('#F5F5F5')
  55.     .width('100%')
  56.     .height('100%');
  57.   }
  58. }
复制代码
运行效果

3.png

五、文本排版与溢出处理

文本排版决定了文本在容器内的展示效果,溢出处理则解决了文本超出容器时的展示问题,是长文本展示的核心能力。
5.1 文本排版核心属性


  • textAlign:文本水平对齐方式,支持Start(左对齐,默认)、Center(居中)、End(右对齐)、Justify(两端对齐,仅多行生效);
  • lineHeight:行高(两行文本基线间距),建议为字号的1.5~2倍,提升长文本可读性;
  • TextVerticalAlign(API 20+):文本基线垂直对齐方式,支持BASELINE(基线对齐,默认)、TOP(顶部)、CENTER(居中)、BOTTOM(底部),控制文本自身基线的对齐规则;
  • TextContentAlign(API 21+):文本内容垂直对齐方式,支持TOP(顶部)、CENTER(居中,默认)、BOTTOM(底部),控制文本内容在容器内的垂直对齐规则。
5.2 溢出处理核心属性

属性名功能说明适用场景生效前提maxLines限制文本最大显示行数所有长文本场景(必设)单独配置即可生效textOverflow溢出部分处理方式文本超出容器时的展示控制必须配合maxLines配置constraintSize强制限制文本的最小/最大宽高精准控制文本尺寸(如热搜、标签)单独配置即可生效textOverflow 有四种核心取值,分别适配不同场景:

  • None:无特殊处理(同Clip)
  • Ellipsis:溢出部分显示省略号,内容预览;
  • Marquee:溢出部分滚动显示,该取值仅在maxLines=1时生效,适用于单行重要文本提醒;
  • Clip:溢出部分直接裁剪,无任何标识,简洁展示。
5.3 示例代码(TextLayoutPage.ets)
  1. @Entry
  2. @Component
  3. struct TextLayoutPage {
  4.   build() {
  5.     Scroll(){
  6.       Column({ space: 15}) {
  7.         // 页面标题
  8.         Text("Text 排版与溢出处理")
  9.           .fontSize(24)
  10.           .fontWeight(FontWeight.Bold)
  11.           .width('100%')
  12.           .textAlign(TextAlign.Center);
  13.         // 1. 排版优化(左对齐 + 1.75倍行高)
  14.         Text("1. 排版优化(左对齐 + 1.75倍行高)")
  15.           .fontSize(14)
  16.           .fontColor('#666666')
  17.           .width('90%');
  18.         Text("鸿蒙(HarmonyOS)是华为公司开发的面向万物互联时代的分布式操作系统,旨在为不同设备的智能化、互联与协同提供统一的语言,为消费者提供跨终端的无缝体验。")
  19.           .fontSize(16)
  20.           .textAlign(TextAlign.Start)
  21.           .lineHeight(28)
  22.           .width('90%')
  23.           .padding(10)
  24.           .backgroundColor(Color.White)
  25.           .borderRadius(8);
  26.         // 2. 长文本溢出处理(省略号)
  27.         Text("2. 长文本溢出(最多2行,超出显示省略号)")
  28.           .fontSize(14)
  29.           .fontColor('#666666')
  30.           .width('90%')
  31.           .margin({ top: 10 });
  32.         Text("鸿蒙(HarmonyOS)是华为公司开发的面向万物互联时代的分布式操作系统,旨在为不同设备的智能化、互联与协同提供统一的语言,为消费者提供跨终端的无缝体验。它支持多种设备形态,包括手机、平板、手表、智慧屏等。")
  33.           .fontSize(16)
  34.           .maxLines(2)
  35.           .textOverflow({ overflow: TextOverflow.Ellipsis })
  36.           .width('90%')
  37.           .padding(10)
  38.           .backgroundColor(Color.White)
  39.           .borderRadius(8);
  40.         // 3. 溢出滚动显示(MARQUEE)
  41.         Text("3. 溢出滚动显示(仅单行支持)")
  42.           .fontSize(14)
  43.           .fontColor('#666666')
  44.           .width('90%')
  45.           .margin({ top: 15, bottom: 5 });
  46.         Text("重要通知:鸿蒙应用开发教程更新啦,点击查看详情!")
  47.           .fontSize(16)
  48.           .fontColor('#FF3333')
  49.           .width('90%')
  50.           .maxLines(1)
  51.           .textOverflow({ overflow: TextOverflow.MARQUEE })
  52.           .padding(10)
  53.           .backgroundColor(Color.White)
  54.           .borderRadius(8);
  55.         // 4. 尺寸约束(精准控宽)
  56.         Text("4. 尺寸约束(精准控制最大宽度)")
  57.           .fontSize(14)
  58.           .fontColor('#666666')
  59.           .width('90%')
  60.           .margin({ top: 15, bottom: 5 });
  61.         Text("这是一段被强制限制最大宽度的文本,超出部分显示省略号")
  62.           .fontSize(16)
  63.           .constraintSize({ maxWidth: 200 })
  64.           .maxLines(1)
  65.           .textOverflow({ overflow: TextOverflow.Ellipsis })
  66.           .padding(10)
  67.           .backgroundColor(Color.White)
  68.           .borderRadius(8);
  69.         // 5. 文本对齐方式(水平+垂直基础)
  70.         Text("5. 文本对齐方式(水平+垂直)")
  71.           .fontSize(14)
  72.           .fontColor('#666666')
  73.           .width('90%')
  74.           .margin({ top: 15, bottom: 5 });
  75.         // 5.1 水平对齐(textAlign)
  76.         Text("5.1 水平对齐(textAlign)")
  77.           .fontSize(12)
  78.           .fontColor('#999999')
  79.           .width('90%')
  80.           .margin({ bottom: 5 });
  81.         Column({ space: 5 }) {
  82.           Text("左对齐(默认 Start)")
  83.             .fontSize(14)
  84.             .textAlign(TextAlign.Start)
  85.             .width('100%')
  86.             .padding(8)
  87.             .backgroundColor('#E8F4FD')
  88.             .borderRadius(4);
  89.           Text("居中对齐(Center)")
  90.             .fontSize(14)
  91.             .textAlign(TextAlign.Center)
  92.             .width('100%')
  93.             .padding(8)
  94.             .backgroundColor('#E8F4FD')
  95.             .borderRadius(4);
  96.           Text("右对齐(End)")
  97.             .fontSize(14)
  98.             .textAlign(TextAlign.End)
  99.             .width('100%')
  100.             .padding(8)
  101.             .backgroundColor('#E8F4FD')
  102.             .borderRadius(4);
  103.           Text("两端对齐(Justify,仅多行生效)\n鸿蒙应用开发教程,覆盖从入门到进阶的全流程知识点")
  104.             .fontSize(14)
  105.             .textAlign(TextAlign.JUSTIFY)
  106.             .lineHeight(20)
  107.             .width('100%')
  108.             .padding(8)
  109.             .backgroundColor('#E8F4FD')
  110.             .borderRadius(4);
  111.         }
  112.         .width('90%')
  113.         .backgroundColor(Color.White)
  114.         .padding(10)
  115.         .borderRadius(8);
  116.         // 5.2 垂直基线对齐(TextVerticalAlign,API20+)- 重点设置行高
  117.         Text("5.2 垂直基线对齐(TextVerticalAlign + lineHeight,API20+)")
  118.           .fontSize(12)
  119.           .fontColor('#999999')
  120.           .width('90%')
  121.           .margin({ top: 10, bottom: 5 });
  122.         Row({ space: 8 }) {
  123.           Text("基线对齐")
  124.             .fontSize(14)
  125.             .textVerticalAlign(TextVerticalAlign.BASELINE)
  126.             .lineHeight(40)
  127.             .backgroundColor('#E8F4FD')
  128.             .width('23%')
  129.             .textAlign(TextAlign.Center)
  130.             .borderRadius(4);
  131.           Text("顶部对齐")
  132.             .fontSize(14)
  133.             .textVerticalAlign(TextVerticalAlign.TOP)
  134.             .lineHeight(50) // 统一行高
  135.             .backgroundColor('#E8F4FD')
  136.             .width('23%')
  137.             .textAlign(TextAlign.Center)
  138.             .borderRadius(4);
  139.           Text("居中对齐")
  140.             .fontSize(14)
  141.             .textVerticalAlign(TextVerticalAlign.CENTER)
  142.             .lineHeight(40)
  143.             .backgroundColor('#E8F4FD')
  144.             .width('23%')
  145.             .textAlign(TextAlign.Center)
  146.             .borderRadius(4);
  147.           Text("底部对齐")
  148.             .fontSize(14)
  149.             .textVerticalAlign(TextVerticalAlign.BOTTOM)
  150.             .lineHeight(40)
  151.             .backgroundColor('#E8F4FD')
  152.             .width('23%')
  153.             .textAlign(TextAlign.Center)
  154.             .borderRadius(4);
  155.         }
  156.         .width('90%')
  157.         .height(80) // 仅外层Row设高
  158.         .backgroundColor(Color.White)
  159.         .borderRadius(8);
  160.         // 5.3 文本内容垂直对齐(TextContentAlign,API21+)
  161.         Text("5.3 文本内容垂直对齐(TextContentAlign,API21+)")
  162.           .fontSize(12)
  163.           .fontColor('#999999')
  164.           .width('90%')
  165.           .margin({ top: 10, bottom: 5 });
  166.         Column({ space: 8 }) {
  167.           Text("内容顶部对齐")
  168.             .fontSize(14)
  169.             .width('100%')
  170.             .height(40)
  171.             .textContentAlign(TextContentAlign.TOP)
  172.             .backgroundColor('#F0F9FF')
  173.             .textAlign(TextAlign.Center)
  174.             .borderRadius(4);
  175.           Text("内容居中对齐(默认)")
  176.             .fontSize(14)
  177.             .width('100%')
  178.             .height(40)
  179.             .textContentAlign(TextContentAlign.CENTER) // 默认值
  180.             .backgroundColor('#F0F9FF')
  181.             .textAlign(TextAlign.Center)
  182.             .borderRadius(4);
  183.           Text("内容底部对齐")
  184.             .fontSize(14)
  185.             .width('100%')
  186.             .height(40)
  187.             .textContentAlign(TextContentAlign.BOTTOM)
  188.             .backgroundColor('#F0F9FF')
  189.             .textAlign(TextAlign.Center)
  190.             .borderRadius(4);
  191.         }
  192.         .width('90%')
  193.         .backgroundColor(Color.White)
  194.         .borderRadius(8);
  195.       }
  196.       .padding(15)
  197.       .backgroundColor('#F5F5F5')
  198.       .width('100%')
  199.     }
  200.     .width('100%')
  201.     .height('100%');
  202.   }
  203. }
复制代码
运行效果

Text排版与溢出处理Text排版与溢出处理1
4.png
5.png
六、文本交互事件

Text组件支持基础交互事件,结合copyOption可配置系统原生文本选择/复制能力,满足轻交互与文本复用需求。同时,Text组件还支持实体识别功能,通过enableDataDetector属性(总开关)控制,设为true即可开启系统原生识别能力,可识别电话、链接、邮箱等实体,配合dataDetectorConfig属性可指定识别类型、接收识别结果,点击识别结果会触发系统默认行为(如点击链接跳转、点击电话拨号)。
6.1 核心概念解析

事件/属性名功能说明支持组件适用场景设备支持onClick点击事件,点击时触发Text/Span轻交互(提示、简单跳转)全设备onHover悬浮事件,鼠标/触控笔悬浮时触发Text/Span鼠标/触控笔设备交互增强仅鼠标/触控笔设备onTouch触摸事件,按下/移动/抬起时触发Text复杂触摸交互全设备copyOption文本选择/复制控制开关Text(Span继承)启用系统原生长按选择/复制能力全设备copyOption 有三个核心枚举值,用于控制文本选择/复制的范围:

  • None:不可选择复制,是默认取值;
  • InApp:仅当前应用内可选择复制;
  • LocalDevice:本地设备所有应用可选择复制。
系统原生选择能力有明确的使用规则:

  • 启用前提:必须配置copyOption属性且取值非None;
  • 触发方式:用户长按压文本,系统会自动弹出选择菜单,包含复制、粘贴、全选等功能;
  • 继承规则:Span组件无独立的copyOption属性,其文本选择能力完全继承外层Text组件的配置。
6.2 示例代码(TextEventPage.ets)
  1. import { promptAction } from '@kit.ArkUI';
  2. @Entry
  3. @Component
  4. struct TextEventPage {
  5.   @State textContent: string = "长按可复制这段文本:https://ost.51cto.com/posts/38236";
  6.   build() {
  7.     Column({ space: 15}) {
  8.       // 页面标题
  9.       Text("Text 交互事件演示")
  10.         .fontSize(24)
  11.         .fontWeight(FontWeight.Bold)
  12.         .width('100%')
  13.         .textAlign(TextAlign.Center);
  14.       // 1. 点击事件
  15.       Text("1. 点击事件(全设备支持)")
  16.         .fontSize(14)
  17.         .fontColor('#666666')
  18.         .width('90%')
  19.         .margin({ bottom: 5 });
  20.       Text("点击我触发提示")
  21.         .fontSize(18)
  22.         .fontColor($r('sys.color.brand'))
  23.         .width('90%')
  24.         .textAlign(TextAlign.Center)
  25.         .padding(10)
  26.         .backgroundColor(Color.White)
  27.         .borderRadius(8)
  28.         .onHover((isHover: boolean) => {
  29.           console.log(`鼠标悬浮状态:${isHover}`);
  30.         })
  31.         .onClick(() => {
  32.           promptAction.showToast({ message: "文本被点击啦!" });
  33.         })
  34.         .onTouch((event) => {
  35.           console.log(`触摸事件类型:${event.type}`);
  36.           return true;
  37.         });
  38.       // 2. 可复制文本(系统原生能力,含实体识别)
  39.       Text("2. 可复制文本(本地设备全应用可用)")
  40.         .fontSize(14)
  41.         .fontColor('#666666')
  42.         .width('90%')
  43.         .margin({ top: 15, bottom: 5 });
  44.       Text(this.textContent)
  45.         .fontSize(18)
  46.         .fontColor('#FF3333')
  47.         .width('90%')
  48.         .textAlign(TextAlign.Center)
  49.         .padding(10)
  50.         .backgroundColor(Color.White)
  51.         .borderRadius(8)
  52.         .copyOption(CopyOptions.LocalDevice)
  53.         .enableDataDetector(true)// 开启实体识别(总开关)
  54.         .dataDetectorConfig({
  55.           // types设为[]识别所有实体,可指定具体类型(如URL、电话号码)
  56.           types: [],
  57.           onDetectResultUpdate: (result: string) => {} // 识别结果回调
  58.         })
  59.       // 3. 应用内可复制文本(验证码场景)
  60.       Text("3. 应用内可复制文本(仅当前应用可用)")
  61.         .fontSize(14)
  62.         .fontColor('#666666')
  63.         .width('90%')
  64.         .margin({ top: 15, bottom: 5 });
  65.       Text("验证码:865239(长按可复制)")
  66.         .fontSize(18)
  67.         .fontColor('#333333')
  68.         .backgroundColor(Color.White)
  69.         .padding(10)
  70.         .borderRadius(8)
  71.         .width('90%')
  72.         .copyOption(CopyOptions.InApp);
  73.     }
  74.     .padding(15)
  75.     .backgroundColor('#F5F5F5')
  76.     .width('100%')
  77.     .height('100%');
  78.   }
  79. }
复制代码
运行效果

Text选中交互事件开启实体识别
6.png
7.png
七、Text 进阶能力

进阶能力涵盖自适应字号、自定义文本选择菜单、热搜榜实战场景,是满足复杂业务需求的核心能力,基于Text组件原生属性实现,无需额外依赖。
其中自定义文本选择菜单功能,通过editMenuOptions属性配置菜单构建函数和点击回调,且该功能依赖copyOption属性启用文本选择能力,可实现扩展系统菜单(如添加分享、翻译等自定义功能)。
7.1 核心概念解析

能力类型核心属性实现逻辑生效前提自适应字号minFontSize + maxFontSize文本在指定字号范围内自动缩放,容器空间不足时缩小① 同时设置min/maxFontSize;② 设置maxLines;③ 有宽/高约束自定义选择菜单editMenuOptions扩展系统原生文本选择菜单,添加自定义功能① 配置copyOption启用文本选择;热搜榜场景constraintSize + maxLines + textOverflow精准控制词条宽度,溢出显示省略号① constraintSize设置最大宽度;② maxLines=1+Ellipsis7.2 示例代码(TextAdvancedPage.ets)
  1. import { promptAction } from '@kit.ArkUI';
  2. @Entry
  3. @Component
  4. struct TextAdvancedPage {
  5.   // 自定义选择菜单:扩展系统菜单,添加「分享」「翻译」选项
  6.   private onCreateMenu = (menuItems: Array<TextMenuItem>): Array<TextMenuItem> => {
  7.     const shareItem: TextMenuItem = {
  8.       content: '分享',
  9.       id: TextMenuItemId.of('share'),
  10.     };
  11.     const translateItem: TextMenuItem = {
  12.       content: '翻译',
  13.       id: TextMenuItemId.of('translate'),
  14.     };
  15.     menuItems.push(shareItem, translateItem);
  16.     return menuItems;
  17.   };
  18.   // 自定义菜单点击事件回调
  19.   private onMenuItemClick = (menuItem: TextMenuItem, textRange: TextRange): boolean => {
  20.     if (menuItem.id.equals(TextMenuItemId.of('share'))) {
  21.       promptAction.showToast({ message: "文本分享成功!" });
  22.       return true;
  23.     }
  24.     if (menuItem.id.equals(TextMenuItemId.of('translate'))) {
  25.       promptAction.showToast({ message: "文本翻译成功!" });
  26.       return true;
  27.     }
  28.     return false;
  29.   };
  30.   build() {
  31.     Column({ space: 20}) {
  32.       Text("Text 进阶能力演示")
  33.         .fontSize(24)
  34.         .fontWeight(FontWeight.Bold)
  35.         .width('100%')
  36.         .textAlign(TextAlign.Center);
  37.       // 1. 自适应字号(12~30fp)
  38.       Text("1. 自适应字号(容器不足时自动缩小)")
  39.         .fontSize(14)
  40.         .fontColor('#666666')
  41.         .width('90%')
  42.         .margin({ bottom: 5 });
  43.       Text("鸿蒙应用开发自适应字号演示,容器变窄时自动缩小,容器足够时使用最大字号")
  44.         .width('90%')
  45.         .height(80)
  46.         .maxFontSize(30)
  47.         .minFontSize(12)
  48.         .maxLines(2)
  49.         .padding(10)
  50.         .backgroundColor(Color.White)
  51.         .borderRadius(8);
  52.       // 2. 自定义文本选择菜单
  53.       Text("2. 自定义文本选择菜单(长按选中后可见扩展选项)")
  54.         .fontSize(14)
  55.         .fontColor('#666666')
  56.         .width('90%')
  57.         .margin({ top: 15, bottom: 5 });
  58.       Text("选中这段文本,可看到系统菜单新增「分享」「翻译」选项")
  59.         .fontSize(18)
  60.         .width('90%')
  61.         .padding(10)
  62.         .backgroundColor(Color.White)
  63.         .borderRadius(8)
  64.         .copyOption(CopyOptions.LocalDevice) // 启用文本选择,菜单生效前提
  65.         .editMenuOptions({
  66.           onCreateMenu: this.onCreateMenu,
  67.           onMenuItemClick: this.onMenuItemClick
  68.         });
  69.       // 3. 热搜榜场景演示
  70.       Text("3. 热搜榜场景(精准控宽+溢出省略)")
  71.         .fontSize(14)
  72.         .fontColor('#666666')
  73.         .width('90%')
  74.         .margin({ top: 15, bottom: 5 });
  75.       Column() {
  76.         // 热搜1(爆)
  77.         Row() {
  78.           Text("1")
  79.           .fontSize(14)
  80.           .fontColor('#FF3333')
  81.           .margin({ left: 10, right: 10 });
  82.           Text("鸿蒙OS 全新版本发布 新增多项核心功能")
  83.             .fontSize(16)
  84.             .fontColor('#333333')
  85.             .maxLines(1)
  86.             .textOverflow({ overflow: TextOverflow.Ellipsis })
  87.             .constraintSize({ maxWidth: 250 });
  88.           Text("爆")
  89.             .margin({ left: 4 })
  90.             .fontSize(12)
  91.             .textAlign(TextAlign.Center)
  92.             .fontColor(Color.White)
  93.             .backgroundColor(0x770100)
  94.             .borderRadius(5)
  95.             .width(20)
  96.             .height(20);
  97.         }
  98.         .width('100%')
  99.         .margin({bottom:8})
  100.         // 热搜2(热)
  101.         Row() {
  102.           Text("2")
  103.           .fontSize(14)
  104.           .fontColor('#FF3333')
  105.           .margin({ left: 10, right: 10 });
  106.           Text("鸿蒙应用开发教程 零基础入门到精通 最新版")
  107.             .fontSize(16)
  108.             .textOverflow({ overflow: TextOverflow.Ellipsis })
  109.             .fontColor('#333333')
  110.             .maxLines(1)
  111.             .constraintSize({ maxWidth: 250 });
  112.           Text("热")
  113.             .margin({ left: 6 })
  114.             .fontSize(12)
  115.             .textAlign(TextAlign.Center)
  116.             .fontColor(Color.White)
  117.             .backgroundColor(0xCC5500)
  118.             .borderRadius(4)
  119.             .width(20)
  120.             .height(20);
  121.         }
  122.         .width('100%')
  123.       }
  124.       .width('100%')
  125.       .padding(10)
  126.       .backgroundColor(Color.White)
  127.       .borderRadius(8)
  128.     }.padding(15)
  129.     .backgroundColor('#F5F5F5')
  130.     .width('100%')
  131.     .height('100%');
  132.   }
  133. }
复制代码
运行效果

Text进阶能力演示添加自定义菜单选中文本默认菜单
8.png
9.png
10.png
八、核心知识点总结


  • 组件定位:Text是只读文本展示组件,无编辑能力,与TextInput/TextArea边界清晰;
  • 事件规则:支持onClick(全设备)、onHover(仅鼠标/触控笔)、onTouch(全设备);文本选择是系统原生能力,由copyOption配置;
  • 样式属性:fontSize默认fp单位,fontWeight支持100~900取值,textAlign的Justify仅对多行生效;TextVerticalAlign(API20+)默认BASELINE,TextContentAlign(API21+)默认CENTER;
  • 溢出处理:长文本必配maxLines+Ellipsis;Marquee仅单行生效;constraintSize优先级高于父容器;
  • Span规则:仅嵌套在Text内,样式继承+覆盖,仅支持onClick,选择能力继承外层;
  • ImageSpan:Text专属子组件,实现文本图片混排,仅3个核心属性,图片需放入media目录;
  • 实体识别:enableDataDetector开启识别,dataDetectorConfig配置细节,支持5种原生实体类型;
  • 自适应字号:需同时满足min/maxFontSize、maxLines、宽高约束三个条件才生效;
  • 自定义选择菜单:依赖copyOption生效,可扩展系统菜单功能;
  • copyOption:枚举值(None/InApp/LocalDevice),控制文本选择/复制范围。
九、配套代码


  • 工程名称:TextApplication
  • 仓库地址:https://gitee.com/HarmonyOS-UI-Basics/harmony-os-ui-basics.git
十、下节预告

下一节我们将学习核心基础组件(三)—— 文本输入组件 TextInput / TextArea / Search,从三大核心维度系统掌握文本输入全场景开发能力:

  • 基础用法:明确 TextInput(单行)、TextArea(多行)、Search(搜索专属)三大组件差异,掌握 Normal / Password / Email 等输入类型配置,适配登录、表单、评论、搜索等场景;
  • 样式与事件:自定义提示文本、背景、边框与密码显隐样式,绑定 onChange、onSubmit、onSecurityStateChange、onPaste 等核心事件,实现输入数据实时同步与交互控制;
  • 进阶实战:掌握 inputFilter 字符过滤、onWillChange 内容拦截、全局焦点控制、键盘避让、光标定位等能力,解决输入校验、格式限制、软键盘遮挡等高频开发问题,独立完成登录注册、搜索联想、评论编辑等实战页面开发。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册