Text

The Text component is used to display a piece of textual information.

NOTE

This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.

Child Components

This component can contain the Span, ImageSpan, SymbolSpan, and ContainerSpan child components.

NOTE

Use child components to implement text and image layout scenarios.

APIs

Text(content?: string | Resource , value?: TextOptions)

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
content string | Resource No Plain text. This parameter takes effect when the child component Span is not included and styled string is not set.
Default value: ' '
NOTE
Priority of displayed content: Styled string > Content of the Span component > Text content of the Text component.
value11+ TextOptions No Initialization options of the component.

Attributes

In addition to the universal attributes, the following attributes are supported.

Layout and Alignment

Attributes Description
baselineOffset Sets the offset of the text baseline.
halfLeading12+ Whether half leading is enabled. Half leading refers to splitting the leading in half and applying it equally to the top and bottom of the line.
textAlign Sets the horizontal alignment mode of the text.
textContentAlign21+ Sets the vertical alignment of the text content area within the component.
textVerticalAlign20+ Sets the vertical alignment of the text.

Font Style

Attributes Description
decoration Style and color of the text decorative line.
font10+ Sets the text style.
font12+ Sets the font style, with support for font settings.
fontColor Sets the font color.
fontFamily Sets the font family.
fontFeature12+ Sets the font feature, for example, monospaced digits.
fontSize Sets the text size.
fontStyle Sets the font style.
fontWeight Sets the font weight.
fontWeight12+ Sets the text font weight, with support for font settings.
letterSpacing Sets the letter spacing for a text style.
shaderStyle20+ Applies gradient or solid color effects to text.
textCase Sets the text case.
textShadow10+ Text shadow.

Text Overflow, Line Break, and Line Wrapping

Attributes Description
ellipsisMode11+ Sets the ellipsis position.
lineBreakStrategy12+ Sets the line break rule.
marqueeOptions18+ Sets the marquee effect for text.
textOverflow Sets the display mode for overflowing text.
wordBreak11+ Sets the word break rule.

Line and Paragraph

Attributes Description
enableAutoSpacing20+ Sets whether to enable automatic spacing between Chinese and Western characters.
lineHeight Sets the text line height.
lineHeightMultiple22+ Sets the line height multiplier for the text.
lineSpacing12+ Sets the line spacing for the text.
lineSpacing20+ Sets the line spacing for the text. When LineSpacingOptions is not specified, line spacing is applied above the first line and below the last line by default.
maxLineHeight22+ Sets the maximum line height of the text.
maxLines Sets the maximum number of lines in the text.
minLineHeight22+ Sets the minimum line height of the text.
minLines22+ Sets the minimum number of lines in the text.
optimizeTrailingSpace20+ Sets whether to optimize trailing spaces at line endings.
textIndent10+ Sets the indent of the first line text.

Font Adaptation

Attributes Description
heightAdaptivePolicy10+ Sets the font size adjustment strategy for adaptive text layout.
maxFontScale12+ Sets the maximum font scale factor for text.
maxFontSize Sets the maximum font size.
minFontScale12+ Sets the minimum font scale factor for text.
minFontSize Sets the minimum font size.

Text Selection and Copy

Attributes Description
caretColor14+ Sets the color of the text selection handle, also known as the caret, in the text box.
copyOption9+ Sets whether copy and paste operations are allowed.
draggable9+ Sets the drag effect of the selected text.
selectedBackgroundColor14+ Sets the background color of the selected text.
selection11+ Sets text selection.
textSelectable12+ Sets whether the text is selectable and focusable.

Text Recognition

Attributes Description
dataDetectorConfig11+ Configures text recognition settings.
enableDataDetector11+ Enables recognition for special entities within the text.
enableSelectedDataDetector22+ Sets whether to enable entity recognition for selected text.

Custom Menu

Attributes Description
bindSelectionMenu11+ Sets the custom selection menu.
editMenuOptions12+ Sets the extended options for the custom menu.

Other Functionality

Attributes Description
contentTransition20+ Text animation effect.
enableHapticFeedback13+ Sets whether to enable haptic feedback.
privacySensitive12+ Sets whether to enable privacy mode on widgets.

The following describes the details of each API.

baselineOffset

baselineOffset(value: number | ResourceStr)

Sets the offset of the text baseline.

Percentage values follow default display behavior.

A positive value moves the content upwards, while a negative value moves it downwards.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value number | ResourceStr Yes Offset of the text baseline.
Default value: 0
The Resource type is supported since API version 20.

bindSelectionMenu11+

bindSelectionMenu(spanType: TextSpanType, content: CustomBuilder, responseType: TextResponseType, options?: SelectionMenuOptions)

Sets the custom selection menu.

The long-press response duration of bindSelectionMenu is 600 ms while that of bindContextMenu is 800 ms. When both are bound and their triggering methods are set to long press, bindSelectionMenu takes precedence.

When the custom menu is too long, it is recommended that nest a Scroll component inside to prevent the keyboard from being obscured.

NOTE

This API cannot be called within attributeModifier.

When editMenuOptions is used for configuring the text selection menu, the system's default style and trigger conditions are preserved.

In contrast, when bindSelectionMenu is used, both the menu style and the trigger conditions are fully customizable.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
spanType TextSpanType Yes Span type of the menu.
Default value: TextSpanType.TEXT
content CustomBuilder Yes Content of the menu.
responseType TextResponseType Yes Response type of the menu.
Default value: TextResponseType.LONG_PRESS
options SelectionMenuOptions No Options of the menu.

caretColor14+

caretColor(color: ResourceColor)

Sets the color of the text selection handle, also known as the caret, in the text box.

Atomic service API: This API can be used in atomic services since API version 14.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
color ResourceColor Yes Color of the text selection handle.
Default value: '#007DFF'

contentTransition20+

contentTransition(transition: Optional<ContentTransition>)

Applies a transition animation to text content. Supports numeric flip animation via NumericTextTransition.

Atomic service API: This API can be used in atomic services since API version 20.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
transition Optional<ContentTransition> Yes Text animation effect.

copyOption9+

copyOption(value: CopyOptions)

Sets whether copy and paste operations are allowed.

Since API version 20, copied text from the Text component includes HTML-formatted content in the pasteboard.

  • When the Text component contains child elements, only Span and ImageSpan support HTML-formatted pasteboard content.

  • For styled strings, refer to toHtml for supported HTML conversion scope.

When copyOption is set to CopyOptions.InApp or CopyOptions.LocalDevice:

  • A long press on the text will display a menu that offers the copy and select-all options.

  • By default, selected text is draggable. To disable dragging, set draggable to false.

  • To support Ctrl+C copying, also set textSelectable to TextSelectableMode.SELECTABLE_FOCUSABLE.

The Text component listens for onClick, which is a non-bubbling event. To allow parent components to respond to clicks within the Text area, use parallelGesture on the parent. For implementation guidance, see Example 7: Setting Text Recognition.

Because widgets do not have the long press event, the menu will not be displayed when users long press text.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value CopyOptions Yes Whether copy and paste operations are allowed.
Default value: CopyOptions.None

dataDetectorConfig11+

dataDetectorConfig(config: TextDataDetectorConfig)

Configures text recognition settings, including entity types to detect, display styles for detected entities, and long-press preview options.

This API must be used together with enableDataDetector. It takes effect only when enableDataDetector is set to true.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
config TextDataDetectorConfig Yes Text recognition configuration.

decoration

decoration(value: DecorationStyleInterface)

Style and color of the text decorative line.

NOTE

When the bottom contour of a character intersects with the decoration, underline avoidance is triggered, commonly affecting characters like "g", "j", "y", "q", and "p."

If the decoration color is set to Color.Transparent, it inherits the text color of the first character in each line. If the decoration color is set to "#00FFFFFF", the line becomes fully transparent.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value DecorationStyleInterface12+ Yes Style of the text decorative line.
Default value:
{
 type: TextDecorationType.None,
 color: Color.Black,
 style: TextDecorationStyle.SOLID 
}
NOTE
The style parameter cannot be used in widgets.

draggable9+

draggable(value: boolean)

Sets the drag effect of the selected text.

This attribute cannot be used together with the onDragStart event.

If set to true, draggable must be used in conjunction with CopyOptions. When copyOptions is set to CopyOptions.InApp or CopyOptions.LocalDevice, the selected text becomes draggable and can be copied into a text box.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value boolean Yes Drag effect of the selected text.
true: The selected text is draggable. false: The selected text is not draggable.
Default value: false

editMenuOptions12+

editMenuOptions(editMenu: EditMenuOptions)

Sets the extended options for the custom menu, including the text content, icon, and callback.

When disableMenuItems or disableSystemServiceMenuItems is used to disable system service menu items in the text selection menu, the disabled menu options will be excluded from the parameter list in the onCreateMenu callback of editMenuOptions.

NOTE

When editMenuOptions is used for configuring the text selection menu, the system's default style and trigger conditions are preserved.

In contrast, when bindSelectionMenu is used, both the menu style and the trigger conditions are fully customizable.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
editMenu EditMenuOptions Yes Extended options of the custom menu.

ellipsisMode11+

ellipsisMode(value: EllipsisMode)

Sets 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.

EllipsisMode.START and EllipsisMode.CENTER take effect only when text overflows in a single line.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value EllipsisMode Yes Ellipsis position.
Default value: EllipsisMode.END

enableAutoSpacing20+

enableAutoSpacing(enabled: Optional<boolean>)

Sets whether to enable automatic spacing between Chinese and Western characters.

Atomic service API: This API can be used in atomic services since API version 20.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
enabled Optional<boolean> Yes Whether to enable automatic spacing between Chinese and Western characters.
true to enable, false otherwise.
Default value: false

enableDataDetector11+

enableDataDetector(enable: boolean)

Sets whether to enable special entity detection within the text. Special entities are detected when enableDataDetector is set to true.

The style of detected entities is as follows: the font color is changed to blue, and a blue underline is added.

color: '#ff007dff'
decoration:{
  type: TextDecorationType.Underline,
  color: '#ff007dff',
  style: TextDecorationStyle.SOLID
}

NOTE

  • This API takes effect only when the device has an underlying text detection capability.

  • When textOverflow is set to TextOverflow.MARQUEE, text special entity detection is not performed.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
enable boolean Yes Whether to enable text recognition.
true: Enable text recognition. false: Disable text recognition.
Default value: false

enableHapticFeedback13+

enableHapticFeedback(isEnabled: boolean)

Sets whether to enable haptic feedback.

To enable haptic feedback, you must declare the ohos.permission.VIBRATE permission under requestPermissions in the module.json5 file of the project.

"requestPermissions": [
 {
    "name": "ohos.permission.VIBRATE",
 }
]

NOTE

This API can be called within attributeModifier since API version 18.

Atomic service API: This API can be used in atomic services since API version 13.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
isEnabled boolean Yes Whether to enable haptic feedback.
true to enable, false otherwise.
Default value: true

enableSelectedDataDetector22+

enableSelectedDataDetector(enable: boolean | undefined)

Sets whether to enable entity recognition for selected text. This API only works on devices that provide text recognition.

When enableSelectedDataDetector is set to true, all entity types are recognized by default.

This feature is only effective when CopyOptions is set to CopyOptions.LocalDevice or CopyOptions.CrossDevice.

Atomic service API: This API can be used in atomic services since API version 22.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
enable boolean | undefined Yes Whether to enable entity recognition for selected text.
true: Entity recognition is enabled. false: Entity recognition is disabled. Default value: true

font10+

font(value: Font)

Sets the text style, covering the font size, font width, font family, and font style.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value Font Yes Text style.

font12+

font(fontValue: Font, options?: FontSettingOptions)

Sets the font style, with support for font settings.

It is only effective for the Text component, not for its child components.

Widget capability: This API can be used in ArkTS widgets since API version 12.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
fontValue Font Yes Sets the text style.
options FontSettingOptions No Font settings.

fontColor

fontColor(value: ResourceColor)

Sets the font color.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value ResourceColor Yes Font color.
Default value: '#e6182431'
Default value for wearables: '#c5ffffff'

fontFamily

fontFamily(value: string | Resource)

Sets the font family.

NOTE

You can use loadFontSync to register custom fonts.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value string | Resource Yes Font family. Default font: 'HarmonyOS Sans'
To specify multiple fonts, separate them with commas (,), and fonts are applied in priority order. Example: 'Arial, HarmonyOS Sans'.

fontFeature12+

fontFeature(value: string)

Sets the font feature, for example, monospaced digits.

Format: normal | <feature-tag-value>

Format of <feature-tag-value>: <string> [ <integer> | on | off ]

There can be multiple <feature-tag-value> values, which are separated by commas (,).

For example, the input format for monospaced clock fonts is "ss01" on.

NOTE

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.

The typesetting engine rounds down the value of 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.

When multiple Text components are placed in the Row 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 or use the flex layout.

The system's default font supports the following ligatures: Th, fb, ff, fb, ffb, ffh, ffi, ffk, ffl, fh, fi, fk, fl, rf, rt, rv, rx, ry. These ligatures may cause unexpected effects of spans and styled strings. Disabling the ligature feature can avoid this issue.

Text rendering behavior is closely tied to the font file in use. For instance, the system's default font supports 8-punctuation compression only for left-side punctuation marks. Right-side punctuation, including exclamation marks, enumeration commas, and question marks, is not affected by this feature.

Widget capability: This API can be used in ArkTS widgets since API version 12.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value string Yes Font feature.

The figure below shows the font feature list.

alt text

Font features are advanced OpenType typographic capabilities such as ligatures, monospacing, and stylistic alternates. These features are typically utilized with custom fonts and require support from the font file itself.

For more information about the font features, see Low-level font feature settings control: the font-feature-settings property and The Complete CSS Demo for OpenType Features.

fontSize

fontSize(value: number | string | Resource)

Sets the text size.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value number | string | Resource Yes Font size. If fontSize is of the number type, the unit fp is used. This parameter cannot be set in percentage.
Default value: 16fp
Default value on wearable devices: 15fp

fontStyle

fontStyle(value: FontStyle)

Sets the font style.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value FontStyle Yes Font style.
Default value: FontStyle.Normal

fontWeight

fontWeight(value: number | FontWeight | ResourceStr)

Sets the font weight. If the value is too large, the text may be clipped depending on the font.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value number | FontWeight | ResourceStr 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.
Default value: FontWeight.Normal
Default value on wearable devices: FontWeight.Regular
The Resource type is supported since API version 20.

fontWeight12+

fontWeight(weight: number | FontWeight | ResourceStr, options?: FontSettingOptions)

Sets the text font weight, with support for font settings.

It is only effective for the Text component, not for its child components.

Widget capability: This API can be used in ArkTS widgets since API version 12.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
weight number | FontWeight | ResourceStr 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.
The Resource type is supported since API version 20.
options FontSettingOptions No Font setting options.
When enableVariableFontWeight in options is set to false, variable font weight adjustment is disabled. If weight is set to a value at intervals of 100 within [100, 900], the font weight uses the specified value. If weight is set to a value that is not a multiple of 100, the default value 400 is used.
When enableVariableFontWeight in options is set to true, variable font weight adjustment is enabled. If weight is set to any integer within [100, 900], the font weight uses the specified value.

halfLeading12+

halfLeading(halfLeading: boolean)

Whether half leading is enabled. Half leading refers to splitting the leading in half and applying it equally to the top and bottom of the line.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
halfLeading boolean Yes Whether half leading is enabled. Half leading refers to splitting the leading in half and applying it equally to the top and bottom of the line.
true: Half leading is enabled. false: Half leading is not enabled.
Default value: false

heightAdaptivePolicy10+

heightAdaptivePolicy(value: TextHeightAdaptivePolicy)

Sets the font size adjustment strategy for adaptive text layout.

The available modes are as follows:

  • MAX_LINES_FIRST: prioritizes using the maxLines attribute to control text height. If the maxLines setting results in a layout beyond the layout constraints, the text will shrink to a font size between minFontSize and maxFontSize to allow for more content to be shown.

  • MIN_FONT_SIZE_FIRST: prioritizes using the minFontSize attribute to control text height. If the text fits on one line at minFontSize, the system attempts to increase the font size between minFontSize and maxFontSize to fill the line with the largest available font size. If the text cannot fit on a single line even at minFontSize, it sticks with minFontSize.

  • LAYOUT_CONSTRAINT_FIRST: prioritizes using layout constraints to control 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.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value TextHeightAdaptivePolicy Yes How the adaptive height is determined for the text.
Default value: TextHeightAdaptivePolicy.MAX_LINES_FIRST

letterSpacing

letterSpacing(value: number | ResourceStr)

Sets 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.

Negative values compress text. Excessive compression may reduce content area to zero, hiding content.

This setting applies to every character, including those at line endings.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value number | ResourceStr Yes Letter spacing.
Default value: 0
Unit: fp
The Resource type is supported since API version 20.

lineBreakStrategy12+

lineBreakStrategy(strategy: LineBreakStrategy)

Sets the line break rule. This attribute takes effect only when wordBreak is not WordBreak.BREAK_ALL. Hyphens are not supported.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
strategy LineBreakStrategy Yes Line break rule.
Default value: LineBreakStrategy.GREEDY

lineHeight

lineHeight(value: number | string | Resource)

Sets the text line height.

If the value is less than or equal to 0, the line height is unrestricted and adapts to the font size. When the value is a number, the unit is fp. For the string type, numeric string values with optional units, for example, "10" or "10fp", are supported.

NOTE

If certain characters have significantly taller glyphs than others in the same line, layout anomalies such as clipping, overlapping, or misalignment may occur. In this case, adjust component attributes such as height and line height to ensure proper layout rendering.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value number | string | Resource Yes Text line height.

lineHeightMultiple22+

lineHeightMultiple(value: number | undefined)

Sets the line height of text in multiple mode.

The line height equals the input parameter value multiplied by fontHeight.

NOTE

When both this API and lineHeight are set, only lineHeightMultiple takes effect.

Widget capability: This API can be used in ArkTS widgets since API version 22.

Atomic service API: This API can be used in atomic services since API version 22.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value number | undefined Yes Multiplier for the line height.
Value range: ≥ 0
Values ≤ 0 are treated as 0. When the value is set to 0, the default line height is used. Decimal values are supported.

lineSpacing12+

lineSpacing(value: LengthMetrics)

Sets the line spacing of the text. If the value specified is less than or equal to 0, the default value 0 is used.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value LengthMetrics Yes Line spacing. Default value: 0

lineSpacing20+

lineSpacing(value: LengthMetrics, options?: LineSpacingOptions)

Sets the line spacing for text. When LineSpacingOptions is not specified, line spacing is applied above the first line and below the last line by default.

Atomic service API: This API can be used in atomic services since API version 20.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value LengthMetrics Yes Line spacing. Values less than or equal to 0 are treated as the default value 0.
options LineSpacingOptions No Line spacing configuration options.
Default value: { onlyBetweenLines: false }

marqueeOptions18+

marqueeOptions(options: Optional<TextMarqueeOptions>)

Sets the marquee effect for text.

The marqueeOptions settings take effect only when textOverflow is set to TextOverflow.MARQUEE.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options Optional<TextMarqueeOptions> Yes Marquee animation properties such as enable/disable, step size, loop count, and direction.

maxFontScale12+

maxFontScale(scale: number | Resource)

Sets the maximum font scale factor for text.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
scale number | Resource Yes Maximum font scale factor for text.
Value range: [1, +∞)
NOTE
Values less than 1 are treated as 1. Other invalid values are ineffective by default.

maxFontSize

maxFontSize(value: number | string | Resource)

Sets the maximum font size.

For the string type, numeric string values with optional units, for example, "10" or "10fp", are supported.

For the setting to take effect, this attribute must be used together with minFontSize and maxLines, or layout constraint settings.

When the adaptive font size is used, the fontSize settings do not take effect.

If the value of maxFontSize is less than or equal to 0 or is less than the value of minFontSize, the adaptive font sizing feature is disabled. In such cases, the fontSize attribute is used instead. If fontSize is not set, the default value will apply.

Since API version 18, adaptive font sizing is supported on child components and styled strings, and text segments without an explicitly defined font size will automatically adjust based on the available space.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value number | string | Resource Yes Maximum font size.
Unit: fp

maxLineHeight22+

maxLineHeight(value: LengthMetrics | undefined)

Sets the maximum line height of text. If the value is less than or equal to 0, the maximum line height is unrestricted.

If maxLineHeight is less than minLineHeight, maxLineHeight takes effect using the value of minLineHeight.

Widget capability: This API can be used in ArkTS widgets since API version 22.

Atomic service API: This API can be used in atomic services since API version 22.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value LengthMetrics | undefined Yes Maximum line height of text. Percentage values are not supported.
Values less than or equal to 0 are treated as 0. When the value is set to 0, the maximum line height is unrestricted.

selectedDragPreviewStyle23+

selectedDragPreviewStyle(value: SelectedDragPreviewStyle | undefined)

Sets the drag preview style for selected text.

Atomic service API: This API can be used in atomic services since API version 23.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value SelectedDragPreviewStyle | undefined Yes Drag preview style for selected text.
If this parameter is set to undefined, the drag preview follows the theme: white in light mode and black in dark mode.

maxLines

maxLines(value: number)

Sets the maximum number of lines for 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 to specify how it is displayed.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value number Yes Maximum number of lines of the text.
NOTE
Value range: [0, INT32_MAX]
If this parameter is set to 0, no text content is displayed.

minFontScale12+

minFontScale(scale: number | Resource)

Sets the minimum font scale factor for text.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
scale number | Resource Yes Minimum font scale factor for text.
Value range: [0, 1]
NOTE
Values less than 0 are treated as 0, and values greater than 1 are treated as 1. Other invalid values do not take effect by default.

minFontSize

minFontSize(value: number | string | Resource)

Sets the minimum font size.

For the string type, numeric string values with optional units, for example, "10" or "10fp", are supported.

For the setting to take effect, this attribute must be used together with maxFontSize and maxLines, or layout constraint settings.

When the adaptive font size is used, the fontSize settings do not take effect.

If the value of minFontSize is less than or equal to 0, the adaptive font sizing feature is disabled. In such cases, the fontSize attribute is used instead. If fontSize is not set, the default value will apply.

Since API version 18, adaptive font sizing is supported on child components and styled strings, and text segments without an explicitly defined font size will automatically adjust based on the available space.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value number | string | Resource Yes Minimum font size.
Unit: fp

minLineHeight22+

minLineHeight(value: LengthMetrics | undefined)

Sets the minimum line height of text. If the value is less than or equal to 0, the default value 0 is used.

Widget capability: This API can be used in ArkTS widgets since API version 22.

Atomic service API: This API can be used in atomic services since API version 22.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value LengthMetrics | undefined Yes Minimum line height of text. Percentage values are not supported.
Values less than or equal to 0 are treated as 0.

minLines22+

minLines(minLines: Optional<number>)

Sets the minimum number of lines for text.

If the actual text height is less than the height for the minimum number of lines, the component uses the height corresponding to the minimum number of lines.

When this API and maxLines are both set, the minimum line height cannot exceed the maximum line height.

If constraintSize is set for the text, the component height is confined within the constraintSize bounds.

Widget capability: This API can be used in ArkTS widgets since API version 22.

Atomic service API: This API can be used in atomic services since API version 22.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
minLines Optional<number> Yes Minimum number of lines of the text.
Value range: [0, INT32_MAX]
Values less than 0 are clamped to 0.

includeFontPadding23+

includeFontPadding(include: Optional<boolean>)

Sets whether to add spacing to the first and last lines to avoid text truncation. If this attribute is not set, no spacing is added by default.

Atomic service API: This API can be used in atomic services since API version 23.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
include Optional<boolean> Yes Whether to add spacing to the first and last lines to avoid text truncation.
true: Spacing is added to the first and last lines. false: Spacing is not added to the first and last lines.

fallbackLineSpacing23+

fallbackLineSpacing(enabled: Optional<boolean>)

Adapts the line height to the actual text height for overlapped multi-line text. This API takes effect only when the line height is less than the actual text height. If this API is not set, the line height does not adapt to the actual text height by default.

Atomic service API: This API can be used in atomic services since API version 23.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
enabled Optional<boolean> Yes Whether the line height adapts to the actual text height.
true: Line height adapts to the actual text height. false: Line height does not adapt to the actual text height.

optimizeTrailingSpace20+

optimizeTrailingSpace(optimize: Optional<boolean>)

Sets whether to optimize trailing spaces at line endings during text layout, resolving alignment display issues caused by trailing spaces.

When Text.optimizeTrailingSpace is set to true:

  • Trailing space optimization applies to multi-line text, single-line text, and text and image layouts (particularly noticeable with TextAlign.Center or TextAlign.End).

  • For text containing only spaces, decoration lines, shadows, and background colors follow the space text display.

  • Leading spaces are not optimized. When text with trailing spaces wraps, trailing spaces on each line are optimized based on component width.

When optimizing pure space text by setting optimizeTrailingSpace to true, you cannot simultaneously set backgroundColor, decoration, and textAlign attributes.

Atomic service API: This API can be used in atomic services since API version 20.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
optimize Optional<boolean> Yes Whether to optimize trailing spaces.
true to optimize, false otherwise.
Default value: false

compressLeadingPunctuation23+

compressLeadingPunctuation(enabled: Optional<boolean>)

Sets whether to enable leading punctuation compression.

NOTE

  • Leading punctuation is not compressed by default.

  • For the range of punctuation marks that support leading compression, see ParagraphStyle.

Atomic service API: This API can be used in atomic services since API version 23.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
enabled Optional<boolean> Yes Whether to enable leading punctuation compression.
true: Leading punctuation compression is enabled. false: Leading punctuation compression is disabled.

orphanCharOptimization

orphanCharOptimization(enabled: Optional<boolean>)

Sets whether to enable orphan character optimization during text typesetting. If this attribute is not set, orphan character optimization is disabled by default.

Orphan character optimization improves the text layout by handling the orphan character (the first Chinese character of the last line of a paragraph) more efficiently. When enabled, it adjusts line breaks to avoid orphan characters as much as possible. This feature takes effect only when wordBreak is not BREAK_ALL and locale of the first TextStyle of the text to be typeset is either "zh-Hans" or "zh-Hant".

Since: 26.0.0

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
enabled Optional<boolean> Yes Whether to enable orphan character optimization for the last line of the paragraph.
true: Orphan character optimization is enabled. false: Orphan character optimization is disabled.
When the value is undefined or null, orphan character optimization is disabled.

privacySensitive12+

privacySensitive(supported: boolean)

Sets whether to enable privacy mode on widgets.

Widget capability: This API can be used in ArkTS widgets since API version 12.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
supported boolean Yes Whether to enable privacy mode on widgets.
Default value: false. The value true means to enable privacy mode, in which case text is obscured with hyphens (-).
NOTE
The value null means not to enable privacy mode on widgets.
Enabling privacy mode requires support from the widget framework. You can use obscured to set how the component content is obscured.

selectedBackgroundColor14+

selectedBackgroundColor(color: ResourceColor)

Sets the background color of the selected text. If the opacity is not set, a 20% opacity will be used.

Atomic service API: This API can be used in atomic services since API version 14.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
color ResourceColor Yes Background color of the selected text.
Default value: '#007DFF'

selection11+

selection(selectionStart: number, selectionEnd: number)

Sets text selection.

The selected text is highlighted, with selection handles and the text selection menu displayed.

If copyOption is set to CopyOptions.None, the setting of the selection attribute does not take effect.

If textOverflow is set to TextOverflow.MARQUEE, the setting of the selection attribute does not take effect.

If 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.

If the selection range falls within a truncated or invisible area, selection is ignored. When clip is set to false, the text outside the parent component can be selected.

You can obtain the selection range change result through the onTextSelectionChange API.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
selectionStart number Yes Start position of the selected text.
Default value: -1
selectionEnd number Yes End position of the selected text.
Default value: -1

shaderStyle20+

shaderStyle(shader: ShaderStyle)

Applies gradient or solid color effects to text. Supports RadialGradientStyle, LinearGradientStyle, and ColorShaderStyle. shaderStyle takes precedence over fontColor and AI-based styling. For solid colors, prefer using fontColor.

Atomic service API: This API can be used in atomic services since API version 20.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
shader ShaderStyle Yes Shader effect.
Based on the input, the system applies a radial gradient (RadialGradientStyle), linear gradient (LinearGradientStyle), or solid color (ColorShaderStyle).
NOTE
If RadialGradientStyle is used and the center parameter (from RadialGradientOptions) is outside the component bounds, setting repeating to true enhances the gradient effect.

textAlign

textAlign(value: TextAlign)

Sets the horizontal alignment of the text.

The text takes up the full width of the Text component.

The vertical position of the text paragraph can be controlled by the align attribute, but the horizontal position cannot be controlled by align in this component. The specific effects are as follows:

  • Alignment.TopStart, Alignment.Top, Alignment.TopEnd: Content aligns to the top.

  • Alignment.Start, Alignment.Center, Alignment.End: Content is centered vertically.

  • Alignment.BottomStart, Alignment.Bottom, Alignment.BottomEnd: Content aligns to the bottom.

When textAlign is set to TextAlign.JUSTIFY, the wordBreak property must be configured according to the text content. The last line of text aligns to the start horizontally and does not participate in justification.

NOTE

textAlign only adjusts the overall text layout and does not affect character display order. For character display order adjustment, see Bidirectional Text Layout and Alignment.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value TextAlign Yes Horizontal alignment of the text.
Default value: TextAlign.Start
Default value on wearable devices: TextAlign.Center

textCase

textCase(value: TextCase)

Sets the text case.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value TextCase Yes Text case.
Default value: TextCase.Normal

textContentAlign21+

textContentAlign(textContentAlign: Optional<TextContentAlign>)

Sets the vertical alignment of the text content area within the component.

This API takes effect only when the height of the text content exceeds the component's height.

Atomic service API: This API can be used in atomic services since API version 21.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
textContentAlign Optional<TextContentAlign> Yes Vertical alignment of the text.
If the value is undefined or invalid, alignment defaults to Center.

textDirection23+

textDirection(direction: TextDirection | undefined)

Specifies the text layout direction. If this attribute is not set, the default text layout direction follows the component layout direction.

Atomic service API: This API can be used in atomic services since API version 23.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
direction TextDirection | undefined Yes Text layout direction.
If this parameter is set to undefined, the text layout direction follows the component layout direction as defined by TextDirection.DEFAULT.

textIndent10+

textIndent(value: Length)

Sets the indent of the first line text.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value Length Yes Indent of the first line text.
Default value: 0
Unit: fp

textOverflow

textOverflow(options: TextOverflowOptions)

Sets the display mode for overflowing text.

When TextOverflowOptions is set to TextOverflow.None, TextOverflow.Clip, or TextOverflow.Ellipsis:

  • TextOverflow.None or TextOverflow.Clip: Text is truncated when it exceeds the maximum number of lines.

  • TextOverflow.Ellipsis: Overflowing text is replaced with an ellipsis (...).

  • This must be used with maxLines for the settings to take effect.

  • Line breaking behavior is controlled by wordBreak. By default, it uses WordBreak.BREAK_WORD, which breaks text by word (for example, English text is broken at word boundaries). To break text by character, set wordBreak to WordBreak.BREAK_ALL.

  • Line wrapping behavior is governed by lineBreakStrategy which takes effect only when wordBreak is not WordBreak.BREAK_ALL. Hyphens are not supported.

  • Since API version 11, it is recommended that you configure both textOverflow and wordBreak to control truncation behavior. For details, see Example 4.

When TextOverflowOptions is set to TextOverflow.MARQUEE:

  • Text scrolls horizontally within a single line.

  • maxLines andcopyOption are ignored.

  • The clip attribute of the Text component defaults to true.

  • CustomSpan is not supported in marquee mode.

  • Behavior of textAlign: If the text does not scroll, textAlign applies; if the text scrolls, textAlign is ignored.

  • Since API version 12, TextOverflow.MARQUEE is available for the ImageSpan component, where the text and images are allowed to scroll within a single line.

Widget capability: This API can be used in ArkTS widgets since API version 9.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
options TextOverflowOptions Yes Display mode when the text is too long.

textSelectable12+

textSelectable(mode: TextSelectableMode)

Sets whether the text is selectable and focusable.

This attribute must be used in conjunction with copyOption.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
mode TextSelectableMode Yes Whether the text is selectable and focusable.
Default value: TextSelectableMode.SELECTABLE_UNFOCUSABLE

textShadow10+

textShadow(value: ShadowOptions | Array<ShadowOptions>)

Sets the text shadow.

Intelligent color extraction is not supported for the type, fill, and color fields of the ShadowOptions object.

Since API version 11, this API supports input parameters in an array to implement multiple text shadows.

Widget capability: This API can be used in ArkTS widgets since API version 10.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value ShadowOptions |  Array<ShadowOptions>11+ Yes Text shadow.

textVerticalAlign20+

textVerticalAlign(textVerticalAlign: Optional<TextVerticalAlign>)

Sets the vertical alignment of the text.

NOTE

  • When this API and halfLeading are both set, halfLeading does not take effect.
  • The effect of this attribute is noticeable only when the same font size is used in a paragraph and lineHeight is set, or when different font sizes are mixed in a paragraph. Otherwise, the effect is the same regardless of whether this attribute is set or which enum value is used. The SuperscriptStyle in TextStyle takes effect only when the value of TextVerticalAlign is set to TextVerticalAlign.BASELINE. In other vertical alignment modes, the superscript and subscript texts are displayed in the same way as the normal text.

Atomic service API: This API can be used in atomic services since API version 20.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
textVerticalAlign Optional<TextVerticalAlign> Yes Vertical alignment of the text.
Default value: TextVerticalAlign.BASELINE

wordBreak11+

wordBreak(value: WordBreak)

Sets the word break rule.

By default, when wordBreak is not called or is set to WordBreak.BREAK_WORD, text is broken by word. (for example, English text is broken at word boundaries).

To break text by character, with the excess part displayed as an ellipsis (...), use WordBreak.BREAK_ALL in combination with {overflow: TextOverflow.Ellipsis} and maxLines.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value WordBreak Yes Word break rule.
Default value: WordBreak.BREAK_WORD

TextSpanType11+

Provides the span type information.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Value Description
TEXT 0 Text span.
Atomic service API: This API can be used in atomic services since API version 12.
IMAGE 1 Image span.
Atomic service API: This API can be used in atomic services since API version 12.
MIXED 2 Mixed span, which contains both text and imagery.
Atomic service API: This API can be used in atomic services since API version 12.
DEFAULT15+ 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.
Atomic service API: This API can be used in atomic services since API version 15.

NOTE

The system follows the priority order below when determining the menu type to display during text interactions:

  1. Check whether a menu is registered for TextSpanType.TEXT and TextResponseType.LONG_PRESS.
  2. Check whether a menu is registered for TextSpanType.TEXT and TextResponseType.DEFAULT.
  3. Check whether a menu is registered for TextSpanType.DEFAULT and TextResponseType.LONG_PRESS.
  4. Check whether a menu is registered for TextSpanType.DEFAULT and TextResponseType.DEFAULT.

TextResponseType11+

Response type of the menu.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Value Description
RIGHT_CLICK 0 The menu is displayed when the component is right-clicked.
Atomic service API: This API can be used in atomic services since API version 12.
LONG_PRESS 1 The menu is displayed when the component is long-pressed.
Atomic service API: This API can be used in atomic services since API version 12.
SELECT 2 The menu is displayed when the component is selected.
Atomic service API: This API can be used in atomic services since API version 12.
DEFAULT15+ 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, mouse selection, and selection API calls.
Atomic service API: This API can be used in atomic services since API version 15.

NOTE

The system follows the priority order below when determining the menu type to display during text interactions:

  1. Check whether a menu is registered for TextSpanType.TEXT and TextResponseType.LONG_PRESS.
  2. Check whether a menu is registered for TextSpanType.TEXT and TextResponseType.DEFAULT.
  3. Check whether a menu is registered for TextSpanType.DEFAULT and TextResponseType.LONG_PRESS.
  4. Check whether a menu is registered for TextSpanType.DEFAULT and TextResponseType.DEFAULT.

TextOverflowOptions18+

Defines the configuration object for text overflow behavior.

NOTE

To standardize anonymous object definitions, the element definitions here have been revised in API version 18. While historical version information is preserved for anonymous objects, there may be cases where the outer element's @since version number is higher than inner elements'. This does not affect interface usability.

Widget capability: This API can be used in ArkTS widgets since API version 18.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Type Read-Only Optional Description
overflow7+ TextOverflow No No Display mode of overflowing text.
Default value: TextOverflow.Clip
Widget capability: This API can be used in ArkTS widgets since API version 9.
Atomic service API: This API can be used in atomic services since API version 11.

Events

In addition to the universal events, the following events are supported.

onCopy11+

onCopy(callback:(value: string) => void)

Called when data is copied to the pasteboard, which is displayed when the text box is long pressed. Currently, only text can be copied.

Atomic service API: This API can be used in atomic services since API version 11.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value string Yes Text that is copied.

onWillCopy

onWillCopy(callback: Callback<string, boolean>)

Called before the copy operation is performed.

Since: 26.0.0

Model restriction: This API can be used only in the stage model.

Atomic service API: This API can be used in atomic services since API version 26.0.0.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
callback Callback<string, boolean> Yes The string type indicates the text to be copied.
The boolean type indicates whether the text can be copied. The value true means yes and false means no.

onTextSelectionChange11+

onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)

Called when the text selection position changes.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
selectionStart number Yes Start position of the selected text.
selectionEnd number Yes End position of the selected text.

onMarqueeStateChange18+

onMarqueeStateChange(callback: Callback<MarqueeState>)

Called when the marquee animation reaches the specified state.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
callback Callback<MarqueeState> Yes Callback that receives a MarqueeState enum value, which indicates the current state of the marquee animation.

TextOptions11+

Describes the initialization options of the Text component.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Type Read-Only Optional Description
controller TextController No No Text controller.

TextController11+

Defines the controller of the Text component.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Objects to Import

controller: TextController = new TextController()

closeSelectionMenu11+

closeSelectionMenu(): void

Closes the custom or default text selection menu.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

setStyledString12+

setStyledString(value: StyledString): void

Binds to or updates the specified styled string.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value StyledString Yes Styled string.
NOTE
The child class MutableStyledString of StyledString can also serve as the argument.

NOTE
Each call to setStyledString replaces the previously bound styled string. It does not append or merge content.

When bound using a controller, the styled string takes effect only after layout completion. When using setStyledString alongside measure, you must wait for layout completion using the layout callback before applying the styled string.

In API version 14 and earlier, calling setStyledString on a TextController object before it is bound to a Text component has no effect.

Since API version 15, the TextController object retains the styled string. Once it is bound to a Text component, the stored content is automatically applied and rendered.

This behavior difference is especially relevant when you set styled strings in the aboutToAppear lifecycle callback. It is ineffective in API version 14 and earlier, but works as expected since API version 15. For best practices, see Creating and Applying a StyledString or MutableStyledString Object.

getLayoutManager12+

getLayoutManager(): LayoutManager

Obtains the LayoutManager object.

Atomic service API: This API can be used in atomic services since API version 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Return value

Type Description
LayoutManager LayoutManager object.

setTextSelection23+

setTextSelection(selectionStart: number | undefined, selectionEnd: number | undefined, options?: SelectionOptions): void

Sets the text selection area, which will be highlighted.

NOTE

If copyOption is set to CopyOptions.None, the setting of setTextSelection does not take effect.

If textOverflow is set to TextOverflow.MARQUEE, the setting of setTextSelection does not take effect.

If 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.

If the selection range falls within a truncated or invisible area, selection is ignored. When truncation is disabled, selection can extend beyond the parent component's bounds.

On PC or 2-in-1 devices, calling setTextSelection does not show the menu even if options is set to MenuPolicy.SHOW.

When an emoji is truncated by the selection range, the emoji is selected if its start position is within the specified text selection range.

Atomic service API: This API can be used in atomic services since API version 23.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
selectionStart number | undefined Yes Start position of the text selection range.
Value range: [0, +∞). Negative values and undefined are treated as 0.
selectionEnd number | undefined Yes End position of the text selection range.
Value range: [0, +∞). Negative values and undefined are treated as 0.
options SelectionOptions No Configuration options for text selection.
Default value: MenuPolicy.DEFAULT in SelectionOptions

TextMarqueeOptions18+

Describes the initialization options of the Marquee component.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Type Read-Only Optional Description
start boolean No No Whether to start the marquee.
true: Start the marquee. false: Do not start the marquee.
Atomic service API: This API can be used in atomic services since API version 18.
step number No Yes Step length of the scrolling animation text.
Default value: 4.0 (in vp)
Atomic service API: This API can be used in atomic services since API version 18.
spacing23+ LengthMetrics No Yes Spacing between two marquee rounds. If the unit of LengthMetrics is PERCENT, the current setting does not take effect and the default value is used.
Default value: 48.0vp
Atomic service API: This API can be used in atomic services since API version 23.
loop number No Yes Number of times the marquee will scroll. If the value is less than or equal to 0, the marquee will scroll continuously.
Default value: -1
Atomic service API: This API can be used in atomic services since API version 18.
fromStart boolean No Yes Whether the text scrolls from the start.
true to scroll from the start, false to scroll in reverse.
Default value: true
Atomic service API: This API can be used in atomic services since API version 18.
delay number No Yes Time interval between scroll movements.
Default value: 0
Unit: millisecond
Atomic service API: This API can be used in atomic services since API version 18.
fadeout boolean No Yes Whether to apply a fade-out effect when the text is too long.
true to apply a fade-out effect when the text is too long, false otherwise.
When this parameter is set to true: if the text content exceeds the display range, a fade-out effect is applied to the edges of the partially visible text; if text is partially visible at both ends, the fade-out effect is applied to both ends. The clip attribute is automatically locked to true and cannot be set to false.
Default value: false
Atomic service API: This API can be used in atomic services since API version 18.
marqueeStartPolicy MarqueeStartPolicy No Yes Policy for starting the marquee. This attribute takes effect only when start is set to true.
Default value: MarqueeStartPolicy.DEFAULT
Atomic service API: This API can be used in atomic services since API version 18.
marqueeUpdatePolicy23+ MarqueeUpdatePolicy No Yes Scrolling policy of the marquee after its attributes are updated.
This attribute takes effect when the marquee is in the playing state and the text width exceeds the width of the marquee component.
Default value: MarqueeUpdatePolicy.DEFAULT
Atomic service API: This API can be used in atomic services since API version 23.

MarqueeStartPolicy18+

Enumerates the marquee scrolling modes.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Value Description
DEFAULT 0 The marquee scrolls continuously. Default value.
ON_FOCUS 1 The marquee starts scrolling when it has focus or when the mouse hovers over it.

MarqueeUpdatePolicy23+

Sets the scrolling policy of the marquee after its attributes are updated.

Atomic service API: This API can be used in atomic services since API version 23.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Value Description
DEFAULT 0 Restarts the marquee from the start position after the attributes of the marquee component are updated.
PRESERVE_POSITION 1 Resumes the marquee from the current position after the attributes of the marquee component are updated.

MarqueeState18+

Enumerates the return values of the marquee state callback.

Atomic service API: This API can be used in atomic services since API version 18.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Value Description
START 0 The marquee starts scrolling.
BOUNCE 1 The marquee completes one scroll movement. If the number of loops is not 1, this value will be returned multiple times.
FINISH 2 All loops of the marquee are completed.

Example

Example 1: Setting the Text Layout

This example showcases various text layouts using the following attributes: textAlign, lineHeight, baselineOffset, and halfLeading (available since API version 12).

// xxx.ets
@Extend(Text)
function style(TextAlign: TextAlign) {
  .textAlign(TextAlign)
  .fontSize(12)
  .border({ width: 1 })
  .padding(10)
  .width('100%')
  .margin(5)
}

@Entry
@Component
struct TextExample1 {
  @State changeTextAlignIndex: number = 0;
  @State changeDecorationIndex: number = 0;
  @State textAlign: TextAlign[] = [TextAlign.Start, TextAlign.Center, TextAlign.End];
  @State textAlignStr: string[] = ['Start', 'Center', 'End'];

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
      // Set horizontal alignment for text.
      // Single-line text
      Text('textAlign').fontSize(9).fontColor(0xCCCCCC)
      Text(`TextAlign set to ${this.textAlignStr[this.changeTextAlignIndex]}.`)
        .style(this.textAlign[this.changeTextAlignIndex])

      // Multi-line text
      Text(`This is the text content with textAlign set to ${this.textAlignStr[this.changeTextAlignIndex]}.`)
        .style(this.textAlign[this.changeTextAlignIndex])
        .margin(5)

      Row() {
        Button('TextAlign value: ' + this.textAlignStr[this.changeTextAlignIndex]).onClick(() => {
          this.changeTextAlignIndex++;
          if (this.changeTextAlignIndex > (this.textAlignStr.length - 1)) {
            this.changeTextAlignIndex = 0;
          }
        })
      }.justifyContent(FlexAlign.Center).width('100%')

      // Set the text line height.
      Text('lineHeight').fontSize(9).fontColor(0xCCCCCC)
      Text('This is the text with the line height set. This is the text with the line height set.')
        .style(TextAlign.Start)
      Text('This is the text with the line height set. This is the text with the line height set.')
        .style(TextAlign.Start)
        .lineHeight(20)

      // Set the text baseline offset.
      Text('baselineOffset').fontSize(9).fontColor(0xCCCCCC)
      Text('This is the text content with baselineOffset 0.')
        .baselineOffset(0)
        .style(TextAlign.Start)
      Text('This is the text content with baselineOffset 30.')
        .baselineOffset(30)
        .style(TextAlign.Start)
      Text('This is the text content with baselineOffset -20.')
        .baselineOffset(-20)
        .style(TextAlign.Start)

      // Set whether half leading is enabled.
      Text('halfLeading').fontSize(9).fontColor(0xCCCCCC)
      Text("This is the text with the halfLeading set.")
        .lineHeight(60)
        .halfLeading(true)
        .style(TextAlign.Start)
      Text("This is the text without the halfLeading set.")
        .lineHeight(60)
        .halfLeading(false)
        .style(TextAlign.Start)
    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
  }
}

textExp1

Example 2: Setting the Text Style

This example showcases various text styles using the following attributes: decoration, letterSpacing, textCase, fontFamily, textShadow (available since API version 10), fontStyle, textIndent (available since API version 10), and fontWeight (available since API version 12, supporting variable font weight setting options).

// xxx.ets
@Extend(Text)
function style() {
  .font({ size: 12 }, { enableVariableFontWeight: true })
  .border({ width: 1 })
  .padding(10)
  .width('100%')
  .margin(5)
}

@Entry
@Component
struct TextExample2 {
  @State changeDecorationIndex: number = 0;
  @State textDecorationType: TextDecorationType[] =
    [TextDecorationType.LineThrough, TextDecorationType.Overline, TextDecorationType.Underline];
  @State textDecorationTypeStr: string[] = ['LineThrough', 'Overline', 'Underline'];
  @State textDecorationStyle: TextDecorationStyle[] =
    [TextDecorationStyle.SOLID, TextDecorationStyle.DOTTED, TextDecorationStyle.WAVY];
  @State textDecorationStyleStr: string[] = ['SOLID', 'DOTTED', 'WAVY'];

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
      Text('decoration').fontSize(9).fontColor(0xCCCCCC)
      Text('This is the text content with the decoration set to LineThrough and the color set to Red.')
        .decoration({
          type: this.textDecorationType[this.changeDecorationIndex],
          color: Color.Red,
          style: this.textDecorationStyle[this.changeDecorationIndex]
        })
        .style()
        .margin(5)

      Row() {
        Button('decoration type: ' + this.textDecorationTypeStr[this.changeDecorationIndex] + ' & ' +
        this.textDecorationStyleStr[this.changeDecorationIndex]).onClick(() => {
          this.changeDecorationIndex++;
          if (this.changeDecorationIndex > (this.textDecorationTypeStr.length - 1)) {
            this.changeDecorationIndex = 0;
          }
        })
      }.justifyContent(FlexAlign.Center).width('100%')

      // Set the letter spacing.
      Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC)
      Text('This is the text content with letterSpacing 0.')
        .letterSpacing(0)
        .style()
      Text('This is the text content with letterSpacing 3.')
        .letterSpacing(3)
        .style()
      Text('This is the text content with letterSpacing -1.')
        .letterSpacing(-1)
        .style()

      Text('textCase').fontSize(9).fontColor(0xCCCCCC)
      Text('This is the text content with textCase set to Normal.')
        .textCase(TextCase.Normal)
        .style()
      // Display the text in lowercase.
      Text('This is the text content with textCase set to LowerCase.')
        .textCase(TextCase.LowerCase)
        .style()
      // Display the text in uppercase.
      Text('This is the text content with textCase set to UpperCase.')
        .textCase(TextCase.UpperCase)
        .style()

      Text('fontFamily').fontSize(9).fontColor(0xCCCCCC)
      // Set the font family.
      Text('This is the text content with fontFamily')
        .style()
        .fontFamily('HarmonyOS Sans')

      Text('textShadow').fontSize(9).fontColor(0xCCCCCC)
      // Set the text shadow.
      Text('textShadow')
        .style()
        .textAlign(TextAlign.Center)
        .fontSize(40)
        .textShadow({
          radius: 10,
          color: Color.Black,
          offsetX: 0,
          offsetY: 0
        })

      Text('fontStyle').fontSize(9).fontColor(0xCCCCCC)
      // Set the font style.
      Text('This is the text content with fontStyle set to Italic')
        .style()
        .fontStyle(FontStyle.Italic)
      Text('This is the text content with fontStyle set to Normal')
        .style()
        .fontStyle(FontStyle.Normal)

      Text('textIndent').fontSize(9).fontColor(0xCCCCCC)
      // Set the text indentation.
      Text('This is the text content with textIndent 30')
        .style()
        .textIndent(30)

      Text('fontWeight').fontSize(9).fontColor(0xCCCCCC)
      // Set the font weight.
      Text('This is the text content with fontWeight 800')
        .style()
        .fontWeight('800', { enableVariableFontWeight: true })

    }.width('100%').padding({ left: 35, right: 35 })
  }
}

textExp2

Example 3: Setting Ellipsis for Overflow Text

This example demonstrates how to clip text with an ellipsis and adjust its position using the maxLines, textOverflow, and ellipsisMode attributes. The MULTILINE_START and MULTILINE_CENTER enums are used to implement the effect of displaying ellipsis at the beginning and in the middle of a line for single-line and multi-line text. In addition, you can set the options for the marquee effect using marqueeOptions and the onMarqueeStateChange callback that is invoked when the marquee animation reaches the specified state.

The ellipsisMode attribute is added to set the display mode for overflow text since API version 11.

The marqueeOptions attribute is added to set the marquee effect options and the onMarqueeStateChange callback is also added since API version 18.

The MULTILINE_START and MULTILINE_CENTER enums are added to the EllipsisMode attribute since API version 24.

// xxx.ets
import { LengthMetrics } from '@kit.ArkUI';

@Extend(Text)
function style() {
  .textAlign(TextAlign.Center)
  .fontSize(15)
  .border({ width: 1 })
  .padding(10)
  .width('100%')
  .margin(5)
}

@Entry
@Component
struct TextExample3 {
  @State text: string =
    'The text component is used to display a piece of textual information.' +
      'Support universal attributes and universal text attributes.' +
      'The text component is used to display a piece of textual information.' +
      'Support universal attributes and universal text attributes.';
  @State ellipsisModeIndex: number = 0;
  @State ellipsisMode: EllipsisMode[] =
    [EllipsisMode.START, EllipsisMode.CENTER, EllipsisMode.END, EllipsisMode.MULTILINE_START,
      EllipsisMode.MULTILINE_CENTER]; // MULTILINE_START and MULTILINE_CENTER are added since API version 24.
  @State ellipsisModeStr: string[] = ['START', 'CENTER', 'END', 'MULTILINE_START',
    'MULTILINE_CENTER'];

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
      // Set the display mode when the text is too long.
      Text('TextOverflow+maxLines').fontSize(12).fontColor(Color.Black)
      // Clip the text when the value of maxLines is exceeded.
      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.')
        .textOverflow({ overflow: TextOverflow.Clip })
        .maxLines(1)
        .style()

      // Show an ellipsis when the value of maxLines is exceeded.
      Text('This is set textOverflow to Ellipsis text content This is set textOverflow to Ellipsis text content.')
        .textOverflow({ overflow: TextOverflow.Ellipsis })
        .maxLines(1)
        .style()

      Text('marquee').fontSize(12).fontColor(Color.Black)
      // Set the text to continuously scroll when text overflow occurs.
      Text('This is the text with the text overflow set marquee')
        .textOverflow({ overflow: TextOverflow.MARQUEE })
        .style()
        .marqueeOptions({
          start: true,
          fromStart: true,
          step: 6,
          spacing: LengthMetrics.vp(48), // Added since API version 23.
          loop: -1,
          delay: 0,
          fadeout: false,
          marqueeStartPolicy: MarqueeStartPolicy.DEFAULT,
          marqueeUpdatePolicy: MarqueeUpdatePolicy.DEFAULT // Added since API version 23.
        })
        .onMarqueeStateChange((state: MarqueeState) => {
          if (state == MarqueeState.START) {
            // "Received state: START";
          } else if (state == MarqueeState.BOUNCE) {
            // "Received state: BOUNCE";
          } else if (state == MarqueeState.FINISH) {
            // "Received state: FINISH";
          }
        })

      // Set the position of the ellipsis (...) for text truncation.
      Text('ellipsisMode (single-line text)').fontSize(12).fontColor(Color.Black)
      Text(this.text)
        .textOverflow({ overflow: TextOverflow.Ellipsis })
        .ellipsisMode(this.ellipsisMode[this.ellipsisModeIndex])
        .maxLines(1)
        .style()
      Text('ellipsisMode (multi-line text)').fontSize(12).fontColor(Color.Black)
      Text(this.text)
        .textOverflow({ overflow: TextOverflow.Ellipsis })
        .ellipsisMode(this.ellipsisMode[this.ellipsisModeIndex])
        .maxLines(3)
        .style()

      Row() {
        Button('Ellipsis Position: ' + this.ellipsisModeStr[this.ellipsisModeIndex]).onClick(() => {
          this.ellipsisModeIndex++;
          if (this.ellipsisModeIndex > (this.ellipsisModeStr.length - 1)) {
            this.ellipsisModeIndex = 0;
          }
        })
      }
    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
  }
}

Example 4: Setting Text Wrapping and Line Breaking

This example demonstrates text behavior under different line breaking and wrapping rules, including overflow behavior, using the wordBreak (available since API version 11), lineBreakStrategy (available since API version 12), and clip attributes.

// xxx.ets
@Extend(Text)
function style() {
  .fontSize(12)
  .border({ width: 1 })
  .padding(10)
  .width('100%')
  .margin(5)
}

@Entry
@Component
struct TextExample4 {
  @State text: string =
    'The text component is used to display a piece of textual information.Support universal attributes and universal text attributes.';
  @State text2: string =
    "They can be classified as built-in components–those directly provided by the ArkUI framework and custom components – those defined by developers" +
      "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," +
      "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.";
  @State textClip: boolean = false;
  @State wordBreakIndex: number = 0;
  @State wordBreak: WordBreak[] = [WordBreak.NORMAL, WordBreak.BREAK_ALL, WordBreak.BREAK_WORD];
  @State wordBreakStr: string[] = ['NORMAL', 'BREAK_ALL', 'BREAK_WORD'];
  @State lineBreakStrategyIndex: number = 0;
  @State lineBreakStrategy: LineBreakStrategy[] =
    [LineBreakStrategy.GREEDY, LineBreakStrategy.HIGH_QUALITY, LineBreakStrategy.BALANCED];
  @State lineBreakStrategyStr: string[] = ['GREEDY', 'HIGH_QUALITY', 'BALANCED'];

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
      Text('wordBreak').fontSize(9).fontColor(0xCCCCCC)
      // Set the word break rule.
      Text(this.text)
        .maxLines(2)
        .textOverflow({ overflow: TextOverflow.Ellipsis })
        .wordBreak(this.wordBreak[this.wordBreakIndex])
        .style()

      Row() {
        Button('wordBreak Value: ' + this.wordBreakStr[this.wordBreakIndex]).onClick(() => {
          this.wordBreakIndex++;
          if (this.wordBreakIndex > (this.wordBreakStr.length - 1)) {
            this.wordBreakIndex = 0;
          }
        })
      }

      Text('clip').fontSize(9).fontColor(0xCCCCCC)
      // Set whether text is clipped when it exceeds the length.
      Text('This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.')
        .wordBreak(WordBreak.NORMAL)
        .maxLines(2)
        .clip(this.textClip)
        .style()
      Row() {
        Button('Clip Mode: ' + this.textClip).onClick(() => {
          this.textClip = !this.textClip;
        })
      }

      Text('lineBreakStrategy').fontSize(9).fontColor(0xCCCCCC)
      // Set the text line breaking rule.
      Text(this.text2)
        .lineBreakStrategy(this.lineBreakStrategy[this.lineBreakStrategyIndex])
        .style()
      Row() {
        Button('lineBreakStrategy Value: ' + this.lineBreakStrategyStr[this.lineBreakStrategyIndex]).onClick(() => {
          this.lineBreakStrategyIndex++;
          if (this.lineBreakStrategyIndex > (this.lineBreakStrategyStr.length - 1)) {
            this.lineBreakStrategyIndex = 0;
          }
        })
      }
    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
  }
}

Example 5: Setting Text Selection and Copy

This example demonstrates how to set text selection, invoke a copy callback, make text selection draggable, modify the selection handle and background colors, and intercept a system copy operation using the following APIs: selection (available since API version 11), onCopy (available since API version 11), draggable (available since API version 9), caretColor (available since API version 14), selectedBackgroundColor (available since API version 14), and onWillCopy.

The onWillCopy API is added since API version 26.0.0.

// xxx.ets
@Entry
@Component
struct TextExample5 {
  @State onCopy: string = '';
  @State text: string =
    'This is set selection to Selection text content This is set selection to Selection text content.';
  @State start: number = 0;
  @State end: number = 20;

  build() {
    Column() {
      Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Start }) {
        Text(this.text)
          .fontSize(12)
          .border({ width: 1 })
          .lineHeight(20)
          .margin(30)
          .copyOption(CopyOptions.InApp)
          .selection(this.start, this.end)
          .onCopy((value: string) => {
            this.onCopy = value;
          })
          // onWillCopy is supported since API version 26.0.0.
          .onWillCopy((value: string) => {
            this.onCopy = value;
            return false;
          })
          .draggable(true)
          .caretColor(Color.Red)
          .selectedBackgroundColor(Color.Grey)
          .enableHapticFeedback(true)
        Button('Set text selection')
          .onClick(() => {
            // Change the start point and end point of the text selection.
            this.start = 10;
            this.end = 30;
          })
        Text(this.onCopy).fontSize(12).margin(10).key('copy')
      }.height(600).width(335).padding({ left: 35, right: 35, top: 35 })
    }.width('100%')
  }
}

Example 6: Setting Text Adaptation and Font Scale Factor Limits

This example demonstrates text adaptive behavior using the heightAdaptivePolicy attribute (available since API version 10), and shows how to configure font scaling limits through minFontScale and maxFontScale (both available since API version 12).

// xxx.ets
@Extend(Text)
function style(HeightAdaptivePolicy: TextHeightAdaptivePolicy) {
  .width('80%')
  .height(90)
  .borderWidth(1)
  .minFontSize(10)
  .maxFontSize(30)
  .maxLines(2)
  .margin(5)
  .textOverflow({ overflow: TextOverflow.Ellipsis })
  .heightAdaptivePolicy(HeightAdaptivePolicy)
}

@Entry
@Component
struct TextExample6 {
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center }) {
      // Set how the adaptive height is determined for the text.
      Text('heightAdaptivePolicy').fontSize(9).fontColor(0xCCCCCC)
      Text('This is the text with the height adaptive policy set.')
        .style(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
      Text('This is the text with the height adaptive policy set.')
        .style(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST)
      Text('This is the text with the height adaptive policy set.')
        .style(TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST)

      Text('fontScale').fontSize(9).fontColor(0xCCCCCC)
      Text('This is the text content with minFontScale set to 1 and maxFontScale set to 1.2')
        .style(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
        .minFontScale(1)
        .maxFontScale(1.2)
    }.height(600).width('100%').padding({ left: 35, right: 35, top: 35 })
  }
}

textHeightAdaptivePolicy

Example 7: Setting Text Recognition

This example implements text recognition capabilities using the enableDataDetector and dataDetectorConfig APIs, available since API version 11. When enableDataDetector is set to true and dataDetectorConfig is not specified, the system detects all entity types, applies the blue font color to these entities, and adds blue underlines to them.

// xxx.ets
@Entry
@Component
struct TextExample7 {
  @State phoneNumber: string = '(86) (755) ********';
  @State url: string = 'www.********.com';
  @State email: string = '***@example.com';
  @State address: string = 'XX (province) XX (city) XX (county) XXXX';
  @State datetime: string = 'YYYY-MM-DD HH:mm';
  @State enableDataDetector: boolean = true;
  @State types: TextDataDetectorType[] = [];

  build() {
    Row() {
      Column() {
        Text(
          'Phone number: ' + this.phoneNumber + '\n' +
            'URL: ' + this.url + '\n' +
            'Email: ' + this.email + '\n' +
            'Address: ' + this.address + '\n' +
            'Time: ' + this.datetime
        )
          .fontSize(16)
          .copyOption(CopyOptions.InApp)
          .enableDataDetector(this.enableDataDetector)
          .dataDetectorConfig({
            types: this.types, onDetectResultUpdate: (result: string) => {
            }
          })
          .textAlign(TextAlign.Center)
          .borderWidth(1)
          .padding(10)
          .width('100%')
        Text(
          'Phone number: ' + this.phoneNumber + '\n' +
            'Time: ' + this.datetime
        )
          .fontSize(16)
          .copyOption(CopyOptions.LocalDevice)
          .textAlign(TextAlign.Center)
          .borderWidth(1)
          .padding(10)
          .width('100%')
        TextInput({ text: 'TextInput content' })
          .copyOption(CopyOptions.LocalDevice)
        TextArea({ text: 'TextArea content' })
          .copyOption(CopyOptions.LocalDevice)
        Search()
          .copyOption(CopyOptions.LocalDevice)
      }
      .width('100%')
      // Use TapGesture in parallelGesture to mimic the effect of a bubbling event,
      // allowing a click on the Text component area to trigger the Column's click event.
      .parallelGesture(TapGesture().onAction((event: GestureEvent) => {
        console.info('test column onClick timestamp:' + event.timestamp);
      }), GestureMask.Normal)
    }
    .height('100%')
  }
}

Example 8: Binding Text to a Custom Menu

This example demonstrates custom menu binding for text using the following APIs, available since API version 11: bindSelectionMenu, onTextSelectionChange, and closeSelectionMenu.

// xxx.ets
@Entry
@Component
struct TextExample8 {
  controller: TextController = new TextController();
  options: TextOptions = { controller: this.controller };

  build() {
    Column() {
      Column() {
        Text(undefined, this.options) {
          Span('Hello World')
          // Replace $r('app.media.startIcon') with the image resource file you use.
          ImageSpan($r('app.media.startIcon'))
            .width(50)
            .height(50)
            .objectFit(ImageFit.Fill)
            .verticalAlign(ImageSpanAlignment.CENTER)
        }
        .copyOption(CopyOptions.InApp)
        .bindSelectionMenu(TextSpanType.IMAGE, this.LongPressImageCustomMenu, TextResponseType.LONG_PRESS, {
          onDisappear: () => {
            console.info(`Callback invoked when the custom menu disappears`);
          },
          onAppear: () => {
            console.info(`Callback invoked when the custom menu appears`);
          },
          onMenuShow: () => {
            console.info(`Callback invoked when the custom menu is shown`);
          },
          onMenuHide: () => {
            console.info(`Callback invoked when the custom menu is hidden`);
          }
        })
        .bindSelectionMenu(TextSpanType.TEXT, this.RightClickTextCustomMenu, TextResponseType.RIGHT_CLICK)
        .bindSelectionMenu(TextSpanType.MIXED, this.SelectMixCustomMenu, TextResponseType.SELECT)
        .onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
          console.info(`Callback invoked when the text selection changes, selectionStart: ${selectionStart}, selectionEnd: ${selectionEnd}`);
        })
        .borderWidth(1)
        .borderColor(Color.Red)
        .width(200)
        .height(100)
      }
      .width('100%')
      .backgroundColor(Color.White)
      .alignItems(HorizontalAlign.Start)
      .padding(25)
    }
    .height('100%')
  }

  @Builder
  RightClickTextCustomMenu() {
    Column() {
      Menu() {
        MenuItemGroup() {
          // Replace $r('app.media.startIcon') with the image resource file you use.
          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Right Click Menu 1", labelInfo: "" })
            .onClick((event) => {
              this.controller.closeSelectionMenu();
            })
          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Right Click Menu 2", labelInfo: "" })
          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Right Click Menu 3", labelInfo: "" })
        }
      }
      .MenuStyles()
    }
  }

  @Builder
  LongPressImageCustomMenu() {
    Column() {
      Menu() {
        MenuItemGroup() {
          // Replace $r('app.media.startIcon') with the image resource file you use.
          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Long Press Image Menu 1", labelInfo: "" })
            .onClick((event) => {
              this.controller.closeSelectionMenu();
            })
          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Long Press Image Menu 2", labelInfo: "" })
          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Long Press Image Menu 3", labelInfo: "" })
        }
      }
      .MenuStyles()
    }
  }

  @Builder
  SelectMixCustomMenu() {
    Column() {
      Menu() {
        MenuItemGroup() {
          // Replace $r('app.media.startIcon') with the image resource file you use.
          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Select Mixed Menu 1", labelInfo: "" })
            .onClick((event) => {
              this.controller.closeSelectionMenu();
            })
          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Select Mixed Menu 2", labelInfo: "" })
          MenuItem({ startIcon: $r('app.media.startIcon'), content: "Select Mixed Menu 3", labelInfo: "" })
        }
      }
      .MenuStyles()
    }
  }
}

@Extend(Menu)
function MenuStyles() {
  .radius($r('sys.float.ohos_id_corner_radius_card'))
  .clip(true)
  .backgroundColor('#F0F0F0')
}

Example 9: Setting Text Features and Line Spacing

This example demonstrates text feature and line spacing effects using the fontFeature and lineSpacing APIs, available since API version 12. The onlyBetweenLines property in LineSpacingOptions (available since API version 20) controls whether line spacing applies only between lines.

// xxx.ets
import { LengthMetrics } from '@kit.ArkUI';

@Extend(Text)
function style() {
  .fontSize(12)
  .border({ width: 1 })
  .width('100%')
}

@Entry
@Component
struct TextExample9 {
  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
      Text('lineSpacing').fontSize(9).fontColor(0xCCCCCC)
      // Set the line spacing.
      Text('This is a context with no lineSpacing set.')
        .lineSpacing(undefined)
        .style()
      Text('This is a context with lineSpacing set to 20_px.')
        .lineSpacing(LengthMetrics.px(20))
        .style()
      Text('This is the context with lineSpacing set to 20_vp.')
        .lineSpacing(LengthMetrics.vp(20))
        .style()
      Text('This is the context with lineSpacing set to 20_fp.')
        .lineSpacing(LengthMetrics.fp(20))
        .style()
      Text('This is the context with lineSpacing set to 20_lpx.')
        .lineSpacing(LengthMetrics.lpx(20))
        .style()
      Text('This is the context with lineSpacing set to 100%.')
        .lineSpacing(LengthMetrics.percent(1))
        .style()
      Text('The line spacing of this context is set to 20_px, and the spacing is effective only between the lines.')
        .lineSpacing(LengthMetrics.px(20), { onlyBetweenLines: true })
        .style()

      Text('fontFeature').fontSize(9).fontColor(0xCCCCCC)
      // Set text features.
      Text('This is frac on : 1/2 2/3 3/4')
        .fontFeature("\"frac\" on")
        .style()
      Text('This is frac off: 1/2 2/3 3/4')
        .fontFeature("\"frac\" off")
        .style()
    }.height(300).width(350).padding({ left: 35, right: 35, top: 35 })
  }
}

Example 10: Obtaining Text Information

This example shows how to use the getLayoutManager API (available since API version 12) to access the text's layout manager for obtaining text information. In addition, it uses the getRectsForRange API within LayoutManager (available since API version 14) to obtain drawing area information for characters or placeholders within any specified text range, given specific width and height constraints.

// xxx.ets
import { text } from '@kit.ArkGraphics2D';

@Entry
@Component
struct TextExample10 {
  @State lineCount: string = "";
  @State glyphPositionAtCoordinate: string = "";
  @State lineMetrics: string = "";
  @State rectsForRangeStr: string = "";
  controller: TextController = new TextController();
  @State textStr: string =
    'Hello World!';

  build() {
    Scroll() {
      Column() {
        Text('Use getLayoutManager to get layout information')
          .fontSize(15)
          .fontColor(0xCCCCCC)
          .width('90%')
          .padding(10)
        Text(this.textStr, { controller: this.controller })
          .fontSize(25)
          .borderWidth(1)
          .onAreaChange(() => {
            let layoutManager: LayoutManager = this.controller.getLayoutManager();
            this.lineCount = "LineCount: " + layoutManager.getLineCount();
          })

        Text('LineCount').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
        Text(this.lineCount)

        Text('GlyphPositionAtCoordinate').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
        Button("Relative Component Coordinate [150, 50]")
          .onClick(() => {
            let layoutManager: LayoutManager = this.controller.getLayoutManager();
            let position: PositionWithAffinity = layoutManager.getGlyphPositionAtCoordinate(150, 50);
            this.glyphPositionAtCoordinate =
              "Relative component coordinate [150, 50] glyphPositionAtCoordinate position: " + position.position + " affinity: " +
              position.affinity;
          })
          .margin({ bottom: 20, top: 10 })
        Text(this.glyphPositionAtCoordinate)

        Text('LineMetrics').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
        Button("Line Metrics")
          .onClick(() => {
            let layoutManager: LayoutManager = this.controller.getLayoutManager();
            let lineMetrics: LineMetrics = layoutManager.getLineMetrics(0);
            this.lineMetrics = "lineMetrics is " + JSON.stringify(lineMetrics) + "\n\n";
            let runMetrics = lineMetrics.runMetrics;
            runMetrics.forEach((value, key) => {
              this.lineMetrics += "runMetrics key is " + key + " " + JSON.stringify(value) + "\n\n";
            })
          })
          .margin({ bottom: 20, top: 10 })
        Text(this.lineMetrics)

        Text('getRectsForRange').fontSize(15).fontColor(0xCCCCCC).width('90%').padding(10)
        Button("Drawing Area Info for Characters/Placeholders within Specified Text Range")
          .onClick(() => {
            let layoutManager: LayoutManager = this.controller.getLayoutManager();
            let range: TextRange = { start: 0, end: 1 };
            let rectsForRangeInfo: text.TextBox[] =
              layoutManager.getRectsForRange(range, text.RectWidthStyle.TIGHT, text.RectHeightStyle.TIGHT);
            this.rectsForRangeStr = "getRectsForRange result is " + "\n\n";
            rectsForRangeInfo.forEach((value, key) => {
              this.rectsForRangeStr += "rectsForRange key is " + key + " " + JSON.stringify(value) + "\n\n";
            })
          })
          .margin({ bottom: 20, top: 10 })
        Text(this.rectsForRangeStr)
      }
      .margin({ top: 100, left: 8, right: 8 })
    }
  }
}

textLayoutManager

Example 11: Implementing Keyboard-based Text Selection

This example implements keyboard-based text selection by setting the textSelectable attribute to TextSelectMode.SELECTABLE_FOCUSABLE, available since API version 12.

// xxx.ets
@Entry
@Component
struct TextExample11 {
  @State message: string =
    'TextTextTextTextTextTextTextText' + 'TextTextTextTextTextTextTextTextTextTextTextTextTextTextTextText';

  build() {
    Column() {
      Text(this.message)
        .width(300)
        .height(100)
        .maxLines(5)
        .fontColor(Color.Black)
        .copyOption(CopyOptions.InApp)
        .selection(3, 8)
        .textSelectable(TextSelectableMode.SELECTABLE_FOCUSABLE)
    }.width('100%').margin({ top: 100 })
  }
}

textTextSelectableMode

Example 12: Setting Custom Menu Extensions

This example implements custom menu extension items for text using the editMenuOptions API (available since API version 12), allowing configuration of text content, icons, and callbacks. Menu data can be configured through the onPrepareMenu callback (available since API version 20).

// xxx.ets
@Entry
@Component
struct TextExample12 {
  @State text: string = 'Text editMenuOptions'
  @State endIndex: number = 0;
  onCreateMenu = (menuItems: Array<TextMenuItem>) => {
    // Replace $r('app.media.startIcon') with the image resource file you use.
    let item1: TextMenuItem = {
      content: 'create1',
      icon: $r('app.media.startIcon'),
      id: TextMenuItemId.of('create1'),
    };
    let item2: TextMenuItem = {
      content: 'create2',
      id: TextMenuItemId.of('create2'),
      icon: $r('app.media.startIcon'),
    };
    menuItems.push(item1);
    menuItems.unshift(item2);
    let targetIndex = menuItems.findIndex(item => item.id.equals(TextMenuItemId.askAI));
    if (targetIndex !== -1) {
      menuItems.splice(targetIndex, 1); // Delete an element at the target index.
    }
    targetIndex = menuItems.findIndex(item => item.id.equals(TextMenuItemId.TRANSLATE));
    if (targetIndex !== -1) {
      menuItems.splice(targetIndex, 1);
    }
    return menuItems;
  }
  onMenuItemClick = (menuItem: TextMenuItem, textRange: TextRange) => {
    if (menuItem.id.equals(TextMenuItemId.of("create2"))) {
      console.info("Intercept id: create2 start:" + textRange.start + "; end:" + textRange.end);
      return true;
    }
    if (menuItem.id.equals(TextMenuItemId.of("prepare1"))) {
      console.info("Intercept id: prepare1 start:" + textRange.start + "; end:" + textRange.end);
      return true;
    }
    if (menuItem.id.equals(TextMenuItemId.COPY)) {
      console.info("Intercept COPY start:" + textRange.start + "; end:" + textRange.end);
      return true;
    }
    if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) {
      console.info("Do not intercept SELECT_ALL start:" + textRange.start + "; end:" + textRange.end);
      return false;
    }
    return false;
  }
  // Replace $r('app.media.startIcon') with the image resource file you use.
  onPrepareMenu = (menuItems: Array<TextMenuItem>) => {
    let item1: TextMenuItem = {
      content: 'prepare1_' + this.endIndex,
      icon: $r('app.media.startIcon'),
      id: TextMenuItemId.of('prepare1'),
    };
    menuItems.unshift(item1);
    return menuItems;
  }
  @State editMenuOptions: EditMenuOptions = {
    onCreateMenu: this.onCreateMenu,
    onMenuItemClick: this.onMenuItemClick,
    onPrepareMenu: this.onPrepareMenu
  };

  build() {
    Column() {
      Text(this.text)
        .fontSize(20)
        .copyOption(CopyOptions.LocalDevice)
        .editMenuOptions(this.editMenuOptions)
        .margin({ top: 100 })
        .onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
          this.endIndex = selectionEnd;
        })
    }
    .width("90%")
    .margin("5%")
  }
}

textEditMenuOptions

Example 13: Securing Sensitive Information

This example illustrates how to secure sensitive information using the privacySensitive attribute, available since API version 12. Note that the display requires widget framework support.

// xxx.ets
@Entry
@Component
struct TextExample13 {
  build() {
    Column({ space: 10 }) {
      Text("privacySensitive")
        .privacySensitive(true)
        .margin({ top: 30 })
    }
    .alignItems(HorizontalAlign.Center)
    .width("100%")
  }
}

textPrivacySensitive

Example 14: Configuring Automatic Spacing Between Chinese and Western Text

This example demonstrates how to configure automatic spacing between Chinese and Western characters using the enableAutoSpacing attribute, available since API version 20.

// xxx.ets
@Entry
@Component
struct TextExample {
  build() {
    Row() {
      Column() {
        Text('Automatic spacing: Enabled').margin(5)
        Text('中文 Text')
          .enableAutoSpacing(true)
        Text('Automatic spacing: Disabled').margin(5)
        Text('中文Text')
          .enableAutoSpacing(false)
      }.height('100%')
    }
    .width('60%')
  }
}

textEnableAutoSpacing

Example 15: Applying Gradient and Solid Colors to Text

This example demonstrates how to apply gradient and solid colors to the Text component using the shaderStyle API, available since API version 20.

@Entry
@Component
struct ShaderColorStyle {
  @State message: string = 'Hello World';
  @State linearGradientOptions1: LinearGradientOptions =
    {
      angle: 45,
      colors: [[Color.Red, 0.0], [Color.Blue, 0.3], [Color.Green, 0.5]]
    };
  @State linearGradientOptions2: LinearGradientOptions =
    {
      direction: GradientDirection.LeftTop,
      colors: [[Color.Red, 0.0], [Color.Blue, 0.3], [Color.Green, 0.5]],
      repeating: true,
    };
  @State radialGradientOptions: RadialGradientOptions =
    {
      center: [50, 50],
      radius: 20,
      colors: [[Color.Red, 0.0], [Color.Blue, 0.3], [Color.Green, 0.5]],
      repeating: true,
    };
  @State colorShaderStyle: ColorShaderStyle =
    {
      color: Color.Blue
    };
  build() {
    Column({ space: 5 }) {
      Text('Linear gradient (45° angle)').fontSize(18).width('90%').fontColor(0xCCCCCC)
        .margin({ top: 40, left: 40 })
      Text(this.message)
        .fontSize(50)
        .width('80%')
        .height(50)
        .shaderStyle(this.linearGradientOptions1)
      Text('Linear gradient (top left direction)').fontSize(18).width('90%').fontColor(0xCCCCCC)
        .margin({ top: 40, left: 40 })
      Text(this.message)
        .fontSize(50)
        .width('80%')
        .height(50)
        .shaderStyle(this.linearGradientOptions2)
      Text('Radial gradient').fontSize(18).width('90%').fontColor(0xCCCCCC)
        .margin({ top: 40, left: 40 })
      Text(this.message)
        .fontSize(50)
        .width('80%')
        .height(50)
        .shaderStyle(this.radialGradientOptions)
      Text('Solid color').fontSize(18).width('90%').fontColor(0xCCCCCC)
        .margin({ top: 40, left: 40 })
      Text(this.message)
        .fontSize(50)
        .width('80%')
        .height(50)
        .shaderStyle(this.colorShaderStyle)
    }
  }
}

zh-cn_image_0000001219864149

Example 16: Configuring Trailing Space Optimization

This example demonstrates how to optimize trailing spaces using the optimizeTrailingSpace attribute, available since API version 20. This attribute is typically used with alignment features, and actual display requires font engine support.

// xxx.ets
@Entry
@Component
struct TextExample16 {
  build() {
    Column() {
      Text("Trimmed space enabled     ")
        .fontSize(30)
        .fontWeight(FontWeight.Bold)
        .margin({ top: 20 })
        .optimizeTrailingSpace(true)
        .textAlign(TextAlign.Center)
      Text("Trimmed space disabled     ")
        .fontSize(30)
        .fontWeight(FontWeight.Bold)
        .margin({ top: 20 })
        .optimizeTrailingSpace(false)
        .textAlign(TextAlign.Center)
    }
    .width("100%")
  }
}

textOptimizeTrailingSpace

Example 17: Configuring Text Vertical Alignment

This example demonstrates how to configure vertical text alignment using the textVerticalAlign attribute, available since API version 20.

// xxx.ets
@Entry
@Component
struct TextExample14 {
  build() {
    Column({ space: 10 }) {
      Text() {
        Span("Hello")
          .fontSize(50)
        // Replace $r('app.media.startIcon') with the image resource file you use.
        ImageSpan($r('app.media.startIcon'))
          .width(30).height(30)
          .verticalAlign(ImageSpanAlignment.FOLLOW_PARAGRAPH)// Available since API version 20.
        Span("World")
      }
      .textVerticalAlign(TextVerticalAlign.CENTER)
      .borderWidth(1)
    }
    .alignItems(HorizontalAlign.Center)
    .width("100%")
  }
}

textVerticalAlign

Example 18: Implementing a Text Flip Animation

This example demonstrates how to implement a a flip animation for numeric text using the contentTransition attribute, available since API version 20.

// xxx.ets
@Entry
@Component
struct TextNumberTransition {
  @State number: number = 98;
  @State numberTransition: NumericTextTransition =
    new NumericTextTransition({ flipDirection: FlipDirection.DOWN, enableBlur: false });

  build() {
    Column() {
      Text(this.number + "")
        .borderWidth(1)
        .fontSize(40)
        .contentTransition(this.numberTransition)
      Button("change number")
        .onClick(() => {
          this.number++;
        })
        .margin(10)
    }
    .justifyContent(FlexAlign.Center)
    .height('100%')
    .width('100%')
  }
}

Text_content_transition

Example 19: Configuring Vertical Alignment for the Text Content Area

This example demonstrates how to use the textContentAlign attribute, available since API version 21, to configure vertical alignment for the text content when it exceeds the component height.

@Entry
@Component
struct TextContentAlignExample {

  build() {
    Column() {
      Row() {
        Text('This is sample text for demonstration')
          .fontSize(30)
          .backgroundColor(Color.Gray)
          .width('80%')
          .height(20)
          .textContentAlign(TextContentAlign.CENTER)
      }.height('60%')
    }
  }
}

Text_Content_Align

Example 20: Setting Line Height Multiplier and Maximum/Minimum Line Heights

This example demonstrates how to use lineHeightMultiple to set the line height in multiple mode and use minLineHeight and maxLineHeight to set the minimum and maximum line heights, all available since API version 22.

import { LengthUnit } from '@kit.ArkUI';

@Entry
@Component
struct Index {
  @State message: string = 'hello';

  build() {
    Scroll() {
      Column() {
        Row() {
          Text(this.message)
            .lineHeight(176)
            .backgroundColor(0xffc0c0c0)
            .fontSize(50)
          Text(this.message)
            .lineHeightMultiple(3)
            .backgroundColor(0xffc0c0c0)
            .fontSize(50)
          Text(this.message)
            .lineHeight(300)
            .maxLineHeight({value:176,unit:LengthUnit.FP})
            .backgroundColor(0xffc0c0c0)
            .fontSize(50)
          Text(this.message)
            .lineHeight(10)
            .minLineHeight({value:176,unit:LengthUnit.FP})
            .backgroundColor(0xffc0c0c0)
            .fontSize(50)
        }
      }
    }.height('100%')
    .width('100%')
  }
}

Text_line_height_multiple

Example 21: Setting the Minimum Number of Lines for Text Display

This example demonstrates how to set the minimum number of lines using the minLines attribute, available since API version 22.


@Entry
@Component
struct TextExample1 {
  @State message1: string = 'Hello world!';
  @State message2: string = 'The minimum number of lines displayed for this text setting is 1';

  build() {
    Column() {
      Text(this.message1)
        .minLines(3)
        .fontSize(20)
        .margin(10)
        .width('95%')
        .border({ width: 1 })
      Text(this.message2)
        .minLines(1)
        .fontSize(20)
        .margin(10)
        .width('95%')
        .border({ width: 1 })
    }.height(100).width('90%').margin(10)
  }
}

textMinlines

Example 22: Setting and Highlighting the Text Selection Range

This example demonstrates how to set and highlight the text selection range using setTextSelection in TextController, available since API version 23.


@Entry
@Component
struct Index {
  controller: TextController = new TextController();
  @State textStr: string = 'Hello World!';

  build() {
    Scroll() {
      Column() {
        Text(this.textStr, { controller: this.controller })
          .fontSize(25)
          .borderWidth(1)
          .copyOption(CopyOptions.LocalDevice)
        Button("setTextSelection")
          .onClick(() => {
            this.controller.setTextSelection(1, 6, { menuPolicy: MenuPolicy.HIDE })
          })
          .margin({ bottom: 20, top: 10 } as Margin)
      }
      .margin({ top: 100, left: 8, right: 8 } as Margin)
    }
  }
}

textSetTextSelection

Example 23: Setting Leading Punctuation Compression

This example demonstrates how to set leading punctuation compression using the compressLeadingPunctuation API. If a punctuation mark with a leading space appears at the start of a line, the punctuation mark will be compressed to the left boundary.

The compressLeadingPunctuation API is supported since API version 23.

// xxx.ets
@Entry
@Component
struct Index {
  build() {
    Column(){
      Text("\u300CLeading punctuation compression enabled")
        .compressLeadingPunctuation(true)
        .margin(5)
        .border({ width: 1 })
        .fontSize(30)
        .width("90%")
      Text("\u300CLeading punctuation compression disabled")
        .compressLeadingPunctuation(false)
        .border({ width: 1 })
        .fontSize(30)
        .width("90%")
    }
  }
}

textCompressLeadingPunctuation

Example 24: Setting Adaptive Spacing

This example uses the includeFontPadding API to add the spacing of the first and last lines and the fallbackLineSpacing API to set adaptive line spacing.

The includeFontPadding and fallbackLineSpacing APIs are supported since API version 23.

// xxx.ets

const UYGHUR_TEXT: string = 'ياخشىمۇسەنياخشىمۇسەنياخشىمۇسەنياخشىمۇسەنياخشىمۇسەنياخشىمۇسەنياخشىمۇسەن';
@Entry
@Component
struct Index {
  @State include: boolean | null | undefined = false;
  @State fallback: boolean | null | undefined = false;
  @State displayText: string = UYGHUR_TEXT;

  build() {
    Column() {
      Text(this.displayText)
        .includeFontPadding(this.include)
        .fallbackLineSpacing(this.fallback)
        .lineHeight(5)
        .width('100%')
        .height(100)
        .backgroundColor('#eee')
        .borderWidth(1)
        .borderColor('#dddddd')

      Scroll() {
        Column() {
          // --- Buttons related to IncludeFontPadding ---
          Button('Set includePadding: ' + this.include)
            .onClick(() => {
              this.include = this.include === false ? true : false;
            })
            .margin({ bottom: 10 })

          // --- Button related to FallbackLineSpacing ---
          Button('Set fallbackLineSpacing: ' + this.fallback)
            .onClick(() => {
              this.fallback = this.fallback === false ? true : false;
            })
            .margin({ bottom: 10 })

        }
        .width('100%')
        .padding(5)
      }
      .height(250)
      .backgroundColor('transparent')
      .scrollBarWidth(2)
      .scrollBarColor('#888')

    }
    .width('100%')
    .height('100%')
    .padding(20)
  }
}

textIncludeFontPadding

Example 25: Setting the Drag Preview Style for Text Being Dragged

This example demonstrates how to set the drag preview style for text being dragged using the selectedDragPreviewStyle API.

The selectedDragPreviewStyle API is supported since API version 23.

@Entry
@Component
struct TextTest {
  build() {
    Column() {
      Text('This is drag text')
        .copyOption(CopyOptions.InApp)
        .width(200)
        .height(100)
        .margin(150)
        .draggable(true)
        .selectedDragPreviewStyle({color: 'rgba(227, 248, 249, 1)'})
    }
    .height('100%')
  }
}

selectedDragPreviewStyle

Example 26: Setting the Text Layout Direction

This example demonstrates how to set the text layout direction using the textDirection API.

The textDirection API is supported since API version 23.

// xxx.ets
@Entry
@Component
struct TextExample {
  @State text: string = 'Text layout direction example';

  build() {
    Column({ space: 3 }) {
      Text('Text layout direction: DEFAULT')
        .fontSize(12).width('90%').margin(5)
      Text(this.text)
        .width('95%')
        .borderWidth(1)
      Text('Text layout direction: RTL')
        .fontSize(12).width('90%').margin(5)
      Text(this.text)
        .width('95%')
        .borderWidth(1)
        .textDirection(TextDirection.RTL)
      Text('Text layout direction: RTL, text horizontal alignment: LEFT')
        .fontSize(12).width('90%').margin(5)
      Text(this.text)
        .width('95%')
        .borderWidth(1)
        .textDirection(TextDirection.RTL)
        .textAlign(TextAlign.LEFT)
    }
    .width('100%')
    .height('100%')
  }
}

textTextDirection

Example 27: Obtaining Text Information Corresponding to Specified Coordinates and Range

The getCharacterPositionAtCoordinate, getGlyphRangeForCharacterRange, and getCharacterRangeForGlyphRange APIs are supported since API version 24. This example shows how to use the getLayoutManager API to call the text layout manager object to obtain text information. It also demonstrates how to use the getCharacterPositionAtCoordinate API in LayoutManager to obtain position information for the coordinate, the getGlyphRangeForCharacterRange API to obtain the glyph index range and actual character index range based on the character index range, and the getCharacterRangeForGlyphRange API to obtain the character index range and actual glyph index range based on the glyph index range.

// xxx.ets
import { LengthMetrics } from '@kit.ArkUI';

@Entry
@Component
struct TextExample10 {
  @State start: number = 10;
  @State end: number = 20;
  textController: TextController = new TextController();
  textStr: string = "Hello World";
  @State str1: string = ""
  @State str2: string = ""
  @State str3: string = ""
  @State str4: string = ""
  textStyleAttrs: TextStyle =
    new TextStyle({ fontWeight: FontWeight.Bolder, fontSize: LengthMetrics.vp(24), fontStyle: FontStyle.Italic });
  titleParagraphStyleAttr: ParagraphStyle =
    new ParagraphStyle({ paragraphSpacing: LengthMetrics.px(50), textIndent: LengthMetrics.vp(15) });
  mutableStyledString: MutableStyledString =
    new MutableStyledString("Styled string TextStyle test\nStyled string test\nStyled string TextStyle test");

  build() {
    Column() {
      Text(this.textStr, { controller: this.textController }) {
        Span("Hello World 123 \n")
        Span("Hello World 456 \n")
        Span("Hello World 789 \n")
      }
      .fontSize(25)
      .borderWidth(1)

      Text(this.str1)
      Text(this.str2)
      Text(this.str3)
      Text(this.str4)

      Button("Add Styled String").onClick (() => {
        this.textController.setStyledString(this.mutableStyledString)
      })

      Button("Glyph Info at [150, 50]")
        .onClick(() => {
          let layoutManager: LayoutManager = this.textController.getLayoutManager();
          let position1: PositionWithAffinity = layoutManager.getGlyphPositionAtCoordinate(150, 50);
          this.str1 = "Glyph info at [150, 50]. glyphPosition position: " + position1.position +
            " affinity: " +
          position1.affinity;

          let position2: PositionWithAffinity =
            layoutManager.getCharacterPositionAtCoordinate(150, 50) as PositionWithAffinity;
          this.str2 = "Glyph info at [150, 50]. characterPosition position: " + position2.position +
            " affinity: " +
          position2.affinity;

          let range1: TextRange = { start: this.start, end: this.end };
          let ranges1: Array<TextRange> = layoutManager.getGlyphRangeForCharacterRange(range1) as Array<TextRange>
          this.str3 = "getGlyphRangeForCharacterRange. Glyph range: " + ranges1[0].start + " " + ranges1[0].end + "\n" 
            "getGlyphRangeForCharacterRange. Actual character range: " + ranges1[1].start + " " + ranges1[1].end

          let range2: TextRange = { start: this.start, end: this.end };
          let ranges2: Array<TextRange> = layoutManager.getCharacterRangeForGlyphRange(range2) as Array<TextRange>
          this.str4 = "getCharacterRangeForGlyphRange. Character range: " + ranges2[0].start + " " + ranges2[0].end + "\n" +
            "getCharacterRangeForGlyphRange. Actual glyph range: " + ranges2[1].start + " " + ranges2[1].end
        })
        .margin({ bottom: 20, top: 10 })
    }.justifyContent(FlexAlign.Center).width("100%").height("100%")
  }
}

textRangePosition

Example 28: Enabling/Disabling Orphan Character Optimization During Text Typesetting

This example demonstrates how to use the orphanCharOptimization API to enable/disable orphan word optimization, ensuring no orphan character appears in the last line of a paragraph.

The orphanCharOptimization API is supported since API version 26.0.0.

// xxx.ets
@Entry
@Component
struct TextExample {
  @State text: string = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa文本aaaaaaaaaaaaa';

  build() {
    Column({ space: 3 }) {
      Text('Text disables orphan character optimization.')
        .fontSize(12).width('90%').margin(5)
      Text(this.text)
        .fontSize(20)
        .width('456')
        .borderWidth(1)
      Text('Text enables orphan character optimization.')
        .fontSize(12).width('90%').margin(5)
      Text(this.text)
        .fontSize(20)
        .width('456')
        .borderWidth(1)
        .orphanCharOptimization(true)
    }
    .width('100%')
    .height('100%')
  }
}

textOrphanCharOptimization