• 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**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
21
22**系统能力:** SystemCapability.ArkUI.ArkUI.Full
23
24**参数:**
25
26| 参数名 | 类型 | 必填 | 说明 |
27| -------- | -------- | -------- | -------- |
28| content | string \| [Resource](ts-types.md#resource) | 否 | 文本内容。包含子组件Span且未设置[属性字符串](ts-universal-styled-string.md#属性字符串)时不生效,显示Span内容,并且此时text组件的样式不生效。<br/>默认值:' ' |
29| value<sup>11+</sup> | [TextOptions](#textoptions11) | 否 | 文本组件初始化选项。|
30
31## 属性
32
33除支持[通用属性](ts-component-general-attributes.md),还支持以下属性:
34
35### textAlign
36
37textAlign(value: TextAlign)
38
39设置文本段落在水平方向的对齐方式。
40
41文本段落宽度占满Text组件宽度。
42
43可通过[align](ts-universal-attributes-location.md#align)属性控制文本段落在垂直方向上的位置,此组件中不可通过align属性控制文本段落在水平方向上的位置,具体效果如下:
44
45- Alignment.TopStartAlignment.TopAlignment.TopEnd:内容顶部对齐。
46
47- Alignment.StartAlignment.CenterAlignment.End:内容垂直居中。
48
49- Alignment.BottomStartAlignment.BottomAlignment.BottomEnd:内容底部对齐。
50
51当textAlign属性设置为TextAlign.JUSTIFY时,需要根据文本内容设置[wordBreak](#wordbreak11)属性,且最后一行文本不参与两端对齐,为水平对齐首部效果。
52
53**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
54
55**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
56
57**系统能力:** SystemCapability.ArkUI.ArkUI.Full
58
59**参数:**
60
61| 参数名 | 类型                                        | 必填 | 说明                                                       |
62| ------ | ------------------------------------------- | ---- | ---------------------------------------------------------- |
63| value  | [TextAlign](ts-appendix-enums.md#textalign) | 是   | 文本段落在水平方向的对齐方式。<br/>默认值:TextAlign.Start<br/>Wearable设备上默认值为:TextAlign.Center |
64
65### textOverflow
66
67textOverflow(options: TextOverflowOptions)
68
69设置文本超长时的显示方式。
70
71文本截断是按字截断。例如,英文以单词为最小单位进行截断,若需要以字母为单位进行截断,可在字母间添加零宽空格:`\u200B`。从API version 11开始,建议优先组合[wordBreak](#wordbreak11)属性设置为WordBreak.BREAK_ALL方式实现字母为单位进行截断,具体详见[示例4设置文本断行及折行](#示例4设置文本断行及折行)。
72
73当overflow设置为TextOverflow.NoneTextOverflow.ClipTextOverflow.Ellipsis时,需配合[maxLines](#maxlines)属性使用,单独设置不生效。设置TextOverflow.NoneTextOverflow.Clip效果一样。
74
75当overflow设置为TextOverflow.MARQUEE时:
76
77- 文本在一行内滚动显示。
78
79- 设置[maxLines](#maxlines)及[copyOption](#copyoption9)属性均不生效。
80
81- Text组件[clip](ts-universal-attributes-sharp-clipping.md#clip)属性默认为true。
82
83- 属性字符串的[CustomSpan](ts-universal-styled-string.md#customspan)不支持跑马灯模式。
84
85- [textAlign](#textalign)属性的生效规则:当文本不可滚动时,textAlign属性生效;当文本可滚动时,textAlign属性不生效。
86
87从API version 12开始,当overflow设置为TextOverflow.MARQUEE时,支持ImageSpan组件,文本和图片在一行内滚动显示。
88
89**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
90
91**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
92
93**系统能力:** SystemCapability.ArkUI.ArkUI.Full
94
95**参数:**
96
97| 参数名 | 类型                                                         | 必填 | 说明                                                         |
98| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
99| options | [TextOverflowOptions](#textoverflowoptions18对象说明) | 是   | 文本超长显示方式对象 |
100
101### maxLines
102
103maxLines(value: number)
104
105设置文本的最大行数。
106
107默认情况下,文本是自动折行的,如果指定此属性,则文本最多不会超过指定的行。如果有多余的文本,可以通过[textOverflow](#textoverflow)来指定截断方式。
108
109**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
110
111**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
112
113**系统能力:** SystemCapability.ArkUI.ArkUI.Full
114
115**参数:**
116
117| 参数名 | 类型   | 必填 | 说明             |
118| ------ | ------ | ---- | ---------------- |
119| value  | number | 是   | 文本的最大行数。 |
120
121### lineHeight
122
123lineHeight(value: number | string | Resource)
124
125设置文本的文本行高。
126
127设置值不大于0时,不限制文本行高,自适应字体大小,number类型时单位为fp。string类型支持number类型取值的字符串形式,可以附带单位,例如"10"、"10fp"。
128
129**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
130
131**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
132
133**系统能力:** SystemCapability.ArkUI.ArkUI.Full
134
135**参数:**
136
137| 参数名 | 类型                                                         | 必填 | 说明             |
138| ------ | ------------------------------------------------------------ | ---- | ---------------- |
139| value  | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 文本的文本行高。 |
140
141### decoration
142
143decoration(value: DecorationStyleInterface)
144
145设置文本装饰线样式及其颜色。
146
147**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
148
149**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
150
151**系统能力:** SystemCapability.ArkUI.ArkUI.Full
152
153**参数:**
154
155| 参数名 | 类型                                                         | 必填 | 说明                                                         |
156| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
157| value  | [DecorationStyleInterface<sup>12+</sup>](ts-universal-styled-string.md#decorationstyleinterface对象说明) | 是   | 文本装饰线样式对象。<br/>默认值:<br/>{<br/>&nbsp;type:&nbsp;TextDecorationType.None,<br/>&nbsp;color:&nbsp;Color.Black,<br/>&nbsp;style:&nbsp;TextDecorationStyle.SOLID&nbsp;<br/>}<br/>**说明:** <br/>style参数不支持卡片能力。 |
158
159### baselineOffset
160
161baselineOffset(value: number | string)
162
163设置文本基线的偏移量。
164
165设置该值为百分比时,按默认值显示。
166
167正数内容向上偏移,负数向下偏移。
168
169**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
170
171**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
172
173**系统能力:** SystemCapability.ArkUI.ArkUI.Full
174
175**参数:**
176
177| 参数名 | 类型                       | 必填 | 说明                             |
178| ------ | -------------------------- | ---- | -------------------------------- |
179| value  | number&nbsp;\|&nbsp;string | 是   | 文本基线的偏移量。<br/>默认值:0 |
180
181### letterSpacing
182
183letterSpacing(value: number | string)
184
185设置文本字符间距。
186
187设置该值为百分比时,按默认值显示。设置该值为0时,按默认值显示。string类型支持number类型取值的字符串形式,可以附带单位,例如"10"、"10fp"。
188
189当取值为负值时,文字会发生压缩,负值过小时会将组件内容区大小压缩为0,导致无内容显示。
190
191**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
192
193**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
194
195**系统能力:** SystemCapability.ArkUI.ArkUI.Full
196
197**参数:**
198
199| 参数名 | 类型                       | 必填 | 说明           |
200| ------ | -------------------------- | ---- | -------------- |
201| value  | number&nbsp;\|&nbsp;string | 是   | 文本字符间距。<br/>单位:fp |
202
203### minFontSize
204
205minFontSize(value: number | string | Resource)
206
207设置文本最小显示字号。
208
209string类型支持number类型取值的字符串形式,可以附带单位,例如"10"、"10fp"。
210
211需配合[maxFontSize](#maxfontsize)以及[maxLines](#maxlines)或布局大小限制使用,单独设置不生效。
212
213自适应字号生效时,fontSize设置不生效。
214
215minFontSize小于或等于0时,自适应字号不生效,此时按照[fontSize](#fontsize)属性的值生效,未设置时按照其默认值生效。
216
217从API version 18开始,支持在子组件和属性字符串上生效,未设置字号的部分自适应字号。
218
219**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
220
221**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
222
223**系统能力:** SystemCapability.ArkUI.ArkUI.Full
224
225**参数:**
226
227| 参数名 | 类型                                                         | 必填 | 说明               |
228| ------ | ------------------------------------------------------------ | ---- | ------------------ |
229| value  | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 文本最小显示字号。<br/>单位:fp |
230
231### maxFontSize
232
233maxFontSize(value: number | string | Resource)
234
235设置文本最大显示字号。
236
237string类型支持number类型取值的字符串形式,可以附带单位,例如"10"、"10fp"。
238
239需配合[minFontSize](#minfontsize)以及[maxLines](#maxlines)或布局大小限制使用,单独设置不生效。
240
241自适应字号生效时,fontSize设置不生效。
242
243maxFontSize小于或等于0时,自适应字号不生效,此时按照[fontSize](#fontsize)属性的值生效,未设置时按照其默认值生效。
244
245从API version 18开始支持在子组件和属性字符串上生效,未设置字号的部分自适应字号。
246
247**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
248
249**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
250
251**系统能力:** SystemCapability.ArkUI.ArkUI.Full
252
253**参数:**
254
255| 参数名 | 类型                                                         | 必填 | 说明               |
256| ------ | ------------------------------------------------------------ | ---- | ------------------ |
257| value  | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 文本最大显示字号。<br/>单位:fp |
258
259### textCase
260
261textCase(value: TextCase)
262
263设置文本大小写。
264
265**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
266
267**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
268
269**系统能力:** SystemCapability.ArkUI.ArkUI.Full
270
271**参数:**
272
273| 参数名 | 类型                                      | 必填 | 说明                                      |
274| ------ | ----------------------------------------- | ---- | ----------------------------------------- |
275| value  | [TextCase](ts-appendix-enums.md#textcase) | 是   | 文本大小写。<br />默认值:TextCase.Normal |
276
277### fontColor
278
279fontColor(value: ResourceColor)
280
281设置字体颜色。
282
283**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
284
285**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
286
287**系统能力:** SystemCapability.ArkUI.ArkUI.Full
288
289**参数:**
290
291| 参数名 | 类型                                       | 必填 | 说明       |
292| ------ | ------------------------------------------ | ---- | ---------- |
293| value  | [ResourceColor](ts-types.md#resourcecolor) | 是   | 字体颜色。<br />默认值:'e6182431'<br />Wearable设备上默认值为:'#c5ffffff' |
294
295### fontSize
296
297fontSize(value: number | string | Resource)
298
299设置字体大小。
300
301**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
302
303**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
304
305**系统能力:** SystemCapability.ArkUI.ArkUI.Full
306
307**参数:**
308
309| 参数名 | 类型                                                         | 必填 | 说明                                                         |
310| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
311| value  | number&nbsp;\|&nbsp;string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 字体大小。fontSize为number类型时,使用fp单位。不支持设置百分比字符串。<br />默认值:16fp<br />Wearable设备上默认值为:15fp |
312
313### fontStyle
314
315fontStyle(value: FontStyle)
316
317设置字体样式。
318
319**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
320
321**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
322
323**系统能力:** SystemCapability.ArkUI.ArkUI.Full
324
325**参数:**
326
327| 参数名 | 类型                                        | 必填 | 说明                                    |
328| ------ | ------------------------------------------- | ---- | --------------------------------------- |
329| value  | [FontStyle](ts-appendix-enums.md#fontstyle) | 是   | 字体样式。<br/>默认值:FontStyle.Normal |
330
331### fontWeight
332
333fontWeight(value: number | FontWeight | string)
334
335设置文本的字体粗细,设置过大可能会在不同字体下有截断。
336
337**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
338
339**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
340
341**系统能力:** SystemCapability.ArkUI.ArkUI.Full
342
343**参数:**
344
345| 参数名 | 类型                                                         | 必填 | 说明                                                         |
346| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
347| value  | number&nbsp;\|&nbsp;[FontWeight](ts-appendix-enums.md#fontweight)&nbsp;\|&nbsp;string | 是   | 文本的字体粗细,number类型取值[100,&nbsp;900],取值间隔为100,默认为400,取值越大,字体越粗。string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。<br/>默认值:FontWeight.Normal<br/>Wearable设备上默认值为:FontWeight.Regular |
348
349### fontFamily
350
351fontFamily(value: string | Resource)
352
353设置字体列表。
354
355**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
356
357**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
358
359**系统能力:** SystemCapability.ArkUI.ArkUI.Full
360
361**参数:**
362
363| 参数名 | 类型                                                 | 必填 | 说明                                                         |
364| ------ | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
365| value  | string&nbsp;\|&nbsp;[Resource](ts-types.md#resource) | 是   | 字体列表。默认字体'HarmonyOS Sans'。<br>应用当前支持'HarmonyOS Sans'字体和[注册自定义字体](../js-apis-font.md)。<br>卡片当前仅支持'HarmonyOS Sans'字体。 |
366
367### copyOption<sup>9+</sup>
368
369copyOption(value: CopyOptions)
370
371设置组件是否支持文本可复制粘贴。
372
373设置copyOptions为CopyOptions.InApp或者CopyOptions.LocalDevice,长按文本,会弹出文本选择菜单,可选中文本并进行复制、全选操作,此时Text会监听onClick事件,手势事件为非冒泡事件,若需要点击Text组件区域响应父组件的点击手势事件,建议在父组件上使用[parallelGesture](ts-gesture-settings.md#绑定手势识别)绑定手势识别,也可参考[示例7设置文本识别](#示例7设置文本识别)。
374
375由于卡片没有长按事件,此场景下长按文本,不会弹出文本选择菜单。
376
377**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。
378
379**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
380
381**系统能力:** SystemCapability.ArkUI.ArkUI.Full
382
383**参数:**
384
385| 参数名 | 类型                                             | 必填 | 说明                                                       |
386| ------ | ------------------------------------------------ | ---- | ---------------------------------------------------------- |
387| value  | [CopyOptions](ts-appendix-enums.md#copyoptions9) | 是   | 组件是否支持文本可复制粘贴。<br />默认值:CopyOptions.None |
388
389### draggable<sup>9+</sup>
390
391draggable(value: boolean)
392
393设置选中文本拖拽效果。
394
395不能和[onDragStart](ts-universal-events-drag-drop.md#ondragstart)事件同时使用。
396
397需配合[CopyOptions](ts-appendix-enums.md#copyoptions9)一起使用,设置copyOptions为CopyOptions.InApp或者CopyOptions.LocalDevice,并且draggable设置为true时,支持对选中文本的拖拽以及选中内容复制到输入框。
398
399**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
400
401**系统能力:** SystemCapability.ArkUI.ArkUI.Full
402
403**参数:**
404
405| 参数名 | 类型    | 必填 | 说明                                 |
406| ------ | ------- | ---- | ------------------------------------ |
407| value  | boolean | 是   | 选中文本拖拽效果。<br/>默认值:false |
408
409### font<sup>10+</sup>
410
411font(value: Font)
412
413设置文本样式。
414
415包括字体大小、字体粗细、字体族和字体风格。
416
417**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
418
419**系统能力:** SystemCapability.ArkUI.ArkUI.Full
420
421**参数:**
422
423| 参数名 | 类型    | 必填 | 说明       |
424| ------ | ------- | ---- | ---------- |
425| value  | [Font](ts-types.md#font) | 是   | 文本样式。 |
426
427### textShadow<sup>10+</sup>
428
429textShadow(value: ShadowOptions | Array&lt;ShadowOptions&gt;)
430
431设置文字阴影效果。
432
433不支持fill字段,不支持智能取色模式。
434
435从API version 11开始,该接口支持以数组形式入参,实现多重文字阴影。
436
437**卡片能力:** 从API version 10开始,该接口支持在ArkTS卡片中使用。
438
439**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
440
441**系统能力:** SystemCapability.ArkUI.ArkUI.Full
442
443**参数:**
444
445| 参数名 | 类型                                                         | 必填 | 说明           |
446| ------ | ------------------------------------------------------------ | ---- | -------------- |
447| value  | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明)&nbsp;\|&nbsp;&nbsp;Array&lt;[ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions对象说明)&gt;<sup>11+</sup> | 是   | 文字阴影效果。 |
448
449### heightAdaptivePolicy<sup>10+</sup>
450
451heightAdaptivePolicy(value: TextHeightAdaptivePolicy)
452
453设置文本自适应布局调整字号的方式。
454
455规则如下:
456
457- MAX_LINES_FIRST模式:优先使用[maxLines](#maxlines)属性来调整文本高度。如果使用maxLines属性的布局大小超过了布局约束,则尝试在[minFontSize](#minfontsize)和[maxFontSize](#maxfontsize)的范围内缩小字体以显示更多文本。
458
459- MIN_FONT_SIZE_FIRST模式:优先使用minFontSize属性来调整文本高度。如果使用minFontSize属性可以将文本布局在一行中,则尝试在minFontSize和maxFontSize的范围内增大字体并使用最大可能的字体大小在一行内显示,否则按minFontSize显示。
460
461- LAYOUT_CONSTRAINT_FIRST模式:优先使用布局约束来调整文本高度。如果布局大小超过布局约束,则尝试在minFontSize和maxFontSize的范围内缩小字体以满足布局约束。如果将字体大小缩小到minFontSize后,布局大小仍然超过布局约束,则删除超过布局约束的行。
462
463**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
464
465**系统能力:** SystemCapability.ArkUI.ArkUI.Full
466
467**参数:**
468
469| 参数名 | 类型                                                         | 必填 | 说明                                                         |
470| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
471| value  | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | 是   | 文本自适应高度的方式。<br/>默认值:TextHeightAdaptivePolicy.MAX_LINES_FIRST |
472
473### textIndent<sup>10+</sup>
474
475textIndent(value: Length)
476
477设置首行文本缩进。
478
479**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
480
481**系统能力:** SystemCapability.ArkUI.ArkUI.Full
482
483**参数:**
484
485| 参数名 | 类型                         | 必填 | 说明                         |
486| ------ | ---------------------------- | ---- | ---------------------------- |
487| value  | [Length](ts-types.md#length) | 是   | 首行文本缩进。<br/>默认值:0 |
488
489### wordBreak<sup>11+</sup>
490
491wordBreak(value: WordBreak)
492
493设置断行规则。
494
495WordBreak.BREAK_ALL与{overflow:&nbsp;TextOverflow.Ellipsis},maxLines组合使用可实现英文单词按字母截断,超出部分以省略号显示。
496
497**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
498
499**系统能力:** SystemCapability.ArkUI.ArkUI.Full
500
501**参数:**
502
503| 参数名 | 类型                                          | 必填 | 说明                                          |
504| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
505| value  | [WordBreak](ts-appendix-enums.md#wordbreak11) | 是   | 断行规则。 <br />默认值:WordBreak.BREAK_WORD |
506
507### selection<sup>11+</sup>
508
509selection(selectionStart: number, selectionEnd: number)
510
511设置选中区域。
512
513选中区域高亮且显示手柄和文本选择菜单。
514
515当copyOption设置为CopyOptions.None时,设置selection属性不生效。
516
517当overflow设置为TextOverflow.MARQUEE时,设置selection属性不生效。
518
519当selectionStart大于等于selectionEnd时不选中。可选范围为[0, textSize],textSize为文本内容最大字符数,入参小于0处理为0,大于textSize处理为textSize。
520
521当selectionStart或selectionEnd在截断不可见区域时不选中。截断为false时超出父组件的文本选中区域生效。
522
523**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
524
525**系统能力:** SystemCapability.ArkUI.ArkUI.Full
526
527**参数:**
528
529| 参数名         | 类型   | 必填 | 说明                                 |
530| -------------- | ------ | ---- | ------------------------------------ |
531| selectionStart | number | 是   | 所选文本的起始位置。<br />默认值:-1 |
532| selectionEnd   | number | 是   | 所选文本的结束位置。<br />默认值:-1 |
533
534### ellipsisMode<sup>11+</sup>
535
536ellipsisMode(value: EllipsisMode)
537
538设置省略位置。
539
540ellipsisMode属性需要配合overflow设置为TextOverflow.Ellipsis以及maxLines使用,单独设置ellipsisMode属性不生效。
541
542EllipsisMode.STARTEllipsisMode.CENTER仅在单行超长文本生效。
543
544**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
545
546**系统能力:** SystemCapability.ArkUI.ArkUI.Full
547
548**参数:**
549
550| 参数名 | 类型                                                | 必填 | 说明                                      |
551| ------ | --------------------------------------------------- | ---- | ----------------------------------------- |
552| value  | [EllipsisMode](ts-appendix-enums.md#ellipsismode11) | 是   | 省略位置。 <br />默认值:EllipsisMode.END |
553
554### enableDataDetector<sup>11+</sup>
555
556enableDataDetector(enable: boolean)
557
558设置是否进行文本特殊实体识别。
559
560该接口依赖设备底层应具有文本识别能力,否则设置不会生效。
561
562当enableDataDetector设置为true,同时不设置dataDetectorConfig属性时,默认识别所有类型的实体,所识别实体的color和decoration会被更改为如下样式:
563
564```ts
565color: '#ff007dff'
566decoration:{
567  type: TextDecorationType.Underline,
568  color: '#ff007dff',
569  style: TextDecorationStyle.SOLID
570}
571```
572
573触摸点击和鼠标右键点击实体,会根据实体类型弹出对应的实体操作菜单,鼠标左键点击实体会直接响应菜单的第一个选项。
574
575当overflow设置为TextOverflow.MARQUEE时,该功能不会生效。
576
577当copyOption设置为CopyOptions.None时,点击实体弹出的菜单没有选择文本、复制、翻译、分享和搜索功能。当copyOption不为CopyOptions.None,且textSelectable设置为TextSelectableMode.UNSELECTABLE时,仍然具有实体复制功能,但没有选择文本功能。
578
579**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
580
581**系统能力:** SystemCapability.ArkUI.ArkUI.Full
582
583**参数:**
584
585| 参数名 | 类型    | 必填 | 说明                              |
586| ------ | ------- | ---- | --------------------------------- |
587| enable  | boolean | 是   | 使能文本识别。<br/>默认值: false |
588
589### dataDetectorConfig<sup>11+</sup>
590
591dataDetectorConfig(config: TextDataDetectorConfig)
592
593设置文本识别配置。
594
595需配合[enableDataDetector](#enabledatadetector11)一起使用,设置enableDataDetector为true时,dataDetectorConfig的配置才能生效。
596
597当有两个实体A、B重叠时,按以下规则保留实体:
598
5991.&nbsp;若A&nbsp;⊂&nbsp;B,则保留B,反之则保留A。
600
6012.&nbsp;当A&nbsp;⊄&nbsp;B且B&nbsp;⊄&nbsp;A时,若A.start&nbsp;<&nbsp;B.start,则保留A,反之则保留B。
602
603**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
604
605**系统能力:** SystemCapability.ArkUI.ArkUI.Full
606
607**参数:**
608
609| 参数名 | 类型                                                        | 必填 | 说明                                                         |
610| ------ | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
611| config | [TextDataDetectorConfig](ts-text-common.md#textdatadetectorconfig11对象说明) | 是   | 文本识别配置。|
612
613### bindSelectionMenu<sup>11+</sup>
614
615bindSelectionMenu(spanType: TextSpanType, content: CustomBuilder, responseType: TextResponseType,
616    options?: SelectionMenuOptions)
617
618设置自定义选择菜单。
619
620bindSelectionMenu长按响应时长为600ms,bindContextMenu长按响应时长为800ms,同时绑定且触发方式均为长按时,优先响应bindSelectionMenu。
621
622自定义菜单超长时,建议内部嵌套[Scroll](./ts-container-scroll.md)组件使用,避免键盘被遮挡。
623
624**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
625
626**系统能力:** SystemCapability.ArkUI.ArkUI.Full
627
628**参数:**
629
630| 参数名       | 类型                                                         | 必填 | 说明                                                         |
631| ------------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
632| spanType     | [TextSpanType](#textspantype11枚举说明)          | 是   | 选择菜单的类型。<br/>默认值:TextSpanType.TEXT               |
633| content      | [CustomBuilder](ts-types.md#custombuilder8)                  | 是   | 选择菜单的内容。                                             |
634| responseType | [TextResponseType](#textresponsetype11枚举说明)  | 是   | 选择菜单的响应类型。<br/>默认值:TextResponseType.LONG_PRESS |
635| options      | [SelectionMenuOptions](ts-basic-components-richeditor.md#selectionmenuoptions10) | 否   | 选择菜单的选项。                                             |
636
637### fontFeature<sup>12+</sup>
638
639fontFeature(value: string)
640
641设置文字特性效果,比如数字等宽的特性。
642
643格式为:normal \| \<feature-tag-value\>
644
645\<feature-tag-value\>的格式为:\<string\> \[ \<integer\> \| on \| off ]
646
647\<feature-tag-value\>的个数可以有多个,中间用','隔开。
648
649例如,使用等宽数字的输入格式为:"ss01" on。
650
651**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
652
653**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
654
655**系统能力:** SystemCapability.ArkUI.ArkUI.Full
656
657**参数:**
658
659| 参数名 | 类型   | 必填 | 说明           |
660| ------ | ------ | ---- | -------------- |
661| value  | string | 是   | 文字特性效果。 |
662
663fontFeature属性列表<br/>
664![alt text](figures/arkts-fontfeature.png)
665
666设置 Font Feature 属性,Font Feature 是 OpenType 字体的高级排版能力,如支持连字、数字等宽等特性,一般用在自定义字体中,其能力需要字体本身支持。
667更多 Font Feature 能力介绍可参考 https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prophttps://sparanoid.com/lab/opentype-features/
668
669>  **说明:**
670>
671>  不支持Text内同时存在文本内容和Span或ImageSpan子组件。如果同时存在,只显示Span或ImageSpan内的内容。
672>
673>  字体排版引擎会对开发者传入的宽度[width](ts-universal-attributes-size.md#width)进行向下取整,保证是整型像素后进行排版。如果字体排版引擎向上取整,可能会出现文字右侧被截断。
674>
675>  当多个Text组件在[Row](ts-container-row.md)容器内布局且没有设置具体的布局分配信息时,Text会以Row的最大尺寸进行布局。如果需要子组件主轴累加的尺寸不超过Row容器主轴的尺寸,可以设置[layoutWeight](ts-universal-attributes-size.md#layoutweight)或者是以[Flex](ts-universal-attributes-flex-layout.md)布局来约束子组件的主轴尺寸。
676
677### lineSpacing<sup>12+</sup>
678
679lineSpacing(value: LengthMetrics)
680
681设置文本的行间距,设置值不大于0时,取默认值0。
682
683**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
684
685**系统能力:** SystemCapability.ArkUI.ArkUI.Full
686
687**参数:**
688
689| 参数名 | 类型                                                         | 必填 | 说明             |
690| ------ | ------------------------------------------------------------ | ---- | ---------------- |
691| value  | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | 是   | 文本的行间距。默认值:0 |
692
693### privacySensitive<sup>12+</sup>
694
695privacySensitive(supported: boolean)
696
697设置是否支持卡片敏感隐私信息。
698
699**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
700
701**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
702
703**系统能力:** SystemCapability.ArkUI.ArkUI.Full
704
705**参数:**
706
707| 参数名    | 类型    | 必填 | 说明                                                         |
708| --------- | ------- | ---- | ------------------------------------------------------------ |
709| supported | boolean | 是   | 是否支持卡片敏感隐私信息。<br/>默认值为false,当设置为true时,隐私模式下文字将被遮罩为横杠“-”样式。<br/>**说明:** <br/>设置null则不敏感。<br/>进入隐私模式需要[卡片框架支持](./ts-universal-attributes-obscured.md)。 |
710
711### lineBreakStrategy<sup>12+</sup>
712
713lineBreakStrategy(strategy: LineBreakStrategy)
714
715设置折行规则。该属性在wordBreak不等于breakAll的时候生效,不支持连词符。
716
717**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
718
719**系统能力:** SystemCapability.ArkUI.ArkUI.Full
720
721**参数:**
722
723| 参数名   | 类型                                                         | 必填 | 说明                                                    |
724| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------- |
725| strategy | [LineBreakStrategy](ts-appendix-enums.md#linebreakstrategy12) | 是   | 文本的折行规则。 <br />默认值:LineBreakStrategy.GREEDY |
726
727### textSelectable<sup>12+</sup>
728
729textSelectable(mode: TextSelectableMode)
730
731设置是否支持文本可选择、可获焦以及Touch后能否获取焦点。
732
733**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
734
735**系统能力:** SystemCapability.ArkUI.ArkUI.Full
736
737**参数:**
738
739| 参数名 | 类型                                          | 必填 | 说明                                          |
740| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
741| mode  | [TextSelectableMode](ts-appendix-enums.md#textselectablemode12) | 是   | 文本是否支持可选择、可获焦。 <br />默认值:TextSelectableMode.SELECTABLE_UNFOCUSABLE |
742
743### editMenuOptions<sup>12+</sup>
744
745editMenuOptions(editMenu: EditMenuOptions)
746
747设置自定义菜单扩展项,允许用户设置扩展项的文本内容、图标、回调方法。
748
749**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
750
751**系统能力:** SystemCapability.ArkUI.ArkUI.Full
752
753**参数:**
754
755| 参数名 | 类型                                          | 必填 | 说明                                          |
756| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
757| editMenu  | [EditMenuOptions](ts-text-common.md#editmenuoptions) | 是   | 扩展菜单选项。 |
758
759### minFontScale<sup>12+</sup>
760
761minFontScale(scale: number | Resource)
762
763设置文本最小的字体缩放倍数。
764
765**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
766
767**系统能力:** SystemCapability.ArkUI.ArkUI.Full
768
769**参数:**
770
771| 参数名 | 类型                                          | 必填 | 说明                                          |
772| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
773| scale  | number \| [Resource](ts-types.md#resource) | 是   | 文本最小的字体缩放倍数。<br/>取值范围:[0, 1]<br/>**说明:** <br/>设置的值小于0时,按值为0处理,设置的值大于1,按值为1处理,异常值默认不生效。 |
774
775### maxFontScale<sup>12+</sup>
776
777maxFontScale(scale: number | Resource)
778
779设置文本最大的字体缩放倍数。
780
781**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
782
783**系统能力:** SystemCapability.ArkUI.ArkUI.Full
784
785**参数:**
786
787| 参数名 | 类型                                          | 必填 | 说明                                          |
788| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
789| scale  | number \| [Resource](ts-types.md#resource) | 是   | 文本最大的字体缩放倍数。<br/>取值范围:[1, +∞)<br/>**说明:** <br/>设置的值小于1时,按值为1处理,异常值默认不生效。 |
790
791### halfLeading<sup>12+</sup>
792
793halfLeading(halfLeading: boolean)
794
795设置文本是否将行间距平分至行的顶部与底部。
796
797组件侧设置halfLeading优先级高于module.json5配置文件中的halfLeading配置项。
798
799**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
800
801**系统能力:** SystemCapability.ArkUI.ArkUI.Full
802
803**参数:**
804
805| 参数名 | 类型                                          | 必填 | 说明                                          |
806| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
807| halfLeading | boolean | 是  | 文本是否将行间距平分至行的顶部与底部。<br/>true表示将行间距平分至行的顶部与底部,false则不平分。<br/>默认值:false |
808
809### font<sup>12+</sup>
810
811font(fontValue: Font, options?: FontSettingOptions)
812
813设置文本样式,支持设置字体配置项。
814
815仅Text组件生效,其子组件不生效。
816
817**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
818
819**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
820
821**系统能力:** SystemCapability.ArkUI.ArkUI.Full
822
823**参数:**
824
825| 参数名 | 类型                                          | 必填 | 说明                                          |
826| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
827| fontValue | [Font](ts-types.md#font) | 是  | 设置文本样式。 |
828| options | [FontSettingOptions](ts-text-common.md#fontsettingoptions12对象说明) | 否  | 设置字体配置项。 |
829
830### fontWeight<sup>12+</sup>
831
832fontWeight(weight: number | FontWeight | string, options?: FontSettingOptions)
833
834设置文本字重,支持设置字体配置项。
835
836仅Text组件生效,其子组件不生效。
837
838**卡片能力:** 从API version 12开始,该接口支持在ArkTS卡片中使用。
839
840**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
841
842**系统能力:** SystemCapability.ArkUI.ArkUI.Full
843
844**参数:**
845
846| 参数名 | 类型                                          | 必填 | 说明                                          |
847| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
848| weight | number&nbsp;\|&nbsp;[FontWeight](ts-appendix-enums.md#fontweight)&nbsp;\|&nbsp;string | 是  | 设置文本字重。number类型取值[100,&nbsp;900],取值间隔为100,默认为400,取值越大,字体越粗。string类型仅支持number类型取值的字符串形式,例如"400",以及"bold"、"bolder"、"lighter"、"regular"、"medium",分别对应FontWeight中相应的枚举值。 |
849| options | [FontSettingOptions](ts-text-common.md#fontsettingoptions12对象说明) | 否  | 设置字体配置项。 |
850
851### enableHapticFeedback<sup>13+</sup>
852
853enableHapticFeedback(isEnabled: boolean)
854
855设置是否开启触控反馈。
856
857**原子化服务API:** 从API version 13开始,该接口支持在原子化服务中使用。
858
859**系统能力:** SystemCapability.ArkUI.ArkUI.Full
860
861**参数:**
862
863| 参数名 | 类型    | 必填 | 说明                               |
864| ------ | ------- | ---- | ---------------------------------- |
865| isEnabled | boolean | 是   | 是否开启触控反馈。<br/>true表示开启,false表示不开启。<br/>默认值:true |
866
867>  **说明:**
868>
869>  开启触控反馈时,需要在工程的module.json5中配置requestPermissions字段开启振动权限,配置如下:
870> ```json
871> "requestPermissions": [
872>  {
873>     "name": "ohos.permission.VIBRATE",
874>  }
875> ]
876> ```
877
878### caretColor<sup>14+</sup>
879
880caretColor(color: ResourceColor)
881
882设置文本框选中区域手柄颜色。
883
884**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
885
886**系统能力:** SystemCapability.ArkUI.ArkUI.Full
887
888**参数:**
889
890| 参数名 | 类型                                       | 必填 | 说明                                   |
891| ------ | ------------------------------------------ | ---- | -------------------------------------- |
892| color  | [ResourceColor](ts-types.md#resourcecolor) | 是   | 文本选中手柄颜色。<br/>默认值:'#007DFF' |
893
894### selectedBackgroundColor<sup>14+</sup>
895
896selectedBackgroundColor(color: ResourceColor)
897
898设置文本选中底板颜色。如果未设置不透明度,默认为20%不透明度。
899
900**原子化服务API:** 从API version 14开始,该接口支持在原子化服务中使用。
901
902**系统能力:** SystemCapability.ArkUI.ArkUI.Full
903
904**参数:**
905
906| 参数名 | 类型                                       | 必填 | 说明                                       |
907| ------ | ------------------------------------------ | ---- | ------------------------------------------ |
908| color  | [ResourceColor](ts-types.md#resourcecolor) | 是   | 文本选中底板颜色。<br/>默认为20%不透明度。<br/>默认值:'#007DFF' |
909
910### marqueeOptions<sup>18+</sup>
911
912marqueeOptions(options: Optional\<TextMarqueeOptions>)
913
914设置文本跑马灯模式的配置项。
915
916当textOverflow设置为TextOverflow.MARQUEE时,marqueeOptions的设置才能生效。
917
918**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
919
920**系统能力:** SystemCapability.ArkUI.ArkUI.Full
921
922**参数:**
923
924| 参数名 | 类型                                       | 必填 | 说明                                       |
925| ------ | ------------------------------------------ | ---- | ------------------------------------------ |
926| options | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[TextMarqueeOptions](#textmarqueeoptions18对象说明)> | 是 | 当text组件的textOverflow属性设置为MARQUEE时,可通过marqueeOptions设置跑马灯动效具体的属性,如开关、步长、循环次数、方向等。 |
927
928## TextSpanType<sup>11+</sup>枚举说明
929
930[Span](ts-basic-components-span.md)类型信息。
931
932**系统能力:** SystemCapability.ArkUI.ArkUI.Full
933
934| 名称 | 值 | 说明 |
935| -------- | ---- | -------- |
936| TEXT | 0 | Span为文字类型。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
937| IMAGE | 1 | Span为图像类型。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
938| MIXED | 2 | Span为图文混合类型。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
939| DEFAULT<sup>15+</sup> | 3 | 注册此类型菜单但未注册TEXT、IMAGE、MIXED菜单时,文字类型、图片类型、图文混合类型都会触发并显示此类型对应的菜单。<br/>**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 |
940
941>  **说明:**
942>
943>  菜单类型的匹配顺序如下。例如,用户长按文本时,根据以下规则查找:
944>  1. 查找是否注册了TextSpanType.TEXTTextResponseType.LONG_PRESS菜单
945>  2. 查找是否注册了TextSpanType.TEXTTextResponseType.DEFAULT菜单
946>  3. 查找是否注册了TextSpanType.DEFAULTTextResponseType.LONG_PRESS菜单
947>  4. 查找是否注册了TextSpanType.DEFAULTTextResponseType.DEFAULT菜单
948
949## TextResponseType<sup>11+</sup>枚举说明
950
951**系统能力:** SystemCapability.ArkUI.ArkUI.Full
952
953| 名称         | 值 |  说明          |
954| ---------- | --- | ------------- |
955| RIGHT_CLICK | 0 | 通过鼠标右键触发菜单弹出。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
956| LONG_PRESS  | 1 | 通过长按触发菜单弹出。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
957| SELECT | 2 | 通过鼠标选中触发菜单弹出。<br/>**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。 |
958| DEFAULT<sup>15+</sup> | 3 | 注册此类型的菜单但未注册RIGHT_CLICK、LONG_PRESS、SELECT时,右键、长按、鼠标选中都会触发并显示此类型对应的菜单。<br/>**原子化服务API:** 从API version 15开始,该接口支持在原子化服务中使用。 |
959
960>  **说明:**
961>
962>  菜单类型的匹配顺序如下。例如,用户长按文本时,根据以下规则查找:
963>  1. 查找是否注册了TextSpanType.TEXTTextResponseType.LONG_PRESS菜单
964>  2. 查找是否注册了TextSpanType.TEXTTextResponseType.DEFAULT菜单
965>  3. 查找是否注册了TextSpanType.DEFAULTTextResponseType.LONG_PRESS菜单
966>  4. 查找是否注册了TextSpanType.DEFAULTTextResponseType.DEFAULT菜单
967
968## TextOverflowOptions<sup>18+</sup>对象说明
969
970文本超长显示方式对象。
971
972**卡片能力:** 从API version 18开始,该接口支持在ArkTS卡片中使用。
973
974**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
975
976**系统能力:** SystemCapability.ArkUI.ArkUI.Full
977
978**参数:**
979
980| 名称 | 类型                                                         | 必填 | 说明                                                         |
981| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
982| overflow<sup>7+</sup>  | [TextOverflow](ts-appendix-enums.md#textoverflow) | 是   | 文本超长时的显示方式。<br/>默认值:TextOverflow.Clip <br/>**卡片能力:** 从API version 9开始,该接口支持在ArkTS卡片中使用。<br/>**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。 |
983
984## 事件
985
986除支持[通用事件](ts-component-general-events.md)外,还支持以下事件:
987
988### onCopy<sup>11+</sup>
989
990onCopy(callback:(value:&nbsp;string)&nbsp;=&gt;&nbsp;void)
991
992长按文本内部区域弹出剪贴板后,点击剪切板复制按钮,触发该回调。目前文本复制仅支持文本。
993
994**原子化服务API:** 从API version 11开始,该接口支持在原子化服务中使用。
995
996**系统能力:** SystemCapability.ArkUI.ArkUI.Full
997
998**参数:**
999
1000| 参数名 | 类型   | 必填 | 说明             |
1001| ------ | ------ | ---- | ---------------- |
1002| value  | string | 是   | 复制的文本内容。 |
1003
1004### onTextSelectionChange<sup>11+</sup>
1005
1006onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)
1007
1008文本选择的位置发生变化时,触发该回调。
1009
1010**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1011
1012**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1013
1014**参数:**
1015
1016| 参数名         | 类型   | 必填 | 说明                 |
1017| -------------- | ------ | ---- | -------------------- |
1018| selectionStart | number | 是   | 所选文本的起始位置。 |
1019| selectionEnd   | number | 是   | 所选文本的结束位置。 |
1020
1021### onMarqueeStateChange<sup>18+</sup>
1022
1023onMarqueeStateChange(callback: Callback\<MarqueeState\>)
1024
1025跑马灯动画进行到一些特定的阶段时,触发该回调。
1026
1027**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
1028
1029**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1030
1031**参数:**
1032
1033| 参数名    | 类型                                             | 必填  | 说明                       |
1034|--------|---------------------------------------------------|-----|--------------------------|
1035| callback  | Callback\<[MarqueeState](#marqueestate18枚举说明)\> | 是   | 通过callback参数指定触发回调的状态,状态由MarqueeState枚举定义,例如开始滚动、滚动一次、滚动完成。 |
1036
1037## TextOptions<sup>11+</sup>
1038
1039Text初始化参数。
1040
1041**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1042
1043**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1044
1045| 名称 | 类型 | 必填 | 说明 |
1046| -------- | -------- | -------- | -------- |
1047| controller | [TextController](#textcontroller11)  | 是 | 文本控制器。 |
1048
1049## TextController<sup>11+</sup>
1050
1051Text组件的控制器。
1052
1053**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1054
1055**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1056
1057### 导入对象
1058
1059```
1060controller: TextController = new TextController()
1061```
1062
1063### closeSelectionMenu
1064
1065closeSelectionMenu(): void
1066
1067关闭自定义选择菜单或系统默认选择菜单。
1068
1069**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1070
1071**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1072
1073### setStyledString<sup>12+</sup>
1074
1075setStyledString(value: StyledString): void
1076
1077触发绑定或更新属性字符串。
1078
1079**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1080
1081**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1082
1083**参数:**
1084
1085| 参数名   | 类型   | 必填   | 说明                |
1086| ----- | ------ | ---- | ------------------- |
1087| value | [StyledString](ts-universal-styled-string.md#styledstring) | 是    | 属性字符串。<br/>**说明:** <br/>StyledString的子类[MutableStyledString](ts-universal-styled-string.md#mutablestyledstring)也可以作为入参值。 |
1088
1089### getLayoutManager<sup>12+</sup>
1090
1091getLayoutManager(): LayoutManager
1092
1093获取布局管理器对象。
1094
1095**原子化服务API:** 从API version 12开始,该接口支持在原子化服务中使用。
1096
1097**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1098
1099**返回值:**
1100
1101| 类型                                       | 说明      |
1102| ---------------------------------------- | ------- |
1103| [LayoutManager](ts-text-common.md#LayoutManager) | 布局管理器对象。 |
1104
1105## TextMarqueeOptions<sup>18+</sup>对象说明
1106
1107Marquee初始化参数。
1108
1109**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
1110
1111**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1112
1113**参数:**
1114
1115| 名称                | 类型                                              | 必填 | 说明                                                                                  |
1116|--------------------|-------------------------------------------------|----|-------------------------------------------------------------------------------------|
1117| start              | boolean                                         | 是  | 控制跑马灯进入播放状态。<br/>true表示播放,false表示不播放。                           |
1118| step               | number                                          | 否  | 滚动动画文本滚动步长。<br/>默认值:4.0vp                                                           |
1119| loop               | number                                          | 否  | 设置重复滚动的次数,小于等于零时无限循环。<br/>默认值:-1                                                    |
1120| fromStart          | boolean                                         | 否  | 设置文本从头开始滚动或反向滚动。<br/>true表示从头开始滚动,false表示反向滚动。<br/>默认值:true                                                  |
1121| delay              | number                                          | 否  | 设置每次滚动的时间间隔。<br/>默认值:0 <br/>单位:毫秒                                                             |
1122| fadeout            | boolean                                         | 否  | 设置文字超长时的渐隐效果。<br/>true表示支持渐隐效果,false表示不支持渐隐效果。<br/>当Text内容超出显示范围时,未完全展现的文字边缘将应用渐隐效果。若两端均有文字未完全显示,则两端同时应用渐隐效果。在渐隐效果开启状态下,clip属性将自动锁定为true,不允许设置为false。<br/>默认值:false  |
1123| marqueeStartPolicy | [MarqueeStartPolicy](#marqueestartpolicy18枚举说明) | 否  | 设置跑马灯启动策略。<br/>默认值:MarqueeStartPolicy.DEFAULT                                       |
1124
1125## MarqueeStartPolicy<sup>18+</sup>枚举说明
1126
1127Marquee的滚动方式,可选择默认持续滚动或条件触发滚动。
1128
1129**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
1130
1131**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1132
1133| 名称        | 值 | 说明            |
1134|----------|----|---------------|
1135| DEFAULT  | 0  | 默认持续滚动。       |
1136| ON_FOCUS | 1  | 获焦以及鼠标悬浮时开始滚动。 |
1137
1138## MarqueeState<sup>18+</sup>枚举说明
1139
1140Marquee状态回调的返回值。
1141
1142**原子化服务API:** 从API version 18开始,该接口支持在原子化服务中使用。
1143
1144**系统能力:** SystemCapability.ArkUI.ArkUI.Full
1145
1146| 名称     | 值 | 说明                            |
1147|--------|----|-------------------------------|
1148| START  | 0  | 跑马灯滚动开始。                     |
1149| BOUNCE | 1  | 完成一次跑马灯滚动,如果循环次数不是1,将会多次返回。 |
1150| FINISH | 2  | 跑马灯全部循环次数完成。              |
1151
1152## 示例
1153
1154### 示例1(设置文本布局)
1155该示例通过textAlign、lineHeight、baselineOffset、halfLeading属性展示了文本布局的效果。
1156```ts
1157// xxx.ets
1158@Extend(Text)
1159function style(TextAlign: TextAlign) {
1160  .textAlign(TextAlign)
1161  .fontSize(12)
1162  .border({ width: 1 })
1163  .padding(10)
1164  .width('100%')
1165  .margin(5)
1166}
1167
1168@Entry
1169@Component
1170struct TextExample1 {
1171  @State changeTextAlignIndex: number = 0;
1172  @State changeDecorationIndex: number = 0;
1173  @State TextAlign: TextAlign[] = [TextAlign.Start, TextAlign.Center, TextAlign.End];
1174  @State TextAlignStr: string[] = ['Start', 'Center', 'End'];
1175  @State TextDecorationType: TextDecorationType[] =
1176    [TextDecorationType.LineThrough, TextDecorationType.Overline, TextDecorationType.Underline];
1177  @State TextDecorationTypeStr: string[] = ['LineThrough', 'Overline', 'Underline'];
1178  @State TextDecorationStyle: TextDecorationStyle[] =
1179    [TextDecorationStyle.SOLID, TextDecorationStyle.DOTTED, TextDecorationStyle.WAVY];
1180  @State TextDecorationStyleStr: string[] = ['SOLID', 'DOTTED', 'WAVY'];
1181
1182  build() {
1183    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1184      // 设置文本水平方向对齐方式
1185      // 单行文本
1186      Text('textAlign').fontSize(9).fontColor(0xCCCCCC)
1187      Text(`TextAlign set to ${this.TextAlignStr[this.changeTextAlignIndex]}.`)
1188        .style(this.TextAlign[this.changeTextAlignIndex])
1189
1190      // 多行文本
1191      Text(`This is the text content with textAlign set to ${this.TextAlignStr[this.changeTextAlignIndex]}.`)
1192        .style(this.TextAlign[this.changeTextAlignIndex])
1193        .margin(5)
1194
1195      Row() {
1196        Button('当前TextAlign类型:' + this.TextAlignStr[this.changeTextAlignIndex]).onClick(() => {
1197          this.changeTextAlignIndex++;
1198          if (this.changeTextAlignIndex > (this.TextAlignStr.length - 1)) {
1199            this.changeTextAlignIndex = 0;
1200          }
1201        })
1202      }.justifyContent(FlexAlign.Center).width('100%')
1203
1204      // 设置文本行高
1205      Text('lineHeight').fontSize(9).fontColor(0xCCCCCC)
1206      Text('This is the text with the line height set. This is the text with the line height set.')
1207        .style(TextAlign.Start)
1208      Text('This is the text with the line height set. This is the text with the line height set.')
1209        .style(TextAlign.Start)
1210        .lineHeight(20)
1211
1212      // 设置文本基线偏移
1213      Text('baselineOffset').fontSize(9).fontColor(0xCCCCCC)
1214      Text('This is the text content with baselineOffset 0.')
1215        .baselineOffset(0)
1216        .style(TextAlign.Start)
1217      Text('This is the text content with baselineOffset 30.')
1218        .baselineOffset(30)
1219        .style(TextAlign.Start)
1220      Text('This is the text content with baselineOffset -20.')
1221        .baselineOffset(-20)
1222        .style(TextAlign.Start)
1223
1224      // 设置文本是否居中对齐
1225      Text('halfLeading').fontSize(9).fontColor(0xCCCCCC)
1226      Text("This is the text with the halfLeading set.")
1227        .lineHeight(60)
1228        .halfLeading(true)
1229        .style(TextAlign.Start)
1230      Text("This is the text without the halfLeading set.")
1231        .lineHeight(60)
1232        .halfLeading(false)
1233        .style(TextAlign.Start)
1234    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
1235  }
1236}
1237```
1238![textExp1](figures/textExp1.gif)
1239
1240### 示例2(设置文本样式)
1241
1242该示例通过decoration、letterSpacing、textCase、fontFamily、textShadow、fontStyle、textIndent、fontWeight属性展示了不同样式的文本效果。
1243
1244```ts
1245@Extend(Text)
1246function style() {
1247  .font({ size: 12 })
1248  .border({ width: 1 })
1249  .padding(10)
1250  .width('100%')
1251  .margin(5)
1252}
1253
1254@Entry
1255@Component
1256struct TextExample2 {
1257  @State changeDecorationIndex: number = 0;
1258  @State TextDecorationType: TextDecorationType[] =
1259    [TextDecorationType.LineThrough, TextDecorationType.Overline, TextDecorationType.Underline];
1260  @State TextDecorationTypeStr: string[] = ['LineThrough', 'Overline', 'Underline'];
1261  @State TextDecorationStyle: TextDecorationStyle[] =
1262    [TextDecorationStyle.SOLID, TextDecorationStyle.DOTTED, TextDecorationStyle.WAVY];
1263  @State TextDecorationStyleStr: string[] = ['SOLID', 'DOTTED', 'WAVY'];
1264
1265  build() {
1266    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1267      Text('decoration').fontSize(9).fontColor(0xCCCCCC)
1268      Text('This is the text content with the decoration set to LineThrough and the color set to Red.')
1269        .decoration({
1270          type: this.TextDecorationType[this.changeDecorationIndex],
1271          color: Color.Red,
1272          style: this.TextDecorationStyle[this.changeDecorationIndex]
1273        })
1274        .style()
1275        .margin(5)
1276
1277      Row() {
1278        Button('当前decoration类型:' + this.TextDecorationTypeStr[this.changeDecorationIndex] + ' & ' +
1279        this.TextDecorationStyleStr[this.changeDecorationIndex]).onClick(() => {
1280          this.changeDecorationIndex++;
1281          if (this.changeDecorationIndex > (this.TextDecorationTypeStr.length - 1)) {
1282            this.changeDecorationIndex = 0;
1283          }
1284        })
1285      }.justifyContent(FlexAlign.Center).width('100%')
1286
1287      // 文本字符间距
1288      Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC)
1289      Text('This is the text content with letterSpacing 0.')
1290        .letterSpacing(0)
1291        .style()
1292      Text('This is the text content with letterSpacing 3.')
1293        .letterSpacing(3)
1294        .style()
1295      Text('This is the text content with letterSpacing -1.')
1296        .letterSpacing(-1)
1297        .style()
1298
1299      Text('textCase').fontSize(9).fontColor(0xCCCCCC)
1300      Text('This is the text content with textCase set to Normal.')
1301        .textCase(TextCase.Normal)
1302        .style()
1303      // 文本全小写展示
1304      Text('This is the text content with textCase set to LowerCase.')
1305        .textCase(TextCase.LowerCase)
1306        .style()
1307      // 文本全大写展示
1308      Text('This is the text content with textCase set to UpperCase.')
1309        .textCase(TextCase.UpperCase)
1310        .style()
1311
1312      Text('fontFamily').fontSize(9).fontColor(0xCCCCCC)
1313      // 设置字体列表
1314      Text('This is the text content with fontFamily')
1315        .style()
1316        .fontFamily('HarmonyOS Sans')
1317
1318      Text('textShadow').fontSize(9).fontColor(0xCCCCCC)
1319      // 设置文字阴影效果
1320      Text('textShadow')
1321        .style()
1322        .textAlign(TextAlign.Center)
1323        .fontSize(40)
1324        .textShadow({
1325          radius: 10,
1326          color: Color.Black,
1327          offsetX: 0,
1328          offsetY: 0
1329        })
1330
1331      Text('fontStyle').fontSize(9).fontColor(0xCCCCCC)
1332      // 设置字体样式
1333      Text('This is the text content with fontStyle set to Italic')
1334        .style()
1335        .fontStyle(FontStyle.Italic)
1336      Text('This is the text content with fontStyle set to Normal')
1337        .style()
1338        .fontStyle(FontStyle.Normal)
1339
1340      Text('textIndent').fontSize(9).fontColor(0xCCCCCC)
1341      // 设置文字缩进
1342      Text('This is the text content with textIndent 30')
1343        .style()
1344        .textIndent(30)
1345
1346      Text('fontWeight').fontSize(9).fontColor(0xCCCCCC)
1347      // 设置文本的字体粗细
1348      Text('This is the text content with fontWeight 800')
1349        .style()
1350        .fontWeight('800', { enableVariableFontWeight: true })
1351
1352    }.width('100%').padding({ left: 35, right: 35 })
1353  }
1354}
1355```
1356![textExp1](figures/textExp2.gif)
1357
1358### 示例3(设置文本超长省略)
1359
1360该示例通过maxLines、textOverflow、ellipsisMode属性展示了文本超长省略以及调整省略位置的效果。
1361
1362```ts
1363@Extend(Text)
1364function style() {
1365  .textAlign(TextAlign.Center)
1366  .fontSize(12)
1367  .border({ width: 1 })
1368  .padding(10)
1369  .width('100%')
1370  .margin(5)
1371}
1372
1373@Entry
1374@Component
1375struct TextExample3 {
1376  @State text: string =
1377    'The text component is used to display a piece of textual information.Support universal attributes and universal text attributes.';
1378  @State ellipsisModeIndex: number = 0;
1379  @State ellipsisMode: EllipsisMode[] = [EllipsisMode.START, EllipsisMode.CENTER, EllipsisMode.END];
1380  @State ellipsisModeStr: string[] = ['START', 'CENTER', 'END'];
1381
1382  build() {
1383    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1384      // 文本超长时显示方式
1385      Text('TextOverflow+maxLines').fontSize(9).fontColor(0xCCCCCC)
1386      // 超出maxLines截断内容展示
1387      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.')
1388        .textOverflow({ overflow: TextOverflow.Clip })
1389        .maxLines(1)
1390        .style()
1391
1392      // 超出maxLines展示省略号
1393      Text('This is set textOverflow to Ellipsis text content This is set textOverflow to Ellipsis text content.')
1394        .textOverflow({ overflow: TextOverflow.Ellipsis })
1395        .maxLines(1)
1396        .style()
1397
1398      Text('marquee').fontSize(9).fontColor(0xCCCCCC)
1399      // 设置文本超长时以跑马灯的方式展示
1400      Text('This is the text with the text overflow set marquee')
1401        .textOverflow({ overflow: TextOverflow.MARQUEE })
1402        .style()
1403        .marqueeOptions({
1404          start: true,
1405          fromStart: true,
1406          step: 6,
1407          loop: -1,
1408          delay: 0,
1409          fadeout: false,
1410          marqueeStartPolicy: MarqueeStartPolicy.DEFAULT
1411        })
1412        .onMarqueeStateChange((state: MarqueeState) => {
1413          if (state == MarqueeState.START) {
1414            // "收到状态: START";
1415          } else if (state == MarqueeState.BOUNCE) {
1416            // "收到状态: BOUNCE";
1417          } else if (state == MarqueeState.FINISH) {
1418            // "收到状态: FINISH";
1419          }
1420        })
1421
1422      Text('ellipsisMode').fontSize(9).fontColor(0xCCCCCC)
1423      // 设置文本超长时省略号的位置
1424      Text(this.text)
1425        .textOverflow({ overflow: TextOverflow.Ellipsis })
1426        .ellipsisMode(this.ellipsisMode[this.ellipsisModeIndex])
1427        .maxLines(1)
1428        .style()
1429
1430      Row() {
1431        Button('更改省略号位置:' + this.ellipsisModeStr[this.ellipsisModeIndex]).onClick(() => {
1432          this.ellipsisModeIndex++;
1433          if (this.ellipsisModeIndex > (this.ellipsisModeStr.length - 1)) {
1434            this.ellipsisModeIndex = 0;
1435          }
1436        })
1437      }
1438    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
1439  }
1440}
1441```
1442
1443![](figures/textExp3.gif)
1444
1445### 示例4(设置文本断行及折行)
1446
1447该示例通过wordBreak、lineBreakStrategy、clip属性展示了文本在不同断行、折行规则下的效果以及文本超长时是否截断。
1448
1449```ts
1450// xxx.ets
1451@Extend(Text)
1452function style() {
1453  .fontSize(12)
1454  .border({ width: 1 })
1455  .padding(10)
1456  .width('100%')
1457  .margin(5)
1458}
1459
1460@Entry
1461@Component
1462struct TextExample4 {
1463  @State text: string =
1464    'The text component is used to display a piece of textual information.Support universal attributes and universal text attributes.';
1465  @State text2: string =
1466    "They can be classified as built-in components–those directly provided by the ArkUI framework and custom components – those defined by developers" +
1467      "The built-in components include buttons radio buttons progress indicators and text You can set the rendering effect of these components in method chaining mode," +
1468      "page components are divided into independent UI units to implement independent creation development and reuse of different units on pages making pages more engineering-oriented.";
1469  @State textClip: boolean = false;
1470  @State wordBreakIndex: number = 0;
1471  @State wordBreak: WordBreak[] = [WordBreak.NORMAL, WordBreak.BREAK_ALL, WordBreak.BREAK_WORD];
1472  @State wordBreakStr: string[] = ['NORMAL', 'BREAK_ALL', 'BREAK_WORD'];
1473  @State lineBreakStrategyIndex: number = 0;
1474  @State lineBreakStrategy: LineBreakStrategy[] =
1475    [LineBreakStrategy.GREEDY, LineBreakStrategy.HIGH_QUALITY, LineBreakStrategy.BALANCED];
1476  @State lineBreakStrategyStr: string[] = ['GREEDY', 'HIGH_QUALITY', 'BALANCED'];
1477
1478  build() {
1479    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1480      Text('wordBreak').fontSize(9).fontColor(0xCCCCCC)
1481      // 设置文本断行规则
1482      Text(this.text)
1483        .maxLines(2)
1484        .textOverflow({ overflow: TextOverflow.Ellipsis })
1485        .wordBreak(this.wordBreak[this.wordBreakIndex])
1486        .style()
1487
1488      Row() {
1489        Button('当前wordBreak模式:' + this.wordBreakStr[this.wordBreakIndex]).onClick(() => {
1490          this.wordBreakIndex++;
1491          if (this.wordBreakIndex > (this.wordBreakStr.length - 1)) {
1492            this.wordBreakIndex = 0;
1493          }
1494        })
1495      }
1496
1497      Text('clip').fontSize(9).fontColor(0xCCCCCC)
1498      // 设置文本是否超长截断
1499      Text('This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.')
1500        .wordBreak(WordBreak.NORMAL)
1501        .maxLines(2)
1502        .clip(this.textClip)
1503        .style()
1504      Row() {
1505        Button('切换clip:' + this.textClip).onClick(() => {
1506          this.textClip = !this.textClip;
1507        })
1508      }
1509
1510      Text('lineBreakStrategy').fontSize(9).fontColor(0xCCCCCC)
1511      // 设置文本折行规则
1512      Text(this.text2)
1513        .lineBreakStrategy(this.lineBreakStrategy[this.lineBreakStrategyIndex])
1514        .style()
1515      Row() {
1516        Button('当前lineBreakStrategy模式:' + this.lineBreakStrategyStr[this.lineBreakStrategyIndex]).onClick(() => {
1517          this.lineBreakStrategyIndex++;
1518          if (this.lineBreakStrategyIndex > (this.lineBreakStrategyStr.length - 1)) {
1519            this.lineBreakStrategyIndex = 0;
1520          }
1521        })
1522      }
1523    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
1524  }
1525}
1526```
1527
1528![](figures/textExp4.gif)
1529
1530### 示例5(设置文本选中和复制)
1531
1532该示例通过selection、onCopy、draggable、caretColor、selectedBackgroundColor接口展示了文本选中、触发复制回调、设置文本选中可拖拽以及修改手柄和选中颜色的效果。
1533
1534```ts
1535// xxx.ets
1536@Entry
1537@Component
1538struct TextExample5 {
1539  @State onCopy: string = '';
1540  @State text: string =
1541    'This is set selection to Selection text content This is set selection to Selection text content.';
1542  @State start: number = 0;
1543  @State end: number = 20;
1544
1545  build() {
1546    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) {
1547      Text(this.text)
1548        .fontSize(12)
1549        .border({ width: 1 })
1550        .lineHeight(20)
1551        .margin(30)
1552        .copyOption(CopyOptions.InApp)
1553        .selection(this.start, this.end)
1554        .onCopy((value: string) => {
1555          this.onCopy = value;
1556        })
1557        .draggable(true)
1558        .caretColor(Color.Red)
1559        .selectedBackgroundColor(Color.Grey)
1560        .enableHapticFeedback(true)
1561      Button('Set text selection')
1562        .margin({ left: 20 })
1563        .onClick(() => {
1564          // 变更文本选中起始点、终点
1565          this.start = 10;
1566          this.end = 30;
1567        })
1568      Text(this.onCopy).fontSize(12).margin(10).key('copy')
1569    }.height(600).width(335).padding({ left: 35, right: 35, top: 35 })
1570  }
1571}
1572```
1573![](figures/textExample5.png)
1574
1575### 示例6(设置文本自适应和缩放倍数限制范围)
1576
1577该示例通过heightAdaptivePolicy属性展示文本自适应效果以及通过minFontScale、maxFontScale展示设置字体缩放倍数限制范围。
1578
1579```ts
1580// xxx.ets
1581@Extend(Text)
1582function style(HeightAdaptivePolicy: TextHeightAdaptivePolicy) {
1583  .width('80%')
1584  .height(90)
1585  .borderWidth(1)
1586  .minFontSize(10)
1587  .maxFontSize(30)
1588  .maxLines(2)
1589  .margin(5)
1590  .textOverflow({ overflow: TextOverflow.Ellipsis })
1591  .heightAdaptivePolicy(HeightAdaptivePolicy)
1592}
1593
1594@Entry
1595@Component
1596struct TextExample6 {
1597  build() {
1598    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1599      // 设置文本自适应高度的方式
1600      Text('heightAdaptivePolicy').fontSize(9).fontColor(0xCCCCCC)
1601      Text('This is the text with the height adaptive policy set.')
1602        .style(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
1603      Text('This is the text with the height adaptive policy set.')
1604        .style(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST)
1605      Text('This is the text with the height adaptive policy set.')
1606        .style(TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST)
1607
1608      Text('fontScale').fontSize(9).fontColor(0xCCCCCC)
1609      Text('This is the text content with minFontScale set to 1 and maxFontScale set to 1.2')
1610        .style(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
1611        .minFontScale(1)
1612        .maxFontScale(1.2)
1613    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
1614  }
1615}
1616```
1617
1618![textHeightAdaptivePolicy](figures/textHeightAdaptivePolicy.PNG)
1619
1620### 示例7(设置文本识别)
1621
1622该示例通过enableDataDetector、dataDetectorConfig接口实现了文本识别的功能。
1623
1624```ts
1625// xxx.ets
1626@Entry
1627@Component
1628struct TextExample7 {
1629  @State phoneNumber: string = '(86) (755) ********';
1630  @State url: string = 'www.********.com';
1631  @State email: string = '***@example.com';
1632  @State address: string = 'XX省XX市XX区XXXX';
1633  @State datetime: string = 'XX年XX月XX日XXXX';
1634  @State enableDataDetector: boolean = true;
1635  @State types: TextDataDetectorType[] = [];
1636
1637  build() {
1638    Row() {
1639      Column() {
1640        Text(
1641          '电话号码:' + this.phoneNumber + '\n' +
1642            '链接:' + this.url + '\n' +
1643            '邮箱:' + this.email + '\n' +
1644            '地址:' + this.address + '\n' +
1645            '时间:' + this.datetime
1646        )
1647          .fontSize(16)
1648          .copyOption(CopyOptions.InApp)
1649          .enableDataDetector(this.enableDataDetector)
1650          .dataDetectorConfig({
1651            types: this.types, onDetectResultUpdate: (result: string) => {
1652            }
1653          })
1654          .textAlign(TextAlign.Center)
1655          .borderWidth(1)
1656          .padding(10)
1657          .width('100%')
1658      }
1659      .width('100%')
1660      // 使用parallelGesture中的TapGesture替代onClick属性,达到非冒泡事件类似冒泡
1661      // 的效果,点击Text组件区域Column上的点击事件正常响应
1662      .parallelGesture(TapGesture().onAction((event: GestureEvent) => {
1663        console.log('test column onClick timestamp:' + event.timestamp);
1664      }), GestureMask.Normal)
1665    }
1666    .height('100%')
1667  }
1668}
1669```
1670
1671![](figures/text7.png)
1672
1673### 示例8(文本绑定自定义菜单)
1674
1675该示例通过bindSelectionMenu、onTextSelectionChange、closeSelectionMenu接口实现了文本绑定自定义菜单的功能。
1676
1677```ts
1678// xxx.ets
1679@Entry
1680@Component
1681struct TextExample8 {
1682  controller: TextController = new TextController();
1683  options: TextOptions = { controller: this.controller };
1684
1685  build() {
1686    Column() {
1687      Column() {
1688        Text(undefined, this.options) {
1689          Span('Hello World')
1690          ImageSpan($r('app.media.icon'))
1691            .width('100px')
1692            .height('100px')
1693            .objectFit(ImageFit.Fill)
1694            .verticalAlign(ImageSpanAlignment.CENTER)
1695        }
1696        .copyOption(CopyOptions.InApp)
1697        .bindSelectionMenu(TextSpanType.IMAGE, this.LongPressImageCustomMenu, TextResponseType.LONG_PRESS, {
1698          onDisappear: () => {
1699            console.info(`自定义选择菜单关闭时回调`);
1700          },
1701          onAppear: () => {
1702            console.info(`自定义选择菜单弹出时回调`);
1703          }
1704        })
1705        .bindSelectionMenu(TextSpanType.TEXT, this.RightClickTextCustomMenu, TextResponseType.RIGHT_CLICK)
1706        .bindSelectionMenu(TextSpanType.MIXED, this.SelectMixCustomMenu, TextResponseType.SELECT)
1707        .onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
1708          console.info(`文本选中区域变化回调, selectionStart: ${selectionStart}, selectionEnd: ${selectionEnd}`);
1709        })
1710        .borderWidth(1)
1711        .borderColor(Color.Red)
1712        .width(200)
1713        .height(100)
1714      }
1715      .width('100%')
1716      .backgroundColor(Color.White)
1717      .alignItems(HorizontalAlign.Start)
1718      .padding(25)
1719    }
1720    .height('100%')
1721  }
1722
1723  @Builder
1724  RightClickTextCustomMenu() {
1725    Column() {
1726      Menu() {
1727        MenuItemGroup() {
1728          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 1", labelInfo: "" })
1729            .onClick((event) => {
1730              this.controller.closeSelectionMenu();
1731            })
1732          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 2", labelInfo: "" })
1733          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 3", labelInfo: "" })
1734        }
1735      }
1736      .MenuStyles()
1737    }
1738  }
1739
1740  @Builder
1741  LongPressImageCustomMenu() {
1742    Column() {
1743      Menu() {
1744        MenuItemGroup() {
1745          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 1", labelInfo: "" })
1746            .onClick((event) => {
1747              this.controller.closeSelectionMenu();
1748            })
1749          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 2", labelInfo: "" })
1750          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 3", labelInfo: "" })
1751        }
1752      }
1753      .MenuStyles()
1754    }
1755  }
1756
1757  @Builder
1758  SelectMixCustomMenu() {
1759    Column() {
1760      Menu() {
1761        MenuItemGroup() {
1762          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 1", labelInfo: "" })
1763            .onClick((event) => {
1764              this.controller.closeSelectionMenu();
1765            })
1766          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 2", labelInfo: "" })
1767          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 3", labelInfo: "" })
1768        }
1769      }
1770      .MenuStyles()
1771    }
1772  }
1773}
1774
1775@Extend(Menu)
1776function MenuStyles() {
1777  .radius($r('sys.float.ohos_id_corner_radius_card'))
1778  .clip(true)
1779  .backgroundColor('#F0F0F0')
1780}
1781```
1782
1783![](figures/textBindSelectionMenu.gif)
1784
1785### 示例9(设置文本特性与行间距)
1786
1787该示例通过fontFeature、lineSpacing接口展示了设置文本特性与行间距的效果。
1788
1789```ts
1790// xxx.ets
1791import { LengthMetrics } from '@kit.ArkUI'
1792
1793@Extend(Text)
1794function style() {
1795  .fontSize(12)
1796  .border({ width: 1 })
1797  .width('100%')
1798}
1799
1800@Entry
1801@Component
1802struct TextExample9 {
1803  build() {
1804    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
1805      Text('lineSpacing').fontSize(9).fontColor(0xCCCCCC)
1806      // 设置文本行间距
1807      Text('This is a context with no lineSpacing set.')
1808        .lineSpacing(undefined)
1809        .style()
1810      Text('This is a context with lineSpacing set to 20_px.')
1811        .lineSpacing(LengthMetrics.px(20))
1812        .style()
1813      Text('This is the context with lineSpacing set to 20_vp.')
1814        .lineSpacing(LengthMetrics.vp(20))
1815        .style()
1816      Text('This is the context with lineSpacing set to 20_fp.')
1817        .lineSpacing(LengthMetrics.fp(20))
1818        .style()
1819      Text('This is the context with lineSpacing set to 20_lpx.')
1820        .lineSpacing(LengthMetrics.lpx(20))
1821        .style()
1822      Text('This is the context with lineSpacing set to 100%.')
1823        .lineSpacing(LengthMetrics.percent(1))
1824        .style()
1825
1826      Text('fontFeature').fontSize(9).fontColor(0xCCCCCC)
1827      // 设置文本特性
1828      Text('This is ss01 on : 0123456789')
1829        .fontFeature("\"ss01\" on")
1830        .style()
1831      Text('This is ss01 off: 0123456789')
1832        .fontFeature("\"ss01\" off")
1833        .style()
1834    }.height(300).width(350).padding({ left: 35, right: 35, top: 35 })
1835  }
1836}
1837```
1838
1839![](figures/TextExample8.PNG)
1840
1841### 示例10(获取文本信息)
1842
1843该示例通过getLayoutManager接口调用文本的布局管理对象获取文本信息。
1844
1845```ts
1846// xxx.ets
1847import { text } from '@kit.ArkGraphics2D'
1848
1849@Entry
1850@Component
1851struct TextExample10 {
1852  @State lineCount: string = "";
1853  @State glyphPositionAtCoordinate: string = "";
1854  @State lineMetrics: string = "";
1855  @State rectsForRangeStr: string = "";
1856  controller: TextController = new TextController();
1857  @State textStr: string =
1858    'Hello World! 您好,世界!';
1859
1860  build() {
1861    Scroll() {
1862      Column() {
1863        Text('Text组件getLayoutManager接口获取段落相对组件的信息')
1864          .fontSize(15)
1865          .fontColor(0xCCCCCC)
1866          .width('90%')
1867          .padding(10)
1868        Text(this.textStr, { controller: this.controller })
1869          .fontSize(25)
1870          .borderWidth(1)
1871          .onAreaChange(() => {
1872            let layoutManager: LayoutManager = this.controller.getLayoutManager();
1873            this.lineCount = "LineCount: " + layoutManager.getLineCount();
1874          })
1875
1876        Text('LineCount').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
1877        Text(this.lineCount)
1878
1879        Text('GlyphPositionAtCoordinate').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
1880        Button("相对组件坐标[150,50]字形信息")
1881          .onClick(() => {
1882            let layoutManager: LayoutManager = this.controller.getLayoutManager();
1883            let position: PositionWithAffinity = layoutManager.getGlyphPositionAtCoordinate(150, 50);
1884            this.glyphPositionAtCoordinate =
1885              "相对组件坐标[150,50] glyphPositionAtCoordinate position: " + position.position + " affinity: " +
1886              position.affinity;
1887          })
1888          .margin({ bottom: 20, top: 10 })
1889        Text(this.glyphPositionAtCoordinate)
1890
1891        Text('LineMetrics').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
1892        Button("首行行信息、文本样式信息、以及字体属性信息")
1893          .onClick(() => {
1894            let layoutManager: LayoutManager = this.controller.getLayoutManager();
1895            let lineMetrics: LineMetrics = layoutManager.getLineMetrics(0);
1896            this.lineMetrics = "lineMetrics is " + JSON.stringify(lineMetrics) + "\n\n";
1897            let runMetrics = lineMetrics.runMetrics;
1898            runMetrics.forEach((value, key) => {
1899              this.lineMetrics += "runMetrics key is " + key + " " + JSON.stringify(value) + "\n\n";
1900            })
1901          })
1902          .margin({ bottom: 20, top: 10 })
1903        Text(this.lineMetrics)
1904
1905        Text('getRectsForRange').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
1906        Button("获取指定矩形宽度和高度下,文本中任意区间范围内字符或占位符的绘制区域信息")
1907          .onClick(() => {
1908            let layoutManager: LayoutManager = this.controller.getLayoutManager();
1909            let range: TextRange = { start: 0, end: 1 };
1910            let rectsForRangeInfo: text.TextBox[] =
1911              layoutManager.getRectsForRange(range, text.RectWidthStyle.TIGHT, text.RectHeightStyle.TIGHT);
1912            this.rectsForRangeStr = "getRectsForRange result is " + "\n\n";
1913            rectsForRangeInfo.forEach((value, key) => {
1914              this.rectsForRangeStr += "rectsForRange key is " + key + " " + JSON.stringify(value) + "\n\n";
1915            })
1916          })
1917          .margin({ bottom: 20, top: 10 })
1918        Text(this.rectsForRangeStr)
1919      }
1920      .margin({ top: 100, left: 8, right: 8 })
1921    }
1922  }
1923}
1924```
1925
1926![textLayoutManager](figures/textLayoutManager.gif)
1927
1928### 示例11(实现键盘框选文本)
1929
1930该示例通过textSelectable属性实现了设置TextSelectMode.SELECTABLE_FOCUSABLE属性时能够触发键盘框选文本功能。
1931
1932```ts
1933// xxx.ets
1934@Entry
1935@Component
1936struct TextExample11 {
1937  @State message: string =
1938    'TextTextTextTextTextTextTextText' + 'TextTextTextTextTextTextTextTextTextTextTextTextTextTextTextText';
1939
1940  build() {
1941    Column() {
1942      Text(this.message)
1943        .width(300)
1944        .height(100)
1945        .maxLines(5)
1946        .fontColor(Color.Black)
1947        .copyOption(CopyOptions.InApp)
1948        .selection(3, 8)
1949        .textSelectable(TextSelectableMode.SELECTABLE_FOCUSABLE)
1950    }.width('100%').margin({ top: 100 })
1951  }
1952}
1953```
1954
1955![textTextSelectableMode](figures/textTextSelectableMode.gif)
1956
1957### 示例12(文本扩展自定义菜单)
1958
1959该示例通过editMenuOptions接口实现了文本设置自定义菜单扩展项的文本内容、图标以及回调的功能。
1960
1961```ts
1962// xxx.ets
1963@Entry
1964@Component
1965struct TextExample12 {
1966  @State text: string = 'Text editMenuOptions'
1967  onCreateMenu = (menuItems: Array<TextMenuItem>) => {
1968    let item1: TextMenuItem = {
1969      content: 'custom1',
1970      icon: $r('app.media.startIcon'),
1971      id: TextMenuItemId.of('custom1'),
1972    };
1973    let item2: TextMenuItem = {
1974      content: 'custom2',
1975      id: TextMenuItemId.of('custom2'),
1976      icon: $r('app.media.startIcon'),
1977    };
1978    menuItems.push(item1);
1979    menuItems.unshift(item2);
1980    return menuItems;
1981  }
1982  onMenuItemClick = (menuItem: TextMenuItem, textRange: TextRange) => {
1983    if (menuItem.id.equals(TextMenuItemId.of("custom2"))) {
1984      console.log("拦截 id: custom2 start:" + textRange.start + "; end:" + textRange.end);
1985      return true;
1986    }
1987    if (menuItem.id.equals(TextMenuItemId.COPY)) {
1988      console.log("拦截 COPY start:" + textRange.start + "; end:" + textRange.end);
1989      return true;
1990    }
1991    if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) {
1992      console.log("不拦截 SELECT_ALL start:" + textRange.start + "; end:" + textRange.end);
1993      return false;
1994    }
1995    return false;
1996  };
1997  @State editMenuOptions: EditMenuOptions = {
1998    onCreateMenu: this.onCreateMenu, onMenuItemClick: this.onMenuItemClick
1999  };
2000
2001  build() {
2002    Column() {
2003      Text(this.text)
2004        .fontSize(20)
2005        .copyOption(CopyOptions.LocalDevice)
2006        .editMenuOptions(this.editMenuOptions)
2007        .margin({ top: 100 })
2008    }
2009    .width("90%")
2010    .margin("5%")
2011  }
2012}
2013```
2014
2015![textEditMenuOptions](figures/textEditMenuOptions.gif)
2016
2017### 示例13(配置隐私隐藏)
2018
2019该示例通过privacySensitive属性展示了文本如何配置隐私隐藏的效果,实际显示需要卡片框架支持。
2020
2021```ts
2022// xxx.ets
2023@Entry
2024@Component
2025struct TextExample13 {
2026  build() {
2027    Column({ space: 10 }) {
2028      Text("privacySensitive")
2029        .privacySensitive(true)
2030        .margin({ top: 30 })
2031    }
2032    .alignItems(HorizontalAlign.Center)
2033    .width("100%")
2034  }
2035}
2036```
2037
2038![textPrivacySensitive](figures/textPrivacySensitive.gif)