• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Text
2
3The **Text** component is used to display a piece of textual information.
4
5>  **NOTE**
6>
7>  This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
8
9
10## Child Components
11
12This component can contain the [Span](ts-basic-components-span.md), [ImageSpan](ts-basic-components-imagespan.md), [SymbolSpan](ts-basic-components-symbolSpan.md), and [ContainerSpan](ts-basic-components-containerspan.md) child components.
13
14## APIs
15
16Text(content?: string | Resource , value?: TextOptions)
17
18**Widget capability**: This API can be used in ArkTS widgets since API version 9.
19
20**Atomic service API**: This API can be used in atomic services since API version 11.
21
22**System capability**: SystemCapability.ArkUI.ArkUI.Full
23
24**Parameters**
25
26| Name| Type| Mandatory| Description|
27| -------- | -------- | -------- | -------- |
28| content | string \| [Resource](ts-types.md#resource) | No| Text content. This parameter does not take effect if the component contains a **Span** child component and does not have any [styled string](ts-universal-styled-string.md#styled-string) configured. In this case, the span content is displayed, and the style of the component does not take effect.<br>Default value: **' '**|
29| value<sup>11+</sup> | [TextOptions](#textoptions11) | No| Initialization options of the component.|
30
31## Attributes
32
33In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported.
34
35### textAlign
36
37textAlign(value: TextAlign)
38
39Sets the horizontal alignment mode of the text.
40
41The text takes up the full width of the **Text** component.
42
43To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text. Yet, it can work with the **textAlign** attribute to jointly determine the horizontal position of the text.
44
45When **textAlign** is set to **TextAlign.JUSTIFY**, you must set the [wordBreak](#wordbreak11) attribute, and the text in the last line is horizontally aligned with the start edge.
46
47**Widget capability**: This API can be used in ArkTS widgets since API version 9.
48
49**Atomic service API**: This API can be used in atomic services since API version 11.
50
51**System capability**: SystemCapability.ArkUI.ArkUI.Full
52
53**Parameters**
54
55| Name| Type                                       | Mandatory| Description                                                      |
56| ------ | ------------------------------------------- | ---- | ---------------------------------------------------------- |
57| value  | [TextAlign](ts-appendix-enums.md#textalign) | Yes  | Horizontal alignment of the text.<br>Default value: **TextAlign.Start** on non-wearable devices and **TextAlign.Center** on wearable devices|
58
59### textOverflow
60
61textOverflow(options: TextOverflowOptions)
62
63Sets the display mode when the text is too long.
64
65Text is clipped at the transition between words. To clip text in the middle of a word, add **\u200B** between characters. Since API version 11, preferably set the **wordBreak** attribute to **WordBreak.BREAK_ALL** to achieve the same purpose. For details, see [Example 4](#example-4-setting-text-wrapping-and-line-breaking).
66
67If **overflow** is set to **TextOverflow.None**, **TextOverflow.Clip**, or **TextOverflow.Ellipsis**, this attribute must be used with **maxLines** for the settings to take effect. **TextOverflow.None** produces the same effect as **TextOverflow.Clip**.
68
69If **overflow** is set to **TextOverflow.MARQUEE**, the text scrolls in a line, and neither **maxLines** nor **copyOption** takes effect. The **textAlign** attribute takes effect only when the text is not scrollable. With **overflow** set to **TextOverflow.MARQUEE**, the **clip** attribute is set to **true** by default. **TextOverflow.MARQUEE** is not available for [CustomSpan](ts-universal-styled-string.md#customspan) of the styled string.
70
71Since API version 12, **TextOverflow.MARQUEE** is available for the **ImageSpan** component, where the text and images are displayed in scrolling mode in a line.
72
73**Widget capability**: This API can be used in ArkTS widgets since API version 9.
74
75**Atomic service API**: This API can be used in atomic services since API version 11.
76
77**System capability**: SystemCapability.ArkUI.ArkUI.Full
78
79**Parameters**
80
81| Name| Type                                                        | Mandatory| Description                                                        |
82| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
83| options | [TextOverflowOptions](#textoverflowoptions18) | Yes  | Display mode when the text is too long.|
84
85### maxLines
86
87maxLines(value: number)
88
89Sets the maximum number of lines in the text. By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use [textOverflow](#textoverflow) to specify how it is displayed.
90
91**Widget capability**: This API can be used in ArkTS widgets since API version 9.
92
93**Atomic service API**: This API can be used in atomic services since API version 11.
94
95**System capability**: SystemCapability.ArkUI.ArkUI.Full
96
97**Parameters**
98
99| Name| Type  | Mandatory| Description            |
100| ------ | ------ | ---- | ---------------- |
101| value  | number | Yes  | Maximum number of lines in the text.|
102
103### lineHeight
104
105lineHeight(value: number | string | Resource)
106
107Sets the text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value is of the number type, the unit fp is used. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported.
108
109**Widget capability**: This API can be used in ArkTS widgets since API version 9.
110
111**Atomic service API**: This API can be used in atomic services since API version 11.
112
113**System capability**: SystemCapability.ArkUI.ArkUI.Full
114
115**Parameters**
116
117| Name| Type                                                        | Mandatory| Description            |
118| ------ | ------------------------------------------------------------ | ---- | ---------------- |
119| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Text line height.|
120
121### decoration
122
123decoration(value: DecorationStyleInterface)
124
125Sets the color, type, and style of the text decorative line.
126
127**Widget capability**: This API can be used in ArkTS widgets since API version 9.
128
129**Atomic service API**: This API can be used in atomic services since API version 11.
130
131**System capability**: SystemCapability.ArkUI.ArkUI.Full
132
133**Parameters**
134
135| Name| Type                                                        | Mandatory| Description                                                        |
136| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
137| value  | [DecorationStyleInterface<sup>12+</sup>](ts-universal-styled-string.md#decorationstyleinterface) | Yes  | Style of the text decorative line.<br>Default value:<br>{<br> type: TextDecorationType.None,<br> color: Color.Black,<br> style: TextDecorationStyle.SOLID <br>}<br>**NOTE**<br>The **style** parameter cannot be used in widgets.|
138
139### baselineOffset
140
141baselineOffset(value: number | string)
142
143Sets the offset of the text baseline. If the value specified is a percentage, the default value is used.
144
145Positive values shift the content upwards, while negative values shift it downwards.
146
147**Widget capability**: This API can be used in ArkTS widgets since API version 9.
148
149**Atomic service API**: This API can be used in atomic services since API version 11.
150
151**System capability**: SystemCapability.ArkUI.ArkUI.Full
152
153**Parameters**
154
155| Name| Type                      | Mandatory| Description                            |
156| ------ | -------------------------- | ---- | -------------------------------- |
157| value  | number \| string | Yes  | Offset of the text baseline.<br>Default value: **0**|
158
159### letterSpacing
160
161letterSpacing(value: number | string)
162
163Sets the letter spacing for a text style. If the value specified is a percentage or 0, the default value is used. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported.
164
165If the value specified is a negative value, the text is compressed. A negative value too small may result in the text being compressed to 0 and no content being displayed.
166
167**Widget capability**: This API can be used in ArkTS widgets since API version 9.
168
169**Atomic service API**: This API can be used in atomic services since API version 11.
170
171**System capability**: SystemCapability.ArkUI.ArkUI.Full
172
173**Parameters**
174
175| Name| Type                      | Mandatory| Description          |
176| ------ | -------------------------- | ---- | -------------- |
177| value  | number \| string | Yes  | Letter spacing.<br>Unit: fp|
178
179### minFontSize
180
181minFontSize(value: number | string | Resource)
182
183Sets the minimum font size. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported.
184
185For the setting to take effect, this attribute must be used together with [maxFontSize](#maxfontsize) and [maxLines](#maxlines), or layout constraint settings.
186
187When the adaptive font size is used, the **fontSize** settings do not take effect.
188
189If the value of **minFontSize** is less than or equal to 0, font size adaptation does not take effect. In this case, the actual font size is determined by the value of [fontSize](#fontsize). If [fontSize](#fontsize) is not specified, the default value is used.
190
191Since API version 18, this attribute takes effect on child components and styled strings, and the adaptive font size is applied to parts where the font size is not set.
192
193**Widget capability**: This API can be used in ArkTS widgets since API version 9.
194
195**Atomic service API**: This API can be used in atomic services since API version 11.
196
197**System capability**: SystemCapability.ArkUI.ArkUI.Full
198
199**Parameters**
200
201| Name| Type                                                        | Mandatory| Description              |
202| ------ | ------------------------------------------------------------ | ---- | ------------------ |
203| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Minimum font size.<br>Unit: fp|
204
205### maxFontSize
206
207maxFontSize(value: number | string | Resource)
208
209Sets the maximum font size. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported.
210
211For the setting to take effect, this attribute must be used together with [minFontSize](#minfontsize) and [maxLines](#maxlines), or layout constraint settings.
212
213When the adaptive font size is used, the **fontSize** settings do not take effect.
214
215If the value of **maxFontSize** is less than or equal to 0, font size adaptation does not take effect. In this case, the actual font size is determined by the value of [fontSize](#fontsize). If [fontSize](#fontsize) is not specified, the default value is used.
216
217Since API version 18, this attribute takes effect on child components and styled strings, and the adaptive font size is applied to parts where the font size is not set.
218
219**Widget capability**: This API can be used in ArkTS widgets since API version 9.
220
221**Atomic service API**: This API can be used in atomic services since API version 11.
222
223**System capability**: SystemCapability.ArkUI.ArkUI.Full
224
225**Parameters**
226
227| Name| Type                                                        | Mandatory| Description              |
228| ------ | ------------------------------------------------------------ | ---- | ------------------ |
229| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Maximum font size.<br>Unit: fp|
230
231### textCase
232
233textCase(value: TextCase)
234
235Sets the text case.
236
237**Widget capability**: This API can be used in ArkTS widgets since API version 9.
238
239**Atomic service API**: This API can be used in atomic services since API version 11.
240
241**System capability**: SystemCapability.ArkUI.ArkUI.Full
242
243**Parameters**
244
245| Name| Type                                     | Mandatory| Description                                     |
246| ------ | ----------------------------------------- | ---- | ----------------------------------------- |
247| value  | [TextCase](ts-appendix-enums.md#textcase) | Yes  | Text case.<br>Default value: **TextCase.Normal**|
248
249### fontColor
250
251fontColor(value: ResourceColor)
252
253Sets the font color. The default value on wearable devices is **'#dbffffff'**.
254
255**Widget capability**: This API can be used in ArkTS widgets since API version 9.
256
257**Atomic service API**: This API can be used in atomic services since API version 11.
258
259**System capability**: SystemCapability.ArkUI.ArkUI.Full
260
261**Parameters**
262
263| Name| Type                                      | Mandatory| Description      |
264| ------ | ------------------------------------------ | ---- | ---------- |
265| value  | [ResourceColor](ts-types.md#resourcecolor) | Yes  | Font color.|
266
267### fontSize
268
269fontSize(value: number | string | Resource)
270
271Sets the text size. The default value on wearable devices is **5fp**.
272
273**Widget capability**: This API can be used in ArkTS widgets since API version 9.
274
275**Atomic service API**: This API can be used in atomic services since API version 11.
276
277**System capability**: SystemCapability.ArkUI.ArkUI.Full
278
279**Parameters**
280
281| Name| Type                                                        | Mandatory| Description                                                        |
282| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
283| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Font size. If **fontSize** is of the number type, the unit fp is used. The default font size is 16 fp. This parameter cannot be set in percentage.|
284
285### fontStyle
286
287fontStyle(value: FontStyle)
288
289Sets the font style.
290
291**Widget capability**: This API can be used in ArkTS widgets since API version 9.
292
293**Atomic service API**: This API can be used in atomic services since API version 11.
294
295**System capability**: SystemCapability.ArkUI.ArkUI.Full
296
297**Parameters**
298
299| Name| Type                                       | Mandatory| Description                                   |
300| ------ | ------------------------------------------- | ---- | --------------------------------------- |
301| value  | [FontStyle](ts-appendix-enums.md#fontstyle) | Yes  | Font style.<br>Default value: **FontStyle.Normal**|
302
303### fontWeight
304
305fontWeight(value: number | FontWeight | string)
306
307Sets the font weight. If the value is too large, the text may be clipped depending on the font.
308
309**Widget capability**: This API can be used in ArkTS widgets since API version 9.
310
311**Atomic service API**: This API can be used in atomic services since API version 11.
312
313**System capability**: SystemCapability.ArkUI.ArkUI.Full
314
315**Parameters**
316
317| Name| Type                                                        | Mandatory| Description                                                        |
318| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
319| value  | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Yes  | Font weight. For the number type, the value range is [100, 900], at an interval of 100. The default value is **400**. A larger value indicates a heavier font weight. For the string type, only strings that represent a number, for example, **"400"**, and the following enumerated values of **FontWeight** are supported: **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**.<br>Default value: **FontWeight.Normal** on non-wearable devices and **FontWeight.Regular** on wearable devices|
320
321### fontFamily
322
323fontFamily(value: string | Resource)
324
325Sets the font family.
326
327**Widget capability**: This API can be used in ArkTS widgets since API version 9.
328
329**Atomic service API**: This API can be used in atomic services since API version 11.
330
331**System capability**: SystemCapability.ArkUI.ArkUI.Full
332
333**Parameters**
334
335| Name| Type                                                | Mandatory| Description                                                        |
336| ------ | ---------------------------------------------------- | ---- | ------------------------------------------------------------ |
337| value  | string \| [Resource](ts-types.md#resource) | Yes  | Font family. Default font: **'HarmonyOS Sans'**<br>The 'HarmonyOS Sans' font and [registered custom fonts](../js-apis-font.md) are supported for applications.<br>Only the 'HarmonyOS Sans' font is supported for widgets.|
338
339### copyOption<sup>9+</sup>
340
341copyOption(value: CopyOptions)
342
343Sets whether copy and paste is allowed. If this attribute is set to **CopyOptions.InApp** or **CopyOptions.LocalDevice**, a long press on the text will display a context menu that offers the copy and select-all options.
344
345Because widgets do not have the long press event, the context menu will not be displayed when users long press text.
346
347**Widget capability**: This API can be used in ArkTS widgets since API version 9.
348
349**Atomic service API**: This API can be used in atomic services since API version 11.
350
351**System capability**: SystemCapability.ArkUI.ArkUI.Full
352
353**Parameters**
354
355| Name| Type                                            | Mandatory| Description                                                      |
356| ------ | ------------------------------------------------ | ---- | ---------------------------------------------------------- |
357| value  | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Yes  | Whether copy and paste is allowed.<br>Default value: **CopyOptions.None**|
358
359### draggable<sup>9+</sup>
360
361draggable(value: boolean)
362
363Sets the drag effect of the selected text.
364
365This attribute cannot be used together with the [onDragStart](ts-universal-events-drag-drop.md) event.
366
367It must be used together with [CopyOptions](ts-appendix-enums.md#copyoptions9). When it is set to **true** and **copyOptions** is set to **CopyOptions.InApp** or **CopyOptions.LocalDevice**, the selected text can be dragged and copied to the text box.
368
369**Atomic service API**: This API can be used in atomic services since API version 11.
370
371**System capability**: SystemCapability.ArkUI.ArkUI.Full
372
373**Parameters**
374
375| Name| Type   | Mandatory| Description                                |
376| ------ | ------- | ---- | ------------------------------------ |
377| value  | boolean | Yes  | Drag effect of the selected text.<br>Default value: **false**|
378
379### font<sup>10+</sup>
380
381font(value: Font)
382
383Sets the text style, covering the font size, font width, font family, and font style.
384
385**Atomic service API**: This API can be used in atomic services since API version 11.
386
387**System capability**: SystemCapability.ArkUI.ArkUI.Full
388
389**Parameters**
390
391| Name| Type   | Mandatory| Description      |
392| ------ | ------- | ---- | ---------- |
393| value  | [Font](ts-types.md#font) | Yes  | Text style.|
394
395### textShadow<sup>10+</sup>
396
397textShadow(value: ShadowOptions | Array&lt;ShadowOptions&gt;)
398
399Sets the text shadow.
400
401This API does not work with the **fill** attribute or coloring strategy.
402
403Since API version 11, this API supports input parameters in an array to implement multiple text shadows.
404
405**Widget capability**: This API can be used in ArkTS widgets since API version 10.
406
407**Atomic service API**: This API can be used in atomic services since API version 11.
408
409**System capability**: SystemCapability.ArkUI.ArkUI.Full
410
411**Parameters**
412
413| Name| Type                                                        | Mandatory| Description          |
414| ------ | ------------------------------------------------------------ | ---- | -------------- |
415| value  | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions) \|  Array&lt;[ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions)&gt;<sup>11+</sup> | Yes  | Text shadow.|
416
417### heightAdaptivePolicy<sup>10+</sup>
418
419heightAdaptivePolicy(value: TextHeightAdaptivePolicy)
420
421Sets how the font size of text adapts to layout constraints.
422
423When this attribute is set to **TextHeightAdaptivePolicy.MAX_LINES_FIRST**, the [maxLines](#maxlines) attribute takes precedence for adjusting the text height. If the **maxLines** setting results in a layout beyond the layout constraints, the text will shrink to a font size between [minFontSize](#minfontsize) and [maxFontSize](#maxfontsize) to allow for more content to be shown.
424
425If this attribute is set to **TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST**, the **minFontSize** attribute takes precedence for adjusting the text height. If the text fits on one line at **minFontSize**, the system attempts to increase the font size within the range of **minFontSize** and **maxFontSize** to display the text as large as possible on one line. If the text cannot fit into a single line even at **minFontSize**, it sticks with **minFontSize**.
426
427If this attribute is set to **TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST**, the layout constraints take precedence for adjusting the text height. If the resultant layout is beyond the layout constraints, the text will shrink to a font size between **minFontSize** and **maxFontSize** to respect the layout constraints. If the text still extends beyond the layout constraints after shrinking to **minFontSize**, the lines that exceed the constraints are deleted.
428
429**Atomic service API**: This API can be used in atomic services since API version 11.
430
431**System capability**: SystemCapability.ArkUI.ArkUI.Full
432
433**Parameters**
434
435| Name| Type                                                        | Mandatory| Description                                                        |
436| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
437| value  | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | Yes  | How the adaptive height is determined for the text.<br>Default value: **TextHeightAdaptivePolicy.MAX_LINES_FIRST**|
438
439### textIndent<sup>10+</sup>
440
441textIndent(value: Length)
442
443Sets the indent of the first line text.
444
445**Atomic service API**: This API can be used in atomic services since API version 11.
446
447**System capability**: SystemCapability.ArkUI.ArkUI.Full
448
449**Parameters**
450
451| Name| Type                        | Mandatory| Description                        |
452| ------ | ---------------------------- | ---- | ---------------------------- |
453| value  | [Length](ts-types.md#length) | Yes  | Indent of the first line text.<br>Default value: **0**|
454
455### wordBreak<sup>11+</sup>
456
457wordBreak(value: WordBreak)
458
459Sets the word break rule. When used with **{overflow: TextOverflow.Ellipsis}** and **maxLines**, **WordBreak.BREAK_ALL** can insert line breaks between letters when overflow occurs and display excess content with an ellipsis (...).
460
461**Atomic service API**: This API can be used in atomic services since API version 11.
462
463**System capability**: SystemCapability.ArkUI.ArkUI.Full
464
465**Parameters**
466
467| Name| Type                                         | Mandatory| Description                                         |
468| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
469| value  | [WordBreak](ts-appendix-enums.md#wordbreak11) | Yes  | Word break rule.<br>Default value: **WordBreak.BREAK_WORD**|
470
471### selection<sup>11+</sup>
472
473selection(selectionStart: number, selectionEnd: number)
474
475Sets text selection. The selected text is highlighted, and a selection handle is displayed together with a menu of available actions.
476
477When **copyOption** is set to **CopyOptions.None**, the **selection** attribute is not effective.
478
479When **overflow** is set to **TextOverflow.MARQUEE**, the **selection** attribute is not effective.
480
481If the value of **selectionStart** is greater than or equal to that of **selectionEnd**, no text will be selected. The value range is [0, textSize], where **textSize** indicates the maximum number of characters in the text content. If the value is less than 0, the value **0** will be used. If the value is greater than **textSize**, **textSize** will be used.
482
483If the value of **selectionStart** or **selectionEnd** falls within the invisible area, no text will be selected. If clipping is disabled, the text selection outside of the parent component takes effect.
484
485**Atomic service API**: This API can be used in atomic services since API version 11.
486
487**System capability**: SystemCapability.ArkUI.ArkUI.Full
488
489**Parameters**
490
491| Name        | Type  | Mandatory| Description                                |
492| -------------- | ------ | ---- | ------------------------------------ |
493| selectionStart | number | Yes  | Start position of the selected text.<br>Default value: **-1**|
494| selectionEnd   | number | Yes  | End position of the selected text.<br>Default value: **-1**|
495
496### ellipsisMode<sup>11+</sup>
497
498ellipsisMode(value: EllipsisMode)
499
500Sets the ellipsis position. For the settings to work, **overflow** must be set to **TextOverflow.Ellipsis** and **maxLines** must be specified. Setting **ellipsisMode** alone does not take effect.
501
502**EllipsisMode.START** and **EllipsisMode.CENTER** take effect only when text overflows in a single line.
503
504**Atomic service API**: This API can be used in atomic services since API version 12.
505
506**System capability**: SystemCapability.ArkUI.ArkUI.Full
507
508**Parameters**
509
510| Name| Type                                               | Mandatory| Description                                     |
511| ------ | --------------------------------------------------- | ---- | ----------------------------------------- |
512| value  | [EllipsisMode](ts-appendix-enums.md#ellipsismode11) | Yes  | Ellipsis position.<br>Default value: **EllipsisMode.END**|
513
514### enableDataDetector<sup>11+</sup>
515
516enableDataDetector(enable: boolean)
517
518Enables recognition for special entities within the text.
519
520This API only works on devices that provide text recognition.
521
522When **enableDataDetector** is set to **true**, and the **dataDetectorConfig** attribute is not set, all types of entities are recognized by default, and the **color** and **decoration** of the recognized entities will be changed to the following styles:
523
524```ts
525color: '#ff007dff'
526decoration:{
527  type: TextDecorationType.Underline,
528  color: '#ff007dff',
529  style: TextDecorationStyle.SOLID
530}
531```
532
533Touching and right-clicking an entity with the mouse will pop up the corresponding entity operation menu based on the type of entity, while left-clicking an entity with the mouse will directly respond to the first option of the menu.
534
535This API does not work when **overflow** is set to **TextOverflow.MARQUEE**.
536
537When **copyOption** is set to **CopyOptions.None**, the menu displayed after an entity is clicked does not provide the text selection, copy, translation, or sharing functionality. When **copyOption** is not set to **CopyOptions.None**, and **textSelectable** is set to **TextSelectableMode.UNSELECTABLE**, the entity still has the copy functionality but does not have the text selection feature.
538
539**Atomic service API**: This API can be used in atomic services since API version 12.
540
541**System capability**: SystemCapability.ArkUI.ArkUI.Full
542
543**Parameters**
544
545| Name| Type   | Mandatory| Description                             |
546| ------ | ------- | ---- | --------------------------------- |
547| enable  | boolean | Yes  | Whether to enable text recognition.<br>Default value: **false**|
548
549### dataDetectorConfig<sup>11+</sup>
550
551dataDetectorConfig(config: TextDataDetectorConfig)
552
553Configures text recognition settings.
554
555This API must be used together with [enableDataDetector](#enabledatadetector11). It takes effect only when **enableDataDetector** is set to **true**.
556
557When entities A and B overlap, the following rules are followed:
558
5591. If A is a subset of B (A ⊂ B), then B is retained; otherwise, A is retained.
560
5612. If A is not a subset of B (A ⊄ B) and B is not a subset of A (B ⊄ A), and if the starting point of A is earlier than that of B (A.start < B.start), then A is retained; otherwise, B is retained.
562
563**Atomic service API**: This API can be used in atomic services since API version 12.
564
565**System capability**: SystemCapability.ArkUI.ArkUI.Full
566
567**Parameters**
568
569| Name| Type                                                       | Mandatory| Description                                                        |
570| ------ | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
571| config | [TextDataDetectorConfig](ts-text-common.md#textdatadetectorconfig11) | Yes  | Text recognition configuration.|
572
573### bindSelectionMenu<sup>11+</sup>
574
575bindSelectionMenu(spanType: TextSpanType, content: CustomBuilder, responseType: TextResponseType,
576    options?: SelectionMenuOptions)
577
578Sets the custom context menu on text selection.
579
580The duration required for a long-press gesture is 600 ms for **bindSelectionMenu** and 800 ms for **bindContextMenu**. When both **bindSelectionMenu** and **bindContextMenu** are set and both are configured to be triggered by a long-press gesture, **bindSelectionMenu** is triggered first.
581
582If the custom menu is too long, embed a [Scroll](./ts-container-scroll.md) component to prevent the keyboard from being blocked.
583
584**Atomic service API**: This API can be used in atomic services since API version 12.
585
586**System capability**: SystemCapability.ArkUI.ArkUI.Full
587
588**Parameters**
589
590| Name      | Type                                                        | Mandatory| Description                                                        |
591| ------------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
592| spanType     | [TextSpanType](#textspantype11)          | Yes  | Span type of the menu.<br>Default value: **TextSpanType.TEXT**              |
593| content      | [CustomBuilder](ts-types.md#custombuilder8)                  | Yes  | Content of the menu.                                            |
594| responseType | [TextResponseType](#textresponsetype11)  | Yes  | Response type of the menu.<br>Default value: **TextResponseType.LONG_PRESS**|
595| options      | [SelectionMenuOptions](ts-basic-components-richeditor.md#selectionmenuoptions10) | No  | Options of the menu.                                            |
596
597### fontFeature<sup>12+</sup>
598
599fontFeature(value: string)
600
601Sets the font feature, for example, monospaced digits.
602
603Format: normal \| \<feature-tag-value\>
604
605Format of **\<feature-tag-value\>**: \<string\> \[ \<integer\> \| on \| off ]
606
607There can be multiple **\<feature-tag-value\>** values, which are separated by commas (,).
608
609For example, the input format for monospaced clock fonts is "ss01" on.
610
611**Widget capability**: This API can be used in ArkTS widgets since API version 12.
612
613**Atomic service API**: This API can be used in atomic services since API version 12.
614
615**System capability**: SystemCapability.ArkUI.ArkUI.Full
616
617**Parameters**
618
619| Name| Type  | Mandatory| Description          |
620| ------ | ------ | ---- | -------------- |
621| value  | string | Yes  | Font feature.|
622
623Font feature list<br>
624![alt text](figures/arkts-fontfeature.png)
625
626Font features are advanced typographic features, such as ligatures and monospace, for OpenType fonts. They are typically used in custom fonts and require the support of the font itself.
627For more information about the font features, see [Low-level font feature settings control: the font-feature-settings property](https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop) and [The Complete CSS Demo for OpenType Features](https://sparanoid.com/lab/opentype-features/).
628
629>  **NOTE**
630>
631>  The **Text** component cannot contain both text and the child component **Span** or **ImageSpan**. If both of them exist, only the content in **Span** or **ImageSpan** is displayed.
632>
633>  The typesetting engine rounds down the value of [width](ts-universal-attributes-size.md#width) to ensure that the value is an integer. If the typesetting engine rounds up the value instead, the right side of the text may be clipped.
634>
635>  When multiple **Text** components are placed in the [Row](ts-container-row.md) container with no specific layout or space allocation settings configured, the components are laid out based on the maximum size of the container. To make sure the sum of the components' main axis sizes does not exceed the main axis size of the container, you can set [layoutWeight](ts-universal-attributes-size.md#layoutweight) or use the [flex layout](ts-universal-attributes-flex-layout.md).
636
637### lineSpacing<sup>12+</sup>
638
639lineSpacing(value: LengthMetrics)
640
641Sets the line spacing of the text. If the value specified is less than or equal to 0, the default value **0** is used.
642
643**Atomic service API**: This API can be used in atomic services since API version 12.
644
645**System capability**: SystemCapability.ArkUI.ArkUI.Full
646
647**Parameters**
648
649| Name| Type                                                        | Mandatory| Description            |
650| ------ | ------------------------------------------------------------ | ---- | ---------------- |
651| value  | [LengthMetrics](../js-apis-arkui-graphics.md#lengthmetrics12) | Yes  | Line spacing. Default value: **0**|
652
653### privacySensitive<sup>12+</sup>
654
655privacySensitive(supported: boolean)
656
657Sets whether to enable privacy mode on widgets.
658
659**Widget capability**: This API can be used in ArkTS widgets since API version 12.
660
661**Atomic service API**: This API can be used in atomic services since API version 12.
662
663**System capability**: SystemCapability.ArkUI.ArkUI.Full
664
665**Parameters**
666
667| Name   | Type   | Mandatory| Description                                                        |
668| --------- | ------- | ---- | ------------------------------------------------------------ |
669| supported | boolean | Yes  | Whether to enable privacy mode on widgets.<br>The value **true** means to enable privacy mode, in which case text is obscured as hyphens (-).<br>Default value: **false**<br>**NOTE**<br>If this parameter is set to **null**, privacy mode is disabled.<br>Enabling privacy mode requires [widget framework support](./ts-universal-attributes-obscured.md).|
670
671### lineBreakStrategy<sup>12+</sup>
672
673lineBreakStrategy(strategy: LineBreakStrategy)
674
675Sets the line break rule. This attribute takes effect when **wordBreak** is not set to **breakAll**. Hyphens are not supported.
676
677**Atomic service API**: This API can be used in atomic services since API version 12.
678
679**System capability**: SystemCapability.ArkUI.ArkUI.Full
680
681**Parameters**
682
683| Name  | Type                                                        | Mandatory| Description                                                   |
684| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------- |
685| strategy | [LineBreakStrategy](ts-appendix-enums.md#linebreakstrategy12) | Yes  | Line break rule.<br>Default value: **LineBreakStrategy.GREEDY**|
686
687### textSelectable<sup>12+</sup>
688
689textSelectable(mode: TextSelectableMode)
690
691Sets whether the text is selectable and focusable.
692
693**Atomic service API**: This API can be used in atomic services since API version 12.
694
695**System capability**: SystemCapability.ArkUI.ArkUI.Full
696
697**Parameters**
698
699| Name| Type                                         | Mandatory| Description                                         |
700| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
701| mode  | [TextSelectableMode](ts-appendix-enums.md#textselectablemode12) | Yes  | Whether the text is selectable and focusable.<br>Default value: **TextSelectableMode.SELECTABLE_UNFOCUSABLE**|
702
703### editMenuOptions<sup>12+</sup>
704
705editMenuOptions(editMenu: EditMenuOptions)
706
707Sets the extended options of the custom context menu on selection, including the text content, icon, and callback.
708
709**Atomic service API**: This API can be used in atomic services since API version 12.
710
711**System capability**: SystemCapability.ArkUI.ArkUI.Full
712
713**Parameters**
714
715| Name| Type                                         | Mandatory| Description                                         |
716| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
717| editMenu  | [EditMenuOptions](ts-text-common.md#editmenuoptions) | Yes  | Extended options of the custom context menu on selection.|
718
719### minFontScale<sup>12+</sup>
720
721minFontScale(scale: number | Resource)
722
723Sets the minimum font scale factor for text.
724
725**Atomic service API**: This API can be used in atomic services since API version 12.
726
727**System capability**: SystemCapability.ArkUI.ArkUI.Full
728
729**Parameters**
730
731| Name| Type                                         | Mandatory| Description                                         |
732| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
733| scale  | number \| [Resource](ts-types.md#resource) | Yes  | Minimum font scale factor for text.<br>Value range: [0, 1]<br>**NOTE**<br>A value less than 0 is handled as **0**. A value greater than 1 is handled as **1**. Abnormal values are ineffective by default.|
734
735### maxFontScale<sup>12+</sup>
736
737maxFontScale(scale: number | Resource)
738
739Sets the maximum font scale factor for text.
740
741**Atomic service API**: This API can be used in atomic services since API version 12.
742
743**System capability**: SystemCapability.ArkUI.ArkUI.Full
744
745**Parameters**
746
747| Name| Type                                         | Mandatory| Description                                         |
748| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
749| scale  | number \| [Resource](ts-types.md#resource) | Yes  | Maximum font scale factor for text.<br>Value range: [1, +∞)<br>**NOTE**<br>A value less than 1 is handled as **1**. Abnormal values are ineffective by default.|
750
751### halfLeading<sup>12+</sup>
752
753halfLeading(halfLeading: boolean)
754
755Sets whether half leading is enabled.
756
757The **halfLeading** settings configured within the component take precedence over those in **module.json5**.
758
759**Atomic service API**: This API can be used in atomic services since API version 12.
760
761**System capability**: SystemCapability.ArkUI.ArkUI.Full
762
763**Parameters**
764
765| Name| Type                                         | Mandatory| Description                                         |
766| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
767| halfLeading | boolean | Yes | Whether half leading is enabled.<br>Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite.<br>Default value: **false**|
768
769### font<sup>12+</sup>
770
771font(fontValue: Font, options?: FontSettingOptions)
772
773Sets the font style, with support for font settings.
774
775It is only effective for the **Text** component, not for its child components.
776
777**Widget capability**: This API can be used in ArkTS widgets since API version 12.
778
779**Atomic service API**: This API can be used in atomic services since API version 12.
780
781**System capability**: SystemCapability.ArkUI.ArkUI.Full
782
783**Parameters**
784
785| Name| Type                                         | Mandatory| Description                                         |
786| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
787| fontValue | [Font](ts-types.md#font) | Yes | Text style.|
788| options | [FontSettingOptions](ts-text-common.md#fontsettingoptions12) | No | Font settings.|
789
790### fontWeight<sup>12+</sup>
791
792fontWeight(weight: number | FontWeight | string, options?: FontSettingOptions)
793
794Sets the text font weight, with support for font settings.
795
796It is only effective for the **Text** component, not for its child components.
797
798**Widget capability**: This API can be used in ArkTS widgets since API version 12.
799
800**Atomic service API**: This API can be used in atomic services since API version 12.
801
802**System capability**: SystemCapability.ArkUI.ArkUI.Full
803
804**Parameters**
805
806| Name| Type                                         | Mandatory| Description                                         |
807| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
808| weight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Yes | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. A larger value indicates a heavier font weight. The default value is **400**. For the string type, only strings that represent a number, for example, **"400"**, and the following enumerated values of **FontWeight** are supported: **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**.|
809| options | [FontSettingOptions](ts-text-common.md#fontsettingoptions12) | No | Font settings.|
810
811### enableHapticFeedback<sup>13+</sup>
812
813enableHapticFeedback(isEnabled: boolean)
814
815Specifies whether to enable haptic feedback.
816
817**Atomic service API**: This API can be used in atomic services since API version 13.
818
819**System capability**: SystemCapability.ArkUI.ArkUI.Full
820
821**Parameters**
822
823| Name| Type   | Mandatory| Description                              |
824| ------ | ------- | ---- | ---------------------------------- |
825| isEnabled | boolean | Yes  | Whether to enable haptic feedback.<br>Default value: **true**|
826
827>  **NOTE**
828>
829>  To enable haptic feedback, you must declare the ohos.permission.VIBRATE permission under **requestPermissions** in the **module.json5** file of the project.
830> ```json
831> "requestPermissions": [
832>  {
833>     "name": "ohos.permission.VIBRATE",
834>  }
835> ]
836> ```
837
838### caretColor<sup>14+</sup>
839
840caretColor(color: ResourceColor)
841
842Sets the color of the text selection handle, also known as the caret, in the text box.
843
844**Atomic service API**: This API can be used in atomic services since API version 14.
845
846**System capability**: SystemCapability.ArkUI.ArkUI.Full
847
848**Parameters**
849
850| Name| Type                                      | Mandatory| Description                                  |
851| ------ | ------------------------------------------ | ---- | -------------------------------------- |
852| color  | [ResourceColor](ts-types.md#resourcecolor) | Yes  | Color of the text selection handle.<br>Default value: **'#007DFF'**|
853
854### selectedBackgroundColor<sup>14+</sup>
855
856selectedBackgroundColor(color: ResourceColor)
857
858Sets the background color of the selected text. If the opacity is not set, a 20% opacity will be used.
859
860**Atomic service API**: This API can be used in atomic services since API version 14.
861
862**System capability**: SystemCapability.ArkUI.ArkUI.Full
863
864**Parameters**
865
866| Name| Type                                      | Mandatory| Description                                      |
867| ------ | ------------------------------------------ | ---- | ------------------------------------------ |
868| color  | [ResourceColor](ts-types.md#resourcecolor) | Yes  | Background color of the selected text.<br>By default, a 20% opacity is applied.<br>Default value: **'#007DFF'**|
869
870### marqueeOptions<sup>18+</sup>
871
872marqueeOptions(options: Optional\<TextMarqueeOptions>)
873
874Sets the marquee effect for text.
875
876The **marqueeOptions** settings take effect only when **textOverflow** is set to **TextOverflow.MARQUEE**.
877
878**Atomic service API**: This API can be used in atomic services since API version 18.
879
880**System capability**: SystemCapability.ArkUI.ArkUI.Full
881
882**Parameters**
883
884| Name| Type                                      | Mandatory| Description                                      |
885| ------ | ------------------------------------------ | ---- | ------------------------------------------ |
886| options | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[TextMarqueeOptions](#textmarqueeoptions18)> | Yes| Marquee settings, including the switch, step length, number of loops, and direction.|
887
888## TextSpanType<sup>11+</sup>
889
890Provides the [span](ts-basic-components-span.md) type information.
891
892**System capability**: SystemCapability.ArkUI.ArkUI.Full
893
894| Name| Value| Description|
895| -------- | ---- | -------- |
896| TEXT | 0 | Text span.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
897| IMAGE | 1 | Image span.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
898| MIXED | 2 | Mixed span, which contains both text and imagery.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
899| DEFAULT<sup>15+</sup> | 3 | When this type is registered but **TEXT**, **IMAGE**, or **MIXED** types are not registered, this type will be triggered and displayed for those registered types.<br>**Atomic service API**: This API can be used in atomic services since API version 15.|
900
901>  **NOTE**
902>
903>  The order for menu type matching is as follows. When the user interacts with text, the system follows this order to decides which type of menu to display.
904>  1. Check whether a menu is registered for **TextSpanType.TEXT** and **TextResponseType.LONG_PRESS**.
905>  2. Check whether a menu is registered for **TextSpanType.TEXT** and **TextResponseType.DEFAULT**.
906>  3. Check whether a menu is registered for **TextSpanType.DEFAULT** and **TextResponseType.LONG_PRESS**.
907>  4. Check whether a menu is registered for **TextSpanType.DEFAULT** and **TextResponseType.DEFAULT**.
908
909## TextResponseType<sup>11+</sup>
910
911**System capability**: SystemCapability.ArkUI.ArkUI.Full
912
913| Name        | Value|  Description         |
914| ---------- | --- | ------------- |
915| RIGHT_CLICK | 0 | The menu is displayed when the component is right-clicked.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
916| LONG_PRESS  | 1 | The menu is displayed when the component is long-pressed.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
917| SELECT | 2 | The menu is displayed when the component is selected.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
918| DEFAULT<sup>15+</sup> | 3 | When this type is registered but **RIGHT_CLICK**, **LONG_PRESS**, or **SELECT** types are not registered, this type will be triggered and displayed for right-click, long press, and mouse selection actions.<br>**Atomic service API**: This API can be used in atomic services since API version 15.|
919
920>  **NOTE**
921>
922>  The order for menu type matching is as follows. When the user interacts with text, the system follows this order to decides which type of menu to display.
923>  1. Check whether a menu is registered for **TextSpanType.TEXT** and **TextResponseType.LONG_PRESS**.
924>  2. Check whether a menu is registered for **TextSpanType.TEXT** and **TextResponseType.DEFAULT**.
925>  3. Check whether a menu is registered for **TextSpanType.DEFAULT** and **TextResponseType.LONG_PRESS**.
926>  4. Check whether a menu is registered for **TextSpanType.DEFAULT** and **TextResponseType.DEFAULT**.
927
928## TextOverflowOptions<sup>18+</sup>
929
930Describes the display mode when the text is too long.
931
932**Widget capability**: This API can be used in ArkTS widgets since API version 18.
933
934**Atomic service API**: This API can be used in atomic services since API version 18.
935
936**System capability**: SystemCapability.ArkUI.ArkUI.Full
937
938**Parameters**
939
940| Name| Type                                                        | Mandatory| Description                                                        |
941| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
942| overflow<sup>7+</sup>  | [TextOverflow](ts-appendix-enums.md#textoverflow) | Yes  | Display mode when the text is too long.<br>Default value: **TextOverflow.Clip**<br>**Widget capability**: This API can be used in ArkTS widgets since API version 9.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
943
944## Events
945
946In addition to the [universal events](ts-component-general-events.md), the following events are supported.
947
948### onCopy<sup>11+</sup>
949
950onCopy(callback:(value: string) =&gt; void)
951
952Called when data is copied to the pasteboard, which is displayed when the text box is long pressed. Currently, only text can be copied.
953
954**Atomic service API**: This API can be used in atomic services since API version 11.
955
956**System capability**: SystemCapability.ArkUI.ArkUI.Full
957
958**Parameters**
959
960| Name| Type  | Mandatory| Description            |
961| ------ | ------ | ---- | ---------------- |
962| value  | string | Yes  | Text that is copied.|
963
964### onTextSelectionChange<sup>11+</sup>
965
966onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)
967
968Called when the text selection position changes.
969
970**Atomic service API**: This API can be used in atomic services since API version 12.
971
972**System capability**: SystemCapability.ArkUI.ArkUI.Full
973
974**Parameters**
975
976| Name        | Type  | Mandatory| Description                |
977| -------------- | ------ | ---- | -------------------- |
978| selectionStart | number | Yes  | Start position of the selected text.|
979| selectionEnd   | number | Yes  | End position of the selected text.|
980
981### onMarqueeStateChange<sup>18+</sup>
982
983onMarqueeStateChange(callback: Callback\<MarqueeState\>)
984
985Called when the marquee animation reaches the specified state.
986
987**Atomic service API**: This API can be used in atomic services since API version 18.
988
989**System capability**: SystemCapability.ArkUI.ArkUI.Full
990
991**Parameters**
992
993| Name   | Type                                            | Mandatory | Description                      |
994|--------|---------------------------------------------------|-----|--------------------------|
995| callback  | Callback\<[MarqueeState](#marqueestate18)\> | Yes  | Callback that receives a **MarqueeState** enum value, which indicates the current state of the marquee animation.|
996
997## TextOptions<sup>11+</sup>
998
999Describes the initialization options of the **Text** component.
1000
1001**Atomic service API**: This API can be used in atomic services since API version 12.
1002
1003**System capability**: SystemCapability.ArkUI.ArkUI.Full
1004
1005| Name| Type| Mandatory| Description|
1006| -------- | -------- | -------- | -------- |
1007| controller | [TextController](#textcontroller11)  | Yes| Text controller.|
1008
1009## TextController<sup>11+</sup>
1010
1011Defines the controller of the **Text** component.
1012
1013**Atomic service API**: This API can be used in atomic services since API version 12.
1014
1015**System capability**: SystemCapability.ArkUI.ArkUI.Full
1016
1017### Objects to Import
1018
1019```
1020controller: TextController = new TextController()
1021```
1022
1023### closeSelectionMenu
1024
1025closeSelectionMenu(): void
1026
1027Closes the custom or default context menu on selection.
1028
1029**Atomic service API**: This API can be used in atomic services since API version 12.
1030
1031**System capability**: SystemCapability.ArkUI.ArkUI.Full
1032
1033### setStyledString<sup>12+</sup>
1034
1035setStyledString(value: StyledString): void
1036
1037Binds to or updates the specified styled string.
1038
1039**Atomic service API**: This API can be used in atomic services since API version 12.
1040
1041**System capability**: SystemCapability.ArkUI.ArkUI.Full
1042
1043**Parameters**
1044
1045| Name  | Type  | Mandatory  | Description               |
1046| ----- | ------ | ---- | ------------------- |
1047| value | [StyledString](ts-universal-styled-string.md#styledstring) | Yes   | Styled string.<br>**NOTE**<br>The child class [MutableStyledString](ts-universal-styled-string.md#mutablestyledstring) of **StyledString** can also serve as the argument.|
1048
1049### getLayoutManager<sup>12+</sup>
1050
1051getLayoutManager(): LayoutManager
1052
1053Obtains the **LayoutManager** object.
1054
1055**Atomic service API**: This API can be used in atomic services since API version 12.
1056
1057**System capability**: SystemCapability.ArkUI.ArkUI.Full
1058
1059**Return value**
1060
1061| Type                                      | Description     |
1062| ---------------------------------------- | ------- |
1063| [LayoutManager](ts-text-common.md#layoutmanager12) | **LayoutManager** object.|
1064
1065## TextMarqueeOptions<sup>18+</sup>
1066
1067Describes the initialization options of the **Marquee** component.
1068
1069**Atomic service API**: This API can be used in atomic services since API version 18.
1070
1071**System capability**: SystemCapability.ArkUI.ArkUI.Full
1072
1073**Parameters**
1074
1075| Name               | Type                                             | Mandatory| Description                                                                                 |
1076|--------------------|-------------------------------------------------|----|-------------------------------------------------------------------------------------|
1077| start              | boolean                                         | Yes | Whether to start the marquee.                                                                       |
1078| step               | number                                          | No | Step length of the scrolling animation text.<br>Default value: **4.0** (in vp)                                                          |
1079| loop               | number                                          | No | Number of times the marquee will scroll. If the value is less than or equal to **0**, the marquee will scroll continuously.<br>Default value: **-1**                                                   |
1080| fromStart          | boolean                                         | No | Whether the text scrolls from the start.<br>Default value: **true**                                                      |
1081| delay              | number                                          | No | Time interval between scroll movements.<br>Default value: **0**                                                             |
1082| fadeout            | boolean                                         | No | Whether to apply a fade-out effect when the text is too long. With this parameter set to **true**: When the text content exceeds the display range, the edges of the partially visible text will have a fade-out effect applied; If both ends have partially visible text, both ends will have the fade-out effect applied; The **clip** attribute is automatically locked to **true** and cannot be set to **false**.<br>Default value: **false** |
1083| marqueeStartPolicy | [MarqueeStartPolicy](#marqueestartpolicy18) | No | Start policy of the marquee.<br>Default value: **MarqueeStartPolicy.DEFAULT**                                      |
1084
1085## MarqueeStartPolicy<sup>18+</sup>
1086
1087Enumerates the marquee scrolling modes.
1088
1089**Atomic service API**: This API can be used in atomic services since API version 18.
1090
1091**System capability**: SystemCapability.ArkUI.ArkUI.Full
1092
1093| Name       | Value| Description           |
1094|----------|----|---------------|
1095| DEFAULT  | 0  | The marquee scrolls continuously. Default value.      |
1096| ON_FOCUS | 1  | The marquee starts scrolling when it has focus or when the mouse hovers over it.|
1097
1098## MarqueeState<sup>18+</sup>
1099
1100Enumerates the return values of the marquee state callback.
1101
1102**Atomic service API**: This API can be used in atomic services since API version 18.
1103
1104**System capability**: SystemCapability.ArkUI.ArkUI.Full
1105
1106| Name    | Value| Description                           |
1107|--------|----|-------------------------------|
1108| START  | 0  | The marquee starts scrolling.                    |
1109| BOUNCE | 1  | The marquee completes one scroll movement. If the number of **loops** is not 1, this value will be returned multiple times.|
1110| FINISH | 2  | All loops of the marquee are completed.             |
1111
1112## Example
1113
1114### Example 1: Setting the Text Layout
1115This example demonstrates the effects of text layout attributes such as **textAlign**, **lineHeight**, **baselineOffset**, and **halfLeading**.
1116```ts
1117// xxx.ets
1118@Extend(Text)
1119function style(TextAlign: TextAlign) {
1120  .textAlign(TextAlign)
1121  .fontSize(12)
1122  .border({ width: 1 })
1123  .padding(10)
1124  .width('100%')
1125  .margin(5)
1126}
1127
1128@Entry
1129@Component
1130struct TextExample1 {
1131  @State changeTextAlignIndex: number = 0;
1132  @State changeDecorationIndex: number = 0;
1133  @State TextAlign: TextAlign[] = [TextAlign.Start, TextAlign.Center, TextAlign.End];
1134  @State TextAlignStr: string[] = ['Start', 'Center', 'End'];
1135  @State TextDecorationType: TextDecorationType[] =
1136    [TextDecorationType.LineThrough, TextDecorationType.Overline, TextDecorationType.Underline];
1137  @State TextDecorationTypeStr: string[] = ['LineThrough', 'Overline', 'Underline'];
1138  @State TextDecorationStyle: TextDecorationStyle[] =
1139    [TextDecorationStyle.SOLID, TextDecorationStyle.DOTTED, TextDecorationStyle.WAVY];
1140  @State TextDecorationStyleStr: string[] = ['SOLID', 'DOTTED', 'WAVY'];
1141
1142  build() {
1143    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1144      // Set horizontal alignment for text.
1145      // Single-line text
1146      Text('textAlign').fontSize(9).fontColor(0xCCCCCC)
1147      Text(`TextAlign set to ${this.TextAlignStr[this.changeTextAlignIndex]}.`)
1148        .style(this.TextAlign[this.changeTextAlignIndex])
1149
1150      // Multi-line text
1151      Text(`This is the text content with textAlign set to ${this.TextAlignStr[this.changeTextAlignIndex]}.`)
1152        .style(this.TextAlign[this.changeTextAlignIndex])
1153        .margin(5)
1154
1155      Row() {
1156        Button('TextAlign Value: ' + this.TextAlignStr[this.changeTextAlignIndex]).onClick(() => {
1157          this.changeTextAlignIndex++;
1158          if (this.changeTextAlignIndex > (this.TextAlignStr.length - 1)) {
1159            this.changeTextAlignIndex = 0;
1160          }
1161        })
1162      }.justifyContent(FlexAlign.Center).width('100%')
1163
1164      // Set the text line height.
1165      Text('lineHeight').fontSize(9).fontColor(0xCCCCCC)
1166      Text('This is the text with the line height set. This is the text with the line height set.')
1167        .style(TextAlign.Start)
1168      Text('This is the text with the line height set. This is the text with the line height set.')
1169        .style(TextAlign.Start)
1170        .lineHeight(20)
1171
1172      // Set the text baseline offset.
1173      Text('baselineOffset').fontSize(9).fontColor(0xCCCCCC)
1174      Text('This is the text content with baselineOffset 0.')
1175        .baselineOffset(0)
1176        .style(TextAlign.Start)
1177      Text('This is the text content with baselineOffset 30.')
1178        .baselineOffset(30)
1179        .style(TextAlign.Start)
1180      Text('This is the text content with baselineOffset -20.')
1181        .baselineOffset(-20)
1182        .style(TextAlign.Start)
1183
1184      // Set whether half leading is enabled.
1185      Text('halfLeading').fontSize(9).fontColor(0xCCCCCC)
1186      Text("This is the text with the halfLeading set.")
1187        .lineHeight(60)
1188        .halfLeading(true)
1189        .style(TextAlign.Start)
1190      Text("This is the text without the halfLeading set.")
1191        .lineHeight(60)
1192        .halfLeading(false)
1193        .style(TextAlign.Start)
1194    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
1195  }
1196}
1197```
1198![textExp1](figures/textExp1.gif)
1199
1200### Example 2: Setting the Text Style
1201
1202This example shows how to set various text styles using **decoration**, **letterSpacing**, and **textCase**, **fontFamily**, **textShadow**, **fontStyle**, **textIndent**, and **fontWeight** attributes.
1203
1204```ts
1205@Extend(Text)
1206function style() {
1207  .font({ size: 12 })
1208  .border({ width: 1 })
1209  .padding(10)
1210  .width('100%')
1211  .margin(5)
1212}
1213
1214@Entry
1215@Component
1216struct TextExample2 {
1217  @State changeDecorationIndex: number = 0;
1218  @State TextDecorationType: TextDecorationType[] =
1219    [TextDecorationType.LineThrough, TextDecorationType.Overline, TextDecorationType.Underline];
1220  @State TextDecorationTypeStr: string[] = ['LineThrough', 'Overline', 'Underline'];
1221  @State TextDecorationStyle: TextDecorationStyle[] =
1222    [TextDecorationStyle.SOLID, TextDecorationStyle.DOTTED, TextDecorationStyle.WAVY];
1223  @State TextDecorationStyleStr: string[] = ['SOLID', 'DOTTED', 'WAVY'];
1224
1225  build() {
1226    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1227      Text('decoration').fontSize(9).fontColor(0xCCCCCC)
1228      Text('This is the text content with the decoration set to LineThrough and the color set to Red.')
1229        .decoration({
1230          type: this.TextDecorationType[this.changeDecorationIndex],
1231          color: Color.Red,
1232          style: this.TextDecorationStyle[this.changeDecorationIndex]
1233        })
1234        .style()
1235        .margin(5)
1236
1237      Row() {
1238        Button('Decoration Type: ' + this.TextDecorationTypeStr[this.changeDecorationIndex] + ' & ' +
1239        this.TextDecorationStyleStr[this.changeDecorationIndex]).onClick(() => {
1240          this.changeDecorationIndex++;
1241          if (this.changeDecorationIndex > (this.TextDecorationTypeStr.length - 1)) {
1242            this.changeDecorationIndex = 0;
1243          }
1244        })
1245      }.justifyContent(FlexAlign.Center).width('100%')
1246
1247      // Set the letter spacing.
1248      Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC)
1249      Text('This is the text content with letterSpacing 0.')
1250        .letterSpacing(0)
1251        .style()
1252      Text('This is the text content with letterSpacing 3.')
1253        .letterSpacing(3)
1254        .style()
1255      Text('This is the text content with letterSpacing -1.')
1256        .letterSpacing(-1)
1257        .style()
1258
1259      Text('textCase').fontSize(9).fontColor(0xCCCCCC)
1260      Text('This is the text content with textCase set to Normal.')
1261        .textCase(TextCase.Normal)
1262        .style()
1263      // Display the text in lowercase.
1264      Text('This is the text content with textCase set to LowerCase.')
1265        .textCase(TextCase.LowerCase)
1266        .style()
1267      // Display the text in uppercase.
1268      Text('This is the text content with textCase set to UpperCase.')
1269        .textCase(TextCase.UpperCase)
1270        .style()
1271
1272      Text('fontFamily').fontSize(9).fontColor(0xCCCCCC)
1273      // Set the font family.
1274      Text('This is the text content with fontFamily')
1275        .style()
1276        .fontFamily('HarmonyOS Sans')
1277
1278      Text('textShadow').fontSize(9).fontColor(0xCCCCCC)
1279      // Set the text shadow.
1280      Text('textShadow')
1281        .style()
1282        .textAlign(TextAlign.Center)
1283        .fontSize(40)
1284        .textShadow({
1285          radius: 10,
1286          color: Color.Black,
1287          offsetX: 0,
1288          offsetY: 0
1289        })
1290
1291      Text('fontStyle').fontSize(9).fontColor(0xCCCCCC)
1292      // Set the font style.
1293      Text('This is the text content with fontStyle set to Italic')
1294        .style()
1295        .fontStyle(FontStyle.Italic)
1296      Text('This is the text content with fontStyle set to Normal')
1297        .style()
1298        .fontStyle(FontStyle.Normal)
1299
1300      Text('textIndent').fontSize(9).fontColor(0xCCCCCC)
1301      // Set the text indentation.
1302      Text('This is the text content with textIndent 30')
1303        .style()
1304        .textIndent(30)
1305
1306      Text('fontWeight').fontSize(9).fontColor(0xCCCCCC)
1307      // Set the font weight.
1308      Text('This is the text content with fontWeight 800')
1309        .style()
1310        .fontWeight('800', { enableVariableFontWeight: true })
1311
1312    }.width('100%').padding({ left: 35, right: 35 })
1313  }
1314}
1315```
1316![textExp1](figures/textExp2.gif)
1317
1318### Example 3: Setting Text Overflow
1319
1320This example demonstrates how to use **maxLines**, **textOverflow**, and **ellipsisMode** to display excess content with an ellipsis (...) when the text is too long.
1321
1322```ts
1323@Extend(Text)
1324function style() {
1325  .textAlign(TextAlign.Center)
1326  .fontSize(12)
1327  .border({ width: 1 })
1328  .padding(10)
1329  .width('100%')
1330  .margin(5)
1331}
1332
1333@Entry
1334@Component
1335struct TextExample3 {
1336  @State text: string =
1337    'The text component is used to display a piece of textual information.Support universal attributes and universal text attributes.';
1338  @State ellipsisModeIndex: number = 0;
1339  @State ellipsisMode: EllipsisMode[] = [EllipsisMode.START, EllipsisMode.CENTER, EllipsisMode.END];
1340  @State ellipsisModeStr: string[] = ['START', 'CENTER', 'END'];
1341
1342  build() {
1343    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1344      // Set the display mode when the text is too long.
1345      Text('TextOverflow+maxLines').fontSize(9).fontColor(0xCCCCCC)
1346      // Clip the text when the value of maxLines is exceeded.
1347      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.')
1348        .textOverflow({ overflow: TextOverflow.Clip })
1349        .maxLines(1)
1350        .style()
1351
1352      // Show an ellipsis (...) when the value of maxLines is exceeded.
1353      Text('This is set textOverflow to Ellipsis text content This is set textOverflow to Ellipsis text content.')
1354        .textOverflow({ overflow: TextOverflow.Ellipsis })
1355        .maxLines(1)
1356        .style()
1357
1358      Text('marquee').fontSize(9).fontColor(0xCCCCCC)
1359      // Set the text to continuously scroll when text overflow occurs.
1360      Text('This is the text with the text overflow set marquee')
1361        .textOverflow({ overflow: TextOverflow.MARQUEE })
1362        .style()
1363        .marqueeOptions({
1364          start: true,
1365          fromStart: true,
1366          step: 6,
1367          loop: -1,
1368          delay: 0,
1369          fadeout: false,
1370          marqueeStartPolicy: MarqueeStartPolicy.DEFAULT
1371        })
1372        .onMarqueeStateChange((state: MarqueeState) => {
1373          if (state == MarqueeState.START) {
1374            // "Received state: START";
1375          } else if (state == MarqueeState.BOUNCE) {
1376            // "Received state: BOUNCE";
1377          } else if (state == MarqueeState.FINISH) {
1378            // "Received state: FINISH";
1379          }
1380        })
1381
1382      Text('ellipsisMode').fontSize(9).fontColor(0xCCCCCC)
1383      // Set the position of the ellipsis (...) for text truncation.
1384      Text(this.text)
1385        .textOverflow({ overflow: TextOverflow.Ellipsis })
1386        .ellipsisMode(this.ellipsisMode[this.ellipsisModeIndex])
1387        .maxLines(1)
1388        .style()
1389
1390      Row() {
1391        Button('Ellipsis Position: ' + this.ellipsisModeStr[this.ellipsisModeIndex]).onClick(() => {
1392          this.ellipsisModeIndex++;
1393          if (this.ellipsisModeIndex > (this.ellipsisModeStr.length - 1)) {
1394            this.ellipsisModeIndex = 0;
1395          }
1396        })
1397      }
1398    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
1399  }
1400}
1401```
1402
1403![](figures/textExp3.gif)
1404
1405### Example 4: Setting Text Wrapping and Line Breaking
1406
1407This example demonstrates the effects of different text wrapping and line breaking rules, as well as whether text is clipped when it exceeds the container's length, using the **wordBreak**, **lineBreakStrategy**, and **clip** attributes.
1408
1409```ts
1410// xxx.ets
1411@Extend(Text)
1412function style() {
1413  .fontSize(12)
1414  .border({ width: 1 })
1415  .padding(10)
1416  .width('100%')
1417  .margin(5)
1418}
1419
1420@Entry
1421@Component
1422struct TextExample4 {
1423  @State text: string =
1424    'The text component is used to display a piece of textual information.Support universal attributes and universal text attributes.';
1425  @State text2: string =
1426    "They can be classified as built-in components–those directly provided by the ArkUI framework and custom components – those defined by developers" +
1427      "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," +
1428      "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.";
1429  @State textClip: boolean = false;
1430  @State wordBreakIndex: number = 0;
1431  @State wordBreak: WordBreak[] = [WordBreak.NORMAL, WordBreak.BREAK_ALL, WordBreak.BREAK_WORD];
1432  @State wordBreakStr: string[] = ['NORMAL', 'BREAK_ALL', 'BREAK_WORD'];
1433  @State lineBreakStrategyIndex: number = 0;
1434  @State lineBreakStrategy: LineBreakStrategy[] =
1435    [LineBreakStrategy.GREEDY, LineBreakStrategy.HIGH_QUALITY, LineBreakStrategy.BALANCED];
1436  @State lineBreakStrategyStr: string[] = ['GREEDY', 'HIGH_QUALITY', 'BALANCED'];
1437
1438  build() {
1439    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1440      Text('wordBreak').fontSize(9).fontColor(0xCCCCCC)
1441      // Set the word break rule.
1442      Text(this.text)
1443        .maxLines(2)
1444        .textOverflow({ overflow: TextOverflow.Ellipsis })
1445        .wordBreak(this.wordBreak[this.wordBreakIndex])
1446        .style()
1447
1448      Row() {
1449        Button('wordBreak Value: ' + this.wordBreakStr[this.wordBreakIndex]).onClick(() => {
1450          this.wordBreakIndex++;
1451          if (this.wordBreakIndex > (this.wordBreakStr.length - 1)) {
1452            this.wordBreakIndex = 0;
1453          }
1454        })
1455      }
1456
1457      Text('clip').fontSize(9).fontColor(0xCCCCCC)
1458      // Set whether text is clipped when it exceeds the length.
1459      Text('This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.')
1460        .wordBreak(WordBreak.NORMAL)
1461        .maxLines(2)
1462        .clip(this.textClip)
1463        .style()
1464      Row() {
1465        Button('Clip Mode: ' + this.textClip).onClick(() => {
1466          this.textClip = !this.textClip;
1467        })
1468      }
1469
1470      Text('lineBreakStrategy').fontSize(9).fontColor(0xCCCCCC)
1471      // Set the text line breaking rule.
1472      Text(this.text2)
1473        .lineBreakStrategy(this.lineBreakStrategy[this.lineBreakStrategyIndex])
1474        .style()
1475      Row() {
1476        Button('lineBreakStrategy Value: ' + this.lineBreakStrategyStr[this.lineBreakStrategyIndex]).onClick(() => {
1477          this.lineBreakStrategyIndex++;
1478          if (this.lineBreakStrategyIndex > (this.lineBreakStrategyStr.length - 1)) {
1479            this.lineBreakStrategyIndex = 0;
1480          }
1481        })
1482      }
1483    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
1484  }
1485}
1486```
1487
1488![](figures/textExp4.gif)
1489
1490### Example 5: Setting Text Selection and Copy
1491
1492This example demonstrates how to set text selection, trigger a copy callback, make text selection draggable, and modify the caret and selection background colors using **selection**, **onCopy**, **draggable**, **caretColor**, and **selectedBackgroundColor**.
1493
1494```ts
1495// xxx.ets
1496@Entry
1497@Component
1498struct TextExample5 {
1499  @State onCopy: string = '';
1500  @State text: string =
1501    'This is set selection to Selection text content This is set selection to Selection text content.';
1502  @State start: number = 0;
1503  @State end: number = 20;
1504
1505  build() {
1506    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) {
1507      Text(this.text)
1508        .fontSize(12)
1509        .border({ width: 1 })
1510        .lineHeight(20)
1511        .margin(30)
1512        .copyOption(CopyOptions.InApp)
1513        .selection(this.start, this.end)
1514        .onCopy((value: string) => {
1515          this.onCopy = value;
1516        })
1517        .draggable(true)
1518        .caretColor(Color.Red)
1519        .selectedBackgroundColor(Color.Grey)
1520        .enableHapticFeedback(true)
1521      Button('Set text selection')
1522        .margin({ left: 20 })
1523        .onClick(() => {
1524          // Change the start point and end point of the text selection.
1525          this.start = 10;
1526          this.end = 30;
1527        })
1528      Text(this.onCopy).fontSize(12).margin(10).key('copy')
1529    }.height(600).width(335).padding({ left: 35, right: 35, top: 35 })
1530  }
1531}
1532```
1533![](figures/textExample5.png)
1534
1535### Example 6: Setting Text Adaptation and Font Scale Factor Limits
1536
1537This example demonstrates how to implement text adaptation using **heightAdaptivePolicy** and to set font scale factor limits using **minFontScale** and **maxFontScale**.
1538
1539```ts
1540// xxx.ets
1541@Extend(Text)
1542function style(HeightAdaptivePolicy: TextHeightAdaptivePolicy) {
1543  .width('80%')
1544  .height(90)
1545  .borderWidth(1)
1546  .minFontSize(10)
1547  .maxFontSize(30)
1548  .maxLines(2)
1549  .margin(5)
1550  .textOverflow({ overflow: TextOverflow.Ellipsis })
1551  .heightAdaptivePolicy(HeightAdaptivePolicy)
1552}
1553
1554@Entry
1555@Component
1556struct TextExample6 {
1557  build() {
1558    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
1559      // Set how the adaptive height is determined for the text.
1560      Text('heightAdaptivePolicy').fontSize(9).fontColor(0xCCCCCC)
1561      Text('This is the text with the height adaptive policy set.')
1562        .style(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
1563      Text('This is the text with the height adaptive policy set.')
1564        .style(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST)
1565      Text('This is the text with the height adaptive policy set.')
1566        .style(TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST)
1567
1568      Text('fontScale').fontSize(9).fontColor(0xCCCCCC)
1569      Text('This is the text content with minFontScale set to 1 and maxFontScale set to 1.2')
1570        .style(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
1571        .minFontScale(1)
1572        .maxFontScale(1.2)
1573    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
1574  }
1575}
1576```
1577
1578![textHeightAdaptivePolicy](figures/textHeightAdaptivePolicy.PNG)
1579
1580### Example 7: Setting Text Recognition
1581
1582This example demonstrates how to implement text recognition features using the **enableDataDetector** and **dataDetectorConfig** APIs.
1583
1584```ts
1585// xxx.ets
1586@Entry
1587@Component
1588struct TextExample7 {
1589  @State phoneNumber: string = '(86) (755) ********';
1590  @State url: string = 'www.********.com';
1591  @State email: string = '***@example.com';
1592  @State address: string = 'XX (province) XX (city) XX (county) XXXX';
1593  @State datetime: string = 'XX-XX-XX XXXX';
1594  @State enableDataDetector: boolean = true;
1595  @State types: TextDataDetectorType[] = [];
1596
1597  build() {
1598    Row() {
1599      Column() {
1600        Text(
1601          'Phone number:' + this.phoneNumber + '\n' +
1602            'URL:' + this.url + '\n' +
1603            'Email:' + this.email + '\n' +
1604            'Address:' + this.address + '\n' +
1605            'Time:' + this.datetime
1606        )
1607          .fontSize(16)
1608          .copyOption(CopyOptions.InApp)
1609          .enableDataDetector(this.enableDataDetector)
1610          .dataDetectorConfig({
1611            types: this.types, onDetectResultUpdate: (result: string) => {
1612            }
1613          })
1614          .textAlign(TextAlign.Center)
1615          .borderWidth(1)
1616          .padding(10)
1617          .width('100%')
1618      }
1619      .width('100%')
1620    }
1621    .height('100%')
1622  }
1623}
1624```
1625
1626![](figures/text7.png)
1627
1628### Example 8: Binding Text to a Custom Menu
1629
1630This example showcases how to bind text to a custom menu using the **bindSelectionMenu**, **onTextSelectionChange**, and **closeSelectionMenu** APIs.
1631
1632```ts
1633// xxx.ets
1634@Entry
1635@Component
1636struct TextExample8 {
1637  controller: TextController = new TextController();
1638  options: TextOptions = { controller: this.controller };
1639
1640  build() {
1641    Column() {
1642      Column() {
1643        Text(undefined, this.options) {
1644          Span('Hello World')
1645          ImageSpan($r('app.media.icon'))
1646            .width('100px')
1647            .height('100px')
1648            .objectFit(ImageFit.Fill)
1649            .verticalAlign(ImageSpanAlignment.CENTER)
1650        }
1651        .copyOption(CopyOptions.InApp)
1652        .bindSelectionMenu(TextSpanType.IMAGE, this.LongPressImageCustomMenu, TextResponseType.LONG_PRESS, {
1653          onDisappear: () => {
1654            console.info(`Callback when the custom menu is closed`);
1655          },
1656          onAppear: () => {
1657            console.info(`Callback when the custom menu is displayed`);
1658          }
1659        })
1660        .bindSelectionMenu(TextSpanType.TEXT, this.RightClickTextCustomMenu, TextResponseType.RIGHT_CLICK)
1661        .bindSelectionMenu(TextSpanType.MIXED, this.SelectMixCustomMenu, TextResponseType.SELECT)
1662        .onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
1663          console.info(`Callback when the text selection changes, selectionStart: ${selectionStart}, selectionEnd: ${selectionEnd}`);
1664        })
1665        .borderWidth(1)
1666        .borderColor(Color.Red)
1667        .width(200)
1668        .height(100)
1669      }
1670      .width('100%')
1671      .backgroundColor(Color.White)
1672      .alignItems(HorizontalAlign.Start)
1673      .padding(25)
1674    }
1675    .height('100%')
1676  }
1677
1678  @Builder
1679  RightClickTextCustomMenu() {
1680    Column() {
1681      Menu() {
1682        MenuItemGroup() {
1683          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 1", labelInfo: "" })
1684            .onClick((event) => {
1685              this.controller.closeSelectionMenu();
1686            })
1687          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 2", labelInfo: "" })
1688          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Right Click Menu 3", labelInfo: "" })
1689        }
1690      }
1691      .MenuStyles()
1692    }
1693  }
1694
1695  @Builder
1696  LongPressImageCustomMenu() {
1697    Column() {
1698      Menu() {
1699        MenuItemGroup() {
1700          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 1", labelInfo: "" })
1701            .onClick((event) => {
1702              this.controller.closeSelectionMenu();
1703            })
1704          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 2", labelInfo: "" })
1705          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Long Press Image Menu 3", labelInfo: "" })
1706        }
1707      }
1708      .MenuStyles()
1709    }
1710  }
1711
1712  @Builder
1713  SelectMixCustomMenu() {
1714    Column() {
1715      Menu() {
1716        MenuItemGroup() {
1717          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 1", labelInfo: "" })
1718            .onClick((event) => {
1719              this.controller.closeSelectionMenu();
1720            })
1721          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 2", labelInfo: "" })
1722          MenuItem({ startIcon: $r('app.media.app_icon'), content: "Select Mixed Menu 3", labelInfo: "" })
1723        }
1724      }
1725      .MenuStyles()
1726    }
1727  }
1728}
1729
1730@Extend(Menu)
1731function MenuStyles() {
1732  .radius($r('sys.float.ohos_id_corner_radius_card'))
1733  .clip(true)
1734  .backgroundColor('#F0F0F0')
1735}
1736```
1737
1738![](figures/textBindSelectionMenu.gif)
1739
1740### Example 9: Setting Text Features and Line Spacing
1741
1742This example demonstrates the effects of setting text features and line spacing using the **fontFeature** and **lineSpacing** APIs.
1743
1744```ts
1745// xxx.ets
1746import { LengthMetrics } from '@kit.ArkUI'
1747
1748@Extend(Text)
1749function style() {
1750  .fontSize(12)
1751  .border({ width: 1 })
1752  .width('100%')
1753}
1754
1755@Entry
1756@Component
1757struct TextExample9 {
1758  build() {
1759    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
1760      Text('lineSpacing').fontSize(9).fontColor(0xCCCCCC)
1761      // Set the line spacing.
1762      Text('This is a context with no lineSpacing set.')
1763        .lineSpacing(undefined)
1764        .style()
1765      Text('This is a context with lineSpacing set to 20_px.')
1766        .lineSpacing(LengthMetrics.px(20))
1767        .style()
1768      Text('This is the context with lineSpacing set to 20_vp.')
1769        .lineSpacing(LengthMetrics.vp(20))
1770        .style()
1771      Text('This is the context with lineSpacing set to 20_fp.')
1772        .lineSpacing(LengthMetrics.fp(20))
1773        .style()
1774      Text('This is the context with lineSpacing set to 20_lpx.')
1775        .lineSpacing(LengthMetrics.lpx(20))
1776        .style()
1777      Text('This is the context with lineSpacing set to 100%.')
1778        .lineSpacing(LengthMetrics.percent(1))
1779        .style()
1780
1781      Text('fontFeature').fontSize(9).fontColor(0xCCCCCC)
1782      // Set text features.
1783      Text('This is ss01 on : 0123456789')
1784        .fontFeature("\"ss01\" on")
1785        .style()
1786      Text('This is ss01 off: 0123456789')
1787        .fontFeature("\"ss01\" off")
1788        .style()
1789    }.height(300).width(350).padding({ left: 35, right: 35, top: 35 })
1790  }
1791}
1792```
1793
1794![](figures/TextExample8.PNG)
1795
1796### Example 10: Obtaining Text Information
1797
1798This example shows how to obtain text information by calling the layout manager object of the text using the **getLayoutManager** API.
1799
1800```ts
1801// xxx.ets
1802import { text } from '@kit.ArkGraphics2D'
1803
1804@Entry
1805@Component
1806struct TextExample10 {
1807  @State lineCount: string = "";
1808  @State glyphPositionAtCoordinate: string = "";
1809  @State lineMetrics: string = "";
1810  @State rectsForRangeStr: string = "";
1811  controller: TextController = new TextController();
1812  @State textStr: string =
1813    'Hello World!';
1814
1815  build() {
1816    Scroll() {
1817      Column() {
1818        Text('Use getLayoutManager to get layout information')
1819          .fontSize(15)
1820          .fontColor(0xCCCCCC)
1821          .width('90%')
1822          .padding(10)
1823        Text(this.textStr, { controller: this.controller })
1824          .fontSize(25)
1825          .borderWidth(1)
1826          .onAreaChange(() => {
1827            let layoutManager: LayoutManager = this.controller.getLayoutManager();
1828            this.lineCount = "LineCount: " + layoutManager.getLineCount();
1829          })
1830
1831        Text('LineCount').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
1832        Text(this.lineCount)
1833
1834        Text('GlyphPositionAtCoordinate').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
1835        Button("Relative Component Coordinates [150,50]")
1836          .onClick(() => {
1837            let layoutManager: LayoutManager = this.controller.getLayoutManager();
1838            let position: PositionWithAffinity = layoutManager.getGlyphPositionAtCoordinate(150, 50);
1839            this.glyphPositionAtCoordinate =
1840              "Relative component coordinates [150,50] glyphPositionAtCoordinate position: " + position.position + " affinity: " +
1841              position.affinity;
1842          })
1843          .margin({ bottom: 20, top: 10 })
1844        Text(this.glyphPositionAtCoordinate)
1845
1846        Text('LineMetrics').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
1847        Button("Line Metrics")
1848          .onClick(() => {
1849            let layoutManager: LayoutManager = this.controller.getLayoutManager();
1850            let lineMetrics: LineMetrics = layoutManager.getLineMetrics(0);
1851            this.lineMetrics = "lineMetrics is " + JSON.stringify(lineMetrics) + "\n\n";
1852            let runMetrics = lineMetrics.runMetrics;
1853            runMetrics.forEach((value, key) => {
1854              this.lineMetrics += "runMetrics key is " + key + " " + JSON.stringify(value) + "\n\n";
1855            })
1856          })
1857          .margin({ bottom: 20, top: 10 })
1858        Text(this.lineMetrics)
1859
1860        Text('getRectsForRange').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
1861        Button("Drawing Area Info for Characters/Placeholders within Specified Text Range")
1862          .onClick(() => {
1863            let layoutManager: LayoutManager = this.controller.getLayoutManager();
1864            let range: TextRange = { start: 0, end: 1 };
1865            let rectsForRangeInfo: text.TextBox[] =
1866              layoutManager.getRectsForRange(range, text.RectWidthStyle.TIGHT, text.RectHeightStyle.TIGHT);
1867            this.rectsForRangeStr = "getRectsForRange result is " + "\n\n";
1868            rectsForRangeInfo.forEach((value, key) => {
1869              this.rectsForRangeStr += "rectsForRange key is " + key + " " + JSON.stringify(value) + "\n\n";
1870            })
1871          })
1872          .margin({ bottom: 20, top: 10 })
1873        Text(this.rectsForRangeStr)
1874      }
1875      .margin({ top: 100, left: 8, right: 8 })
1876    }
1877  }
1878}
1879```
1880
1881![textLayoutManager](figures/textLayoutManager.gif)
1882
1883### Example 11: Implementing Keyboard-based Text Selection
1884
1885This example demonstrates how to implement the feature to select text using the keyboard by setting the **textSelectable** attribute to **TextSelectMode.SELECTABLE_FOCUSABLE**.
1886
1887```ts
1888// xxx.ets
1889@Entry
1890@Component
1891struct TextExample11 {
1892  @State message: string =
1893    'TextTextTextTextTextTextTextText' + 'TextTextTextTextTextTextTextTextTextTextTextTextTextTextTextText';
1894
1895  build() {
1896    Column() {
1897      Text(this.message)
1898        .width(300)
1899        .height(100)
1900        .maxLines(5)
1901        .fontColor(Color.Black)
1902        .copyOption(CopyOptions.InApp)
1903        .selection(3, 8)
1904        .textSelectable(TextSelectableMode.SELECTABLE_FOCUSABLE)
1905    }.width('100%').margin({ top: 100 })
1906  }
1907}
1908```
1909
1910![textTextSelectableMode](figures/textTextSelectableMode.gif)
1911
1912### Example 12: Setting Custom Menu Extensions
1913
1914This example demonstrates how to use the **editMenuOptions** API to create custom menu extensions for text settings. It includes customizing text content, icons, and callbacks for these extensions.
1915
1916```ts
1917// xxx.ets
1918@Entry
1919@Component
1920struct TextExample12 {
1921  @State text: string = 'Text editMenuOptions'
1922  onCreateMenu = (menuItems: Array<TextMenuItem>) => {
1923    let item1: TextMenuItem = {
1924      content: 'Custom 1',
1925      icon: $r('app.media.startIcon'),
1926      id: TextMenuItemId.of('custom1'),
1927    };
1928    let item2: TextMenuItem = {
1929      content: 'Custom 2',
1930      id: TextMenuItemId.of('custom2'),
1931      icon: $r('app.media.startIcon'),
1932    };
1933    menuItems.push(item1);
1934    menuItems.unshift(item2);
1935    return menuItems;
1936  }
1937  onMenuItemClick = (menuItem: TextMenuItem, textRange: TextRange) => {
1938    if (menuItem.id.equals(TextMenuItemId.of("custom2"))) {
1939      console.log("Intercept id: custom2 start:" + textRange.start + "; end:" + textRange.end);
1940      return true;
1941    }
1942    if (menuItem.id.equals(TextMenuItemId.COPY)) {
1943      console.log("Intercept COPY start:" + textRange.start + "; end:" + textRange.end);
1944      return true;
1945    }
1946    if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) {
1947      console.log("Do not intercept SELECT_ALL start:" + textRange.start + "; end:" + textRange.end);
1948      return false;
1949    }
1950    return false;
1951  };
1952  @State editMenuOptions: EditMenuOptions = {
1953    onCreateMenu: this.onCreateMenu, onMenuItemClick: this.onMenuItemClick
1954  };
1955
1956  build() {
1957    Column() {
1958      Text(this.text)
1959        .fontSize(20)
1960        .copyOption(CopyOptions.LocalDevice)
1961        .editMenuOptions(this.editMenuOptions)
1962        .margin({ top: 100 })
1963    }
1964    .width("90%")
1965    .margin("5%")
1966  }
1967}
1968```
1969
1970![textEditMenuOptions](figures/textEditMenuOptions.gif)
1971
1972### Example 13: Securing Sensitive Information
1973
1974This example illustrates how to secure sensitive information using the **privacySensitive** attribute. Note that the display requires widget framework support.
1975
1976```ts
1977// xxx.ets
1978@Entry
1979@Component
1980struct TextExample13 {
1981  build() {
1982    Column({ space: 10 }) {
1983      Text("privacySensitive")
1984        .privacySensitive(true)
1985        .margin({ top: 30 })
1986    }
1987    .alignItems(HorizontalAlign.Center)
1988    .width("100%")
1989  }
1990}
1991```
1992
1993![textPrivacySensitive](figures/textPrivacySensitive.gif)
1994