• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Text
2
3显示一段文本的组件。
4
5>  **说明:**
6>
7>  该组件从API Version 7开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。
8
9
10## 子组件
11
12可以包含[Span](ts-basic-components-span.md)、[ImageSpan](ts-basic-components-imagespan.md)、[SymbolSpan](ts-basic-components-symbolSpan.md)和[ContainerSpan](ts-basic-components-containerspan.md)子组件。
13
14## 接口
15
16Text(content?: string | Resource, value?: TextOptions)
17
18从API version 9开始,该接口支持在ArkTS卡片中使用。
19
20**参数:**
21
22| 参数名 | 参数类型 | 必填 | 参数描述 |
23| -------- | -------- | -------- | -------- |
24| content | string \| [Resource](ts-types.md#resource) | 否 | 文本内容。包含子组件Span时不生效,显示Span内容,并且此时text组件的样式不生效。<br/>默认值:' ' |
25| value<sup>11+</sup> | [TextOptions](#textoptions11) | 否 | 文本组件初始化选项。|
26
27## 属性
28
29除支持[通用属性](ts-universal-attributes-size.md)和[文本通用属性](ts-universal-attributes-text-style.md)外,还支持以下属性:
30
31| 名称                       | 参数类型                            | 描述                                               |
32| ----------------------- | ----------------------------------- | ------------------------------------------- |
33| textAlign               | [TextAlign](ts-appendix-enums.md#textalign) | 设置文本段落在水平方向的对齐方式。<br/>默认值:TextAlign.Start<br/>**说明:**<br/>文本段落宽度占满Text组件宽度;可通过[align](ts-universal-attributes-location.md)属性控制文本段落在垂直方向上的位置,此组件中不可通过align属性控制文本段落在水平方向上的位置,即align属性中Alignment.TopStartAlignment.TopAlignment.TopEnd效果相同,控制内容在顶部,Alignment.StartAlignment.CenterAlignment.End效果相同,控制内容垂直居中,Alignment.BottomStartAlignment.BottomAlignment.BottomEnd效果相同,控制内容在底部。结合TextAlign属性可控制内容在水平方向的位置。<br/>当`textAlign`属性设置为TextAlign.JUSTIFY时,最后一行文本不参与两端对齐,为水平对齐首部效果。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
34| textOverflow            | {overflow:&nbsp;[TextOverflow](ts-appendix-enums.md#textoverflow)} | 设置文本超长时的显示方式。<br/>默认值:{overflow:&nbsp;TextOverflow.Clip}<br/>**说明:**<br/>文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:\u200B。从API version 11开始,建议优先组合`wordBreak`属性设置为WordBreak.BREAK_ALL方式实现字母为单位进行截断,使用[示例](#示例4)。<br />当`overflow`设置为TextOverflow.NoneTextOverflow.ClipTextOverflow.Ellipsis时,需配合`maxLines`使用,单独设置不生效。设置TextOverflow.NoneTextOverflow.Clip效果一样。<br/>当`overflow`设置为TextOverflow.MARQUEE时,文本在一行内滚动显示,设置`maxLines`及`copyOption`属性均不生效,此时不支持ImageSpan组件,并且在文本不可滚动时,设置`textAlign`属性生效;在文本可滚动时,设置`textAlign`属性不生效。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
35| maxLines                | number | 设置文本的最大行数。<br />**说明:** <br />默认情况下,文本是自动折行的,如果指定此参数,则文本最多不会超过指定的行。如果有多余的文本,可以通过        `textOverflow`来指定截断方式。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
36| lineHeight              | string&nbsp;\|&nbsp;number&nbsp;\|&nbsp;[Resource](ts-types.md#resource)  | 设置文本的文本行高,设置值不大于0时,不限制文本行高,自适应字体大小,Length为number类型时单位为fp。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。 |
37| decoration              | {<br/>type:&nbsp;[TextDecorationType](ts-appendix-enums.md#textdecorationtype),<br/>color?:&nbsp;[ResourceColor](ts-types.md#resourcecolor)<br/>} | 设置文本装饰线样式及其颜色。<br />默认值:{<br/>type:&nbsp;TextDecorationType.None,<br/>color:Color.Black<br/>} <br/>从API version 9开始,该接口支持在ArkTS卡片中使用。|
38| baselineOffset          | number&nbsp;\|&nbsp;string | 设置文本基线的偏移量,默认值0。  <br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**说明:** <br/>设置该值为百分比时,按默认值显示。 |
39| letterSpacing           | number&nbsp;\|&nbsp;string | 设置文本字符间距。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**说明:** <br/>设置该值为百分比时,按默认值显示。<br /> 当取值为负值时,文字会发生压缩,负值过小时会将组件内容区大小压缩为0,导致无内容显示。 |
40| minFontSize             | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource)      | 设置文本最小显示字号。<br/>需配合maxFontSize以及maxline或布局大小限制使用,单独设置不生效,对子组件不生效。<br/>自适应字号生效时,fontSize设置不生效。<br/>minFontSize小于或等于0时,自适应字号不生效。<br/>从API version 9开始,该接口支持在ArkTS卡片中使用。|
41| maxFontSize             | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource)      | 设置文本最大显示字号。<br/>需配合minFontSize以及maxline或布局大小限制使用,单独设置不生效,对子组件不生效。<br/>自适应字号生效时,fontSize设置不生效。 <br/>从API version 9开始,该接口支持在ArkTS卡片中使用。|
42| textCase                | [TextCase](ts-appendix-enums.md#textcase) | 设置文本大小写。<br />默认值:TextCase.Normal <br/>从API version 9开始,该接口支持在ArkTS卡片中使用。|
43| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 组件支持设置文本是否可复制粘贴。<br />默认值:CopyOptions.None <br/>该接口支持在ArkTS卡片中使用。<br>**说明:** <br/>设置copyOptions为CopyOptions.InApp或者CopyOptions.LocalDevice,长按文本,会弹出文本选择菜单,可选中文本并进行复制、全选操作。 |
44| draggable<sup>9+</sup>  | boolean | 设置选中文本拖拽效果。<br/>不能和[onDragStart](ts-universal-events-drag-drop.md)事件同时使用;<br/>需配合copyOption一起使用,设置copyOptions为CopyOptions.InApp或者CopyOptions.LocalDevice,并且draggable设置为true时,支持对选中文本的拖拽以及选中内容复制到输入框。<br/>默认值:false <br />**说明:**<br />从 API version 9 开始支持。 |
45| font<sup>10+</sup>  | [Font](ts-types.md#font) | 设置文本样式。包括字体大小、字体粗细、字体族和字体风格。 |
46| textShadow<sup>10+</sup> | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明)&nbsp;\|&nbsp;Array&lt;[ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明)&gt;<sup>11+</sup>  | 设置文字阴影效果。<br/>**说明:**<br/>不支持fill字段,不支持智能取色模式。<br/>Text组件clip属性默认为true,超出组件大小区域的内容(例如文字阴影)会被截断。在Text组件内容超出组件大小区域场景下,建议设置`clip`属性为false达到完整文字阴影效果。<br/>从API version 11开始,该接口支持以数组形式入参,实现多重文字阴影。|
47| heightAdaptivePolicy<sup>10+</sup> | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | 设置文本自适应高度的方式。<br/>默认值:TextHeightAdaptivePolicy.MAX_LINES_FIRST。<br/>**说明:**<br/>当设置为TextHeightAdaptivePolicy.MAX_LINES_FIRST时,优先使用`maxLines`属性来调整文本高度。如果使用`maxLines`属性的布局大小超过了布局约束,则尝试在`minFontSize`和`maxFontSize`的范围内缩小字体以显示更多文本。<br/>当设置为TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST时,优先使用`minFontSize`属性来调整文本高度。如果使用`minFontSize`属性可以将文本布局在一行中,则尝试在`minFontSize`和`maxFontSize`的范围内增大字体并使用最大可能的字体大小。<br/>当设置为TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST时,优先使用布局约束来调整文本高度。如果布局大小超过布局约束,则尝试在`minFontSize`和`maxFontSize`的范围内缩小字体以满足布局约束。如果将字体大小缩小到`minFontSize`后,布局大小仍然超过布局约束,则删除超过布局约束的行。|
48| textIndent<sup>10+</sup> | [Length](ts-types.md#length) | 设置首行文本缩进,默认值0。 |
49| font<sup>10+</sup> | [Font](ts-types.md#font) | 设置文本样式。包括字体大小、字体粗细、字体族和字体风格。 |
50| wordBreak<sup>11+</sup> | [WordBreak](ts-appendix-enums.md#wordbreak11) | 设置断行规则。 <br />默认值:WordBreak.BREAK_WORD <br/>**说明:** <br/>从API version 11开始,该接口支持在ArkTS卡片中使用。<br/>WordBreak.BREAK_ALL与{overflow:&nbsp;TextOverflow.Ellipsis},`maxLines`组合使用可实现英文单词按字母截断,超出部分以省略号显示|
51| selection<sup>11+</sup> |(selectionStart:&nbsp;number, selectionEnd:&nbsp;number)| 设置选中区域。选中区域高亮且显示手柄和文本选择菜单。 <br />默认值:(-1,-1) <br/>**说明:** <br/>从API version 11开始,该接口支持在ArkTS卡片中使用。<br/>当`copyOption`设置为CopyOptions.None时,设置`selection`属性不生效。<br/>当`overflow`设置为TextOverflow.MARQUEE时,设置`selection`属性不生效。<br/>当`selectionStart`大于等于`selectionEnd`时不选中。可选范围为[0, textSize],textSize为文本内容最大字符数,入参小于0处理为0,大于textSize处理为textSize。<br/>当`selectionStart`或`selectionEnd`在截断不可见区域时不选中。截断为false时超出父组件的文本选中区域生效。|
52| ellipsisMode<sup>11+</sup> |[EllipsisMode](ts-appendix-enums.md#ellipsismode11)| 设置省略位置。 <br />默认值:EllipsisMode.END <br/>**说明:** <br/>从API version 11开始,该接口支持在ArkTS卡片中使用。<br/>`ellipsisMode`属性需要配合`overflow`设置为TextOverflow.Ellipsis以及maxLines使用,单独设置`ellipsisMode`属性不生效。<br/>EllipsisMode.STARTEllipsisMode.CENTER仅在单行超长文本生效。|
53| enableDataDetector<sup>11+</sup> |boolean| 使能文本识别。<br/>默认值: false<br/>**说明:**<br/>所识别实体的`fontColor`和`decoration`会被更改为如下样式:<br/>fontColor:Color.Blue<br/>decoration:&nbsp;{<br/>type:&nbsp;TextDecorationType.Underline,<br/>color:&nbsp;Color.Blue<br/>}<br/>该接口依赖设备底层应具有文本识别能力,否则设置不会生效。<br/>当`enableDataDetector`设置为true,同时不设置`dataDetectorConfig`属性时,默认识别所有类型的实体。<br/>当`copyOption`设置为CopyOptions.None时,该功能不会生效。 |
54| dataDetectorConfig<sup>11+</sup> | [TextDataDetectorConfig](#textdatadetectorconfig11对象说明) | 文本识别配置。 <br/>默认值:{<br/>types:&nbsp;[ ],<br/>onDetectResultUpdate:&nbsp;null<br/>} <br />**说明:**<br/>需配合`enableDataDetector`一起使用,设置`enableDataDetector`为true时,`dataDetectorConfig`的配置才能生效。<br/>当有两个实体A、B重叠时,按以下规则保留实体:<br/>1.&nbsp;若A&nbsp;⊂&nbsp;B,则保留B,反之则保留A。<br/>2.&nbsp;当A&nbsp;⊄&nbsp;B且B&nbsp;⊄&nbsp;A时,若A.start&nbsp;<&nbsp;B.start,则保留A,反之则保留B。|
55| bindSelectionMenu<sup>11+</sup> | {<br/>spantype:&nbsp;[TextSpanType](ts-appendix-enums.md#textspantype11),<br/>content:&nbsp;[CustomBuilder](ts-types.md#custombuilder8),<br/>responseType:&nbsp;[TextResponseType](ts-appendix-enums.md#textresponsetype11)&nbsp;\,<br/>options?:&nbsp;[SelectionMenuOptions](ts-appendix-enums.md#selectionmenuoptions11)<br/>} | 设置自定义选择菜单。<br/> 默认值:{<br/>  spanType:&nbsp;TextSpanType.TEXT<br/>content:空<br/>responseType:&nbsp;TextResponseType.LONG_PRESS <br/>}<br />**说明:**<br/>`bindSelectionMenu`长按响应时长为600ms,`bindContextMenu`长按响应时长为800ms,同时绑定且触发方式均为长按时,优先响应`bindSelectionMenu`。<br/>自定义菜单超长时,建议内部嵌套[Scroll](./ts-container-scroll.md)组件使用,避免键盘被遮挡。 |
56
57>  **说明:**
58>
59>  不支持Text内同时存在文本内容和Span或ImageSpan子组件。如果同时存在,只显示Span或ImageSpan内的内容。
60>
61>  通用属性中形状裁剪[clip](ts-universal-attributes-sharp-clipping.md#clip)属性,在Text组件中,默认值为true,即文本内容大于组件内容时,文本会截断。如果需要显示超出的部分,可以设置clip为false。
62>
63>  字体排版引擎会对开发者传入的宽度[width](ts-universal-attributes-size.md#width)进行向下取整,保证是整型像素后进行排版。如果字体排版引擎向上取整,可能会出现文字右侧被截断。
64
65## TextDataDetectorConfig<sup>11+</sup>对象说明
66| 参数名 | 类型  | 必填 | 说明  |
67| ------ | -------- | ---- | ------------------------------------------- |
68| types   | [TextDataDetectorType](ts-appendix-enums.md#textdatadetectortype11) | 是   | 设置文本识别的实体类型。设置types为null或者[]时,识别所有类型的实体,否则只识别指定类型的实体。 |
69| onDetectResultUpdate   | (callback:(result: string) => void) | 是   | 文本识别成功后,触发onDetectResultUpdate回调。<br/>-&nbsp;result:文本识别的结果,Json格式。 |
70
71## 事件
72
73除支持[通用事件](ts-universal-events-click.md)外,还支持以下事件:
74
75| 名称                                                         | 功能描述                                                     |
76| ------------------------------------------------------------ | ------------------------------------------------------------ |
77| onCopy(callback:(value:&nbsp;string)&nbsp;=&gt;&nbsp;void)<sup>11+</sup> | 长按文本内部区域弹出剪贴板后,点击剪切板复制按钮,触发该回调。<br/>value:复制的文本内容。 <br/>**说明:** <br/>从API version 11开始,该接口支持在ArkTS卡片中使用。<br/>目前文本复制仅支持文本。|
78| onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)<sup>11+</sup> | 文本选择的位置发生变化时,触发该回调。<br />selectionStart:文本选择区域起始位置,文本框中文字的起始位置为0。<br />selectionEnd:文本选择区域结束位置。 |
79
80## TextOptions<sup>11+</sup>
81
82Text初始化参数。
83
84| 名称 | 类型 | 必填 | 说明 |
85| -------- | -------- | -------- | -------- |
86| controller | [TextController](#textcontroller11)  | 是 | 文本控制器。 |
87
88## TextController<sup>11+</sup>
89
90Text组件的控制器。
91
92### 导入对象
93
94```
95controller: TextController = new TextController()
96```
97
98### closeSelectionMenu
99
100closeSelectionMenu(): void
101
102关闭自定义选择菜单或系统默认选择菜单。
103
104## 示例
105
106### 示例1
107
108```ts
109// xxx.ets
110@Entry
111@Component
112struct TextExample1 {
113  build() {
114    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
115      // 文本水平方向对齐方式设置
116      // 单行文本
117      Text('textAlign').fontSize(9).fontColor(0xCCCCCC)
118      Text('TextAlign set to Center.')
119        .textAlign(TextAlign.Center)
120        .fontSize(12)
121        .border({ width: 1 })
122        .padding(10)
123        .width('100%')
124      Text('TextAlign set to Start.')
125        .textAlign(TextAlign.Start)
126        .fontSize(12)
127        .border({ width: 1 })
128        .padding(10)
129        .width('100%')
130      Text('TextAlign set to End.')
131        .textAlign(TextAlign.End)
132        .fontSize(12)
133        .border({ width: 1 })
134        .padding(10)
135        .width('100%')
136
137      // 多行文本
138      Text('This is the text content with textAlign set to Center.')
139        .textAlign(TextAlign.Center)
140        .fontSize(12)
141        .border({ width: 1 })
142        .padding(10)
143        .width('100%')
144      Text('This is the text content with textAlign set to Start.')
145        .textAlign(TextAlign.Start)
146        .fontSize(12)
147        .border({ width: 1 })
148        .padding(10)
149        .width('100%')
150      Text('This is the text content with textAlign set to End.')
151        .textAlign(TextAlign.End)
152        .fontSize(12)
153        .border({ width: 1 })
154        .padding(10)
155        .width('100%')
156
157
158      // 文本超长时显示方式
159      Text('TextOverflow+maxLines').fontSize(9).fontColor(0xCCCCCC)
160      // 超出maxLines截断内容展示
161      Text('This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content. This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content.')
162        .textOverflow({ overflow: TextOverflow.Clip })
163        .maxLines(1)
164        .fontSize(12)
165        .border({ width: 1 })
166        .padding(10)
167
168      // 超出maxLines展示省略号
169      Text('This is set textOverflow to Ellipsis text content This is set textOverflow to Ellipsis text content.'.split('')
170        .join('\u200B'))
171        .textOverflow({ overflow: TextOverflow.Ellipsis })
172        .maxLines(1)
173        .fontSize(12)
174        .border({ width: 1 })
175        .padding(10)
176
177      Text('lineHeight').fontSize(9).fontColor(0xCCCCCC)
178      Text('This is the text with the line height set. This is the text with the line height set.')
179        .fontSize(12).border({ width: 1 }).padding(10)
180      Text('This is the text with the line height set. This is the text with the line height set.')
181        .fontSize(12).border({ width: 1 }).padding(10)
182        .lineHeight(20)
183    }.height(600).width(350).padding({ left: 35, right: 35, top: 35 })
184  }
185}
186```
187![textExp1](figures/textExp1.png)
188
189### 示例2
190
191```ts
192@Entry
193@Component
194struct TextExample2 {
195  build() {
196    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
197      Text('decoration').fontSize(9).fontColor(0xCCCCCC)
198      Text('This is the text content with the decoration set to LineThrough and the color set to Red.')
199        .decoration({
200          type: TextDecorationType.LineThrough,
201          color: Color.Red
202        })
203        .fontSize(12)
204        .border({ width: 1 })
205        .padding(10)
206        .width('100%')
207
208
209      Text('This is the text content with the decoration set to Overline and the color set to Red.')
210        .decoration({
211          type: TextDecorationType.Overline,
212          color: Color.Red
213        })
214        .fontSize(12)
215        .border({ width: 1 })
216        .padding(10)
217        .width('100%')
218
219
220      Text('This is the text content with the decoration set to Underline and the color set to Red.')
221        .decoration({
222          type: TextDecorationType.Underline,
223          color: Color.Red
224        })
225        .fontSize(12)
226        .border({ width: 1 })
227        .padding(10)
228        .width('100%')
229
230      // 文本基线偏移
231      Text('baselineOffset').fontSize(9).fontColor(0xCCCCCC)
232      Text('This is the text content with baselineOffset 0.')
233        .baselineOffset(0)
234        .fontSize(12)
235        .border({ width: 1 })
236        .padding(10)
237        .width('100%')
238      Text('This is the text content with baselineOffset 30.')
239        .baselineOffset(30)
240        .fontSize(12)
241        .border({ width: 1 })
242        .padding(10)
243        .width('100%')
244      Text('This is the text content with baselineOffset -20.')
245        .baselineOffset(-20)
246        .fontSize(12)
247        .border({ width: 1 })
248        .padding(10)
249        .width('100%')
250
251      // 文本字符间距
252      Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC)
253      Text('This is the text content with letterSpacing 0.')
254        .letterSpacing(0)
255        .fontSize(12)
256        .border({ width: 1 })
257        .padding(10)
258        .width('100%')
259      Text('This is the text content with letterSpacing 3.')
260        .letterSpacing(3)
261        .fontSize(12)
262        .border({ width: 1 })
263        .padding(10)
264        .width('100%')
265      Text('This is the text content with letterSpacing -1.')
266        .letterSpacing(-1)
267        .fontSize(12)
268        .border({ width: 1 })
269        .padding(10)
270        .width('100%')
271
272      Text('textCase').fontSize(9).fontColor(0xCCCCCC)
273      Text('This is the text content with textCase set to Normal.')
274        .textCase(TextCase.Normal)
275        .fontSize(12)
276        .border({ width: 1 })
277        .padding(10)
278        .width('100%')
279      // 文本全小写展示
280      Text('This is the text content with textCase set to LowerCase.')
281        .textCase(TextCase.LowerCase)
282        .fontSize(12)
283        .border({ width: 1 })
284        .padding(10)
285        .width('100%')
286      // 文本全大写展示
287      Text('This is the text content with textCase set to UpperCase.')
288        .textCase(TextCase.UpperCase)
289        .fontSize(12).border({ width: 1 }).padding(10)
290
291    }.height(700).width(350).padding({ left: 35, right: 35, top: 35 })
292  }
293}
294```
295![textExp1](figures/textExp2.png)
296
297### 示例3
298
299textShadow,heightAdaptivePolicy,TextOverflow.MARQUEE使用示例:
300
301```ts
302@Entry
303@Component
304struct TextExample {
305  build() {
306    Column({ space: 8 }) {
307      Text('textShadow').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
308      // 设置文字阴影效果
309      Text('textShadow')
310        .width('80%')
311        .height(55)
312        .fontSize(40)
313        .lineHeight(55)
314        .textAlign(TextAlign.Center)
315        .textShadow({ radius: 10, color: Color.Black, offsetX: 0, offsetY: 0 })
316        .borderWidth(1)
317      Divider()
318      // 设置文本自适应高度的方式
319      Text('heightAdaptivePolicy').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
320      Text('This is the text with the height adaptive policy set')
321        .width('80%')
322        .height(90)
323        .borderWidth(1)
324        .minFontSize(10)
325        .maxFontSize(30)
326        .maxLines(3)
327        .textOverflow({ overflow: TextOverflow.Ellipsis })
328        .heightAdaptivePolicy(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
329      Text('This is the text with the height adaptive policy set')
330        .width('80%')
331        .height(90)
332        .borderWidth(1)
333        .minFontSize(10)
334        .maxFontSize(30)
335        .maxLines(3)
336        .textOverflow({ overflow: TextOverflow.Ellipsis })
337        .heightAdaptivePolicy(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST)
338      Text('This is the text with the height adaptive policy set')
339        .width('80%')
340        .height(90)
341        .borderWidth(1)
342        .minFontSize(10)
343        .maxFontSize(30)
344        .maxLines(3)
345        .textOverflow({ overflow: TextOverflow.Ellipsis })
346        .heightAdaptivePolicy(TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST)
347      Divider()
348      Text('marquee').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
349      // 设置文本超长时以跑马灯的方式展示
350      Text('This is the text with the text overflow set marquee')
351        .width(300)
352        .borderWidth(1)
353        .textOverflow({ overflow: TextOverflow.MARQUEE })
354    }
355  }
356}
357```
358
359![](figures/text_3.gif)
360
361### 示例4
362wordBreak使用示例
363
364```ts
365@Entry
366@Component
367struct TextExample4 {
368  @State type: string = 'WordBreakType:Normal且clip为true'
369  @State text: string = 'This is set wordBreak to WordBreak text content This is set wordBreak to WordBreak text content.'
370
371  build() {
372    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
373      Text(this.type).fontSize(9).fontColor(0xCCCCCC)
374      Text('This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.')
375        .fontSize(12)
376        .border({ width: 1 })
377        .wordBreak(WordBreak.NORMAL)
378        .lineHeight(20)
379        .maxLines(2)
380      Text('WordBreakType:Normal且clip为false').fontSize(9).fontColor(0xCCCCCC)
381      Text('This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.')
382        .fontSize(12)
383        .border({ width: 1 })
384        .wordBreak(WordBreak.NORMAL)
385        .lineHeight(20)
386        .maxLines(2)
387        .clip(false)
388      Text("WordBreakType:BreakAll").fontSize(9).fontColor(0xCCCCCC)
389      Text(this.text)
390        .fontSize(12)
391        .border({ width: 1 })
392        .maxLines(2)
393        .textOverflow({ overflow: TextOverflow.Ellipsis })
394        .wordBreak(WordBreak.BREAK_ALL)
395        .lineHeight(20)
396      Text("WordBreakType:BreakWord").fontSize(9).fontColor(0xCCCCCC)
397      Text(this.text)
398        .fontSize(12)
399        .border({ width: 1 })
400        .maxLines(2)
401        .textOverflow({ overflow: TextOverflow.Ellipsis })
402        .wordBreak(WordBreak.BREAK_WORD)
403        .lineHeight(20)
404    }.height(300).width(335).padding({ left: 35, right: 35, top: 35 })
405  }
406}
407```
408![](figures/textExample4.jpeg)
409
410### 示例5
411selection, onCopy使用示例
412
413```ts
414@Entry
415@Component
416struct TextExample5 {
417  @State onCopy: string = ''
418  @State text: string = 'This is set selection to Selection text content This is set selection to Selection text content.'
419  @State start: number = 0
420  @State end: number = 20
421
422  build() {
423    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) {
424      Text(this.text)
425        .fontSize(12)
426        .border({ width: 1 })
427        .lineHeight(20)
428        .margin(30)
429        .copyOption(CopyOptions.InApp)
430        .selection(this.start, this.end)
431        .onCopy((value: string) => {
432          this.onCopy = value
433        })
434      Button('Set text selection')
435        .margin({left:20})
436        .onClick(() => {
437          // 变更文本选中起始点、终点
438          this.start = 10
439          this.end = 30
440        })
441      Text(this.onCopy).fontSize(12).margin(10).key('copy')
442    }.height(600).width(335).padding({ left: 35, right: 35, top: 35 })
443  }
444}
445```
446![](figures/textExample5.jpeg)
447
448### 示例6
449ellipsisMode使用示例
450
451```ts
452@Entry
453@Component
454struct TextExample6 {
455  @State text: string = 'This is set ellipsisMode to EllipsisMode text content This is set ellipsisMode to EllipsisMode text content.'
456  @State ellipsisModeIndex: number = 0;
457  @State ellipsisMode: EllipsisMode[] = [EllipsisMode.START, EllipsisMode.CENTER, EllipsisMode.END]
458  @State ellipsisModeStr: string[] = ['START', 'CENTER', 'END']
459  build() {
460    Column() {
461      Text(this.text)
462        .fontSize(16)
463        .border({ width: 1 })
464        .lineHeight(20)
465        .maxLines(1)
466        .textOverflow({overflow:TextOverflow.Ellipsis})
467        .ellipsisMode(this.ellipsisMode[this.ellipsisModeIndex])
468        .width(300)
469        .margin({ left: 20, top: 20 })
470
471      Row() {
472        Button('更改省略号位置:' + this.ellipsisModeStr[this.ellipsisModeIndex]).onClick(() => {
473          this.ellipsisModeIndex++
474          if(this.ellipsisModeIndex > (this.ellipsisModeStr.length - 1)) {
475            this.ellipsisModeIndex = 0
476          }
477        })
478      }.margin({ top: 10 })
479    }
480  }
481}
482```
483![](figures/textExample6.gif)
484
485### 示例7
486enableDataDetector和dataDetectorConfig使用示例
487
488```ts
489@Entry
490@Component
491struct TextExample7 {
492  @State phoneNumber: string = '(86) (755) ********';
493  @State url: string = 'www.********.com';
494  @State email: string = '***@example.com';
495  @State address: string = 'XX省XX市XX区XXXX';
496  @State enableDataDetector: boolean = true;
497  @State types: TextDataDetectorType[] = [];
498
499  build() {
500    Row() {
501      Column() {
502        Text(
503          '电话号码:' + this.phoneNumber + '\n' +
504          '链接:' + this.url + '\n' +
505          '邮箱:' + this.email + '\n' +
506          '地址:' + this.address
507        )
508          .fontSize(16)
509          .copyOption(CopyOptions.InApp)
510          .enableDataDetector(this.enableDataDetector)
511          .dataDetectorConfig({types : this.types, onDetectResultUpdate: (result: string)=>{}})
512          .textAlign(TextAlign.Center)
513          .borderWidth(1)
514          .padding(10)
515          .width('100%')
516      }
517      .width('100%')
518    }
519    .height('100%')
520  }
521}
522```
523### 示例8
524bindSelectionMenu,onTextSelectionChange及closeSelectionMenu使用示例
525
526```ts
527@Entry
528@Component
529struct Demo {
530  controller: TextController = new TextController();
531  options: TextOptions = { controller: this.controller };
532
533  build() {
534    Column() {
535      Column() {
536        Text(undefined, this.options) {
537          Span('Hello World')
538          ImageSpan($r('app.media.icon'))
539            .width('100px')
540            .height('100px')
541            .objectFit(ImageFit.Fill)
542            .verticalAlign(ImageSpanAlignment.CENTER)
543        }
544        .copyOption(CopyOptions.InApp)
545        .bindSelectionMenu(TextSpanType.IMAGE, this.LongPressImageCustomMenu, TextResponseType.LONG_PRESS, {
546          onDisappear: () => {
547            console.info(`自定义选择菜单关闭时回调`);
548          },
549          onAppear: () => {
550            console.info(`自定义选择菜单弹出时回调`);
551          }
552        })
553        .bindSelectionMenu(TextSpanType.TEXT, this.RightClickTextCustomMenu, TextResponseType.RIGHT_CLICK)
554        .bindSelectionMenu(TextSpanType.MIXED, this.SelectMixCustomMenu, TextResponseType.SELECT)
555        .onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
556          console.info(`文本选中区域变化回调, selectionStart: ${selectionStart}, selectionEnd: ${selectionEnd}`);
557        })
558        .borderWidth(1)
559        .borderColor(Color.Red)
560        .width(200)
561        .height(100)
562      }
563      .width('100%')
564      .backgroundColor(Color.White)
565      .alignItems(HorizontalAlign.Start)
566      .padding(25)
567    }
568    .height('100%')
569  }
570
571  @Builder
572  RightClickTextCustomMenu() {
573    Column() {
574      Menu() {
575        MenuItemGroup() {
576          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 1", labelInfo: "" })
577            .onClick((event) => {
578              this.controller.closeSelectionMenu();
579            })
580          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 2", labelInfo: "" })
581          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 3", labelInfo: "" })
582        }
583      }
584      .MenuStyles()
585    }
586  }
587
588  @Builder
589  LongPressImageCustomMenu() {
590    Column() {
591      Menu() {
592        MenuItemGroup() {
593          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 1", labelInfo: "" })
594            .onClick((event) => {
595              this.controller.closeSelectionMenu();
596            })
597          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 2", labelInfo: "" })
598          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 3", labelInfo: "" })
599        }
600      }
601      .MenuStyles()
602    }
603  }
604
605  @Builder
606  SelectMixCustomMenu() {
607    Column() {
608      Menu() {
609        MenuItemGroup() {
610          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 1", labelInfo: "" })
611            .onClick((event) => {
612              this.controller.closeSelectionMenu();
613            })
614          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 2", labelInfo: "" })
615          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 3", labelInfo: "" })
616        }
617      }
618      .MenuStyles()
619    }
620  }
621}
622
623@Extend(Menu)
624function MenuStyles() {
625  .radius($r('sys.float.ohos_id_corner_radius_card'))
626  .clip(true)
627  .backgroundColor('#F0F0F0')
628}
629```
630
631![](figures/textBindSelectionMenu.gif)
632