Search

The Search component provides an area for users to enter search queries.

NOTE

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

This component supports plain text only. For rich text, use the RichEditor component.

Child Components

Not supported

APIs

Search(options?: SearchOptions)

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 SearchOptions No Initialization options of the Search component.

SearchOptions18+

Describes the initialization options of the Search component.

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.

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
value8+ ResourceStr No Yes Sets the text input in the search text box.
Since API version 10, this parameter supports two-way binding through $$.
Since API version 18, this parameter supports two-way binding through !!.
Atomic service API: This API can be used in atomic services since API version 11.
The Resource type is supported since API version 20.
placeholder8+ ResourceStr No Yes Text displayed when there is no input.
Atomic service API: This API can be used in atomic services since API version 11.
icon8+ string No Yes Path to the search icon. By default, the system search icon is used.
NOTE
The icon data source supports both relative paths and network images.
- The supported formats include PNG, JPG, BMP, SVG, GIF, pixelmap, and HEIF.
- The Base64 string is supported in the following format: data:image/[png|jpeg|bmp|webp|heif];base64,[base64 data], where [base64 data] is a Base64 string.
If this attribute and the searchIcon attribute are both set, the searchIcon attribute takes precedence.
Atomic service API: This API can be used in atomic services since API version 11.
controller8+ SearchController No Yes Controller of the Search component.
Atomic service API: This API can be used in atomic services since API version 11.

Attributes

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

searchButton

searchButton(value: ResourceStr, option?: SearchButtonOptions)

Sets the text on the search button located next to the search text box.

Clicking the search button triggers both onSubmit and onClick callbacks.

The default font size on wearable devices is 18 fp.

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 ResourceStr Yes Text on the search button located next to the search text box.
The Resource type is supported since API version 20.
option SearchButtonOptions No Text style of the search button located next to the search text box.
Default value:
{
fontSize: '16fp',
fontColor: '#ff3f97e9'
}

placeholderColor

placeholderColor(value: ResourceColor)

Sets the placeholder text color. The default value on wearable devices is '#99ffffff'.

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 Placeholder text color.
Default value: '#99182431'

placeholderFont

placeholderFont(value?: Font)

Placeholder text style, including the font size, font weight, 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 No Placeholder text style.

NOTE

You can use loadFontSync to register custom fonts.

textFont

textFont(value?: Font)

Style of the text entered in the search box, including the font size, font weight, font family, and font style.

The default font size on wearable devices is 18 fp.

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 No Text font of the search text box.

textAlign9+

textAlign(value: TextAlign)

Sets the text alignment mode in the search text box. Currently, the following alignment modes are supported: TextAlign.Start, TextAlign.Center, TextAlign.End, TextAlign.LEFT, and TextAlign.RIGHT. TextAlign.JUSTIFY behaves the same as TextAlign.Start.

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 Text alignment mode in the search text box.
Default value: TextAlign.Start

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.

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 Defines the text layout direction.
If this parameter is set to undefined, the text layout direction follows the component layout direction as defined by TextDirection.DEFAULT.

copyOption9+

copyOption(value: CopyOptions)

Sets whether the input text can be copied. If this attribute is set to CopyOptions.None, the Search component supports paste and select-all operations, while other operations such as copy, cut, translate, and share, as well as the Celia Writer assisted writing feature, are disabled.

Dragging is not allowed when CopyOptions.None is set.

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 the input text can be copied.
Default value: CopyOptions.LocalDevice

searchIcon10+

searchIcon(value: IconOptions | SymbolGlyphModifier)

Sets the style of the search icon on the left.

The default icon size on wearable devices is 16 vp.

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 IconOptions | SymbolGlyphModifier Yes Style of the search icon on the left.
Default value in light mode:
{
size: '16vp',
color: '#99182431',
src: ' '
}
Default value in dark mode:
{
size: '16vp',
color: '#99ffffff',
src: ' '
}

cancelButton10+

cancelButton(value: CancelButtonOptions | CancelButtonSymbolOptions)

Sets the style of the cancel button on the right. For details, see Example 2: Setting Search and Delete Icons and Example 11: Setting a Custom Symbol-Type Cancel Button.

The default icon size on wearable devices is 18 fp.

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 CancelButtonOptions | CancelButtonSymbolOptions Yes Style of the cancel button on the right.
Default value:
{
style: CancelButtonStyle.INPUT,
icon: {
size: '16vp',
color: '#99ffffff',
src: ' '
}
}
When style is set to CancelButtonStyle.CONSTANT, the cancel button is displayed in a default style.

fontColor10+

fontColor(value: ResourceColor)

Sets the font color of the input text. fontSize, fontStyle, fontWeight, and fontFamily are set in the textFont attribute.

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 of the input text.
Default value: '#FF182431'
Default value on wearable devices: **'#dbffffff' **

caretStyle10+

caretStyle(value: CaretStyle)

Sets the caret 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 CaretStyle Yes Caret style.
Default value:
{
width: '2.0vp',
color: '#007DFF'
}

NOTE
Since API version 12, this API can be used to set the text handle color, which is the same as the caret color.

enableKeyboardOnFocus10+

enableKeyboardOnFocus(value: boolean)

Sets whether to pop up the soft keyboard when the Search component obtains focus in a way other than clicking.

Since API version 10, the Search component is bound to the input method by default when it obtains focus.

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 Whether to automatically pop up the soft keyboard when the Search component gains focus.
true: The soft keyboard pops up. false: The soft keyboard does not pop up.
Default value: true

selectionMenuHidden10+

selectionMenuHidden(value: boolean)

Sets whether to hide the system text selection menu.

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 Whether to hide the system text selection menu.
true: Tapping, long-pressing, double-tapping, triple-tapping, or right-clicking the text box will not trigger the system text selection menu.
false: Tapping, long-pressing, double-tapping, triple-tapping, or right-clicking the text box will trigger the system text selection menu.
Default value: false

customKeyboard10+

customKeyboard(value: CustomBuilder | ComponentContent | undefined, options?: KeyboardOptions)

Sets the custom keyboard.

When a custom keyboard is set, activating the text box opens the specified custom component, instead of the system input method.

The custom keyboard's height can be set through the height attribute of the custom component's root node, and its width is fixed at the default value.

The custom keyboard is presented by overlaying the original screen. It is not compressed or lifted if avoid mode is not enabled or avoidance is not needed for the text box.

The custom keyboard cannot obtain focus, but it blocks gesture events.

By default, the custom keyboard is closed when the input component loses focus. You can also use the stopEditing API to close the keyboard.

When setting a custom keyboard, you can bind the onKeyPreIme event to prevent input from the physical keyboard.

From API version 23, the setCustomKeyboardContinueFeature API can be used to enable the continuation feature for custom keyboards. When switching between custom keyboards, the system changes the keyboard directly without triggering the close and open animations.

NOTE

This API cannot be called within attributeModifier.

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 CustomBuilder | ComponentContent22+ | undefined22+ Yes Custom keyboard. If the value is undefined, the custom keyboard is closed.
options12+ KeyboardOptions No Whether to support keyboard avoidance.

type11+

type(value: SearchType)

Sets the text box type.

Different SearchType values trigger corresponding keyboard types and enforce input restrictions.

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 SearchType Yes Text box type.
Default value: SearchType.NORMAL

maxLength11+

maxLength(value: number)

Sets the maximum number of characters for text input. By default, there is no maximum number of characters. When the maximum number is reached, no more characters can be entered.

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 number Yes Maximum number of characters for text input.
When the value is less than 0, the default value is used and no limit is applied.

enterKeyType12+

enterKeyType(value: EnterKeyType)

Sets the type of the Enter key.

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 EnterKeyType Yes Type of the Enter key.
Default value: EnterKeyType.Search

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

lineHeight12+

lineHeight(value: number | string | Resource)

Sets the text line height. If the value is less than or equal to 0, the line height is not limited and the font size is adaptive. If the value is of the number type, the unit fp is used.

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 number | string | Resource Yes Text line height.

NOTE

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

decoration12+

decoration(value: TextDecorationOptions)

Sets the color, type, and style of the text decorative 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 TextDecorationOptions Yes Text decorative line options.
Default value: {
 type: TextDecorationType.None,
 color: Color.Black,
 style: TextDecorationStyle.SOLID 
}

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.

letterSpacing12+

letterSpacing(value: number | string | Resource)

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.

If the value specified is a negative value, the text is compressed. A negative value too small may result in the text being compressed to 0 and no content being displayed.

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

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 number | string | Resource Yes Letter spacing.
Unit: fp

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.

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.

For details about the supported font features, see the font feature list.

Font features are advanced typographic features, such as ligatures and monospace, for OpenType fonts. They are typically used in custom fonts and require the support of the font itself.

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.

selectedBackgroundColor12+

selectedBackgroundColor(value: 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 12.

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
value ResourceColor Yes Background color of the selected text.

inputFilter12+

inputFilter(value: ResourceStr, error?:  Callback< string >)

Sets the regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out.

For single-character input scenarios, only single-character matching is supported; for multi-character input scenarios (such as pasting), string matching is supported.

If inputFilter is set and the entered characters are not null, the filtering effect attached to the text box type (specified through the type attribute) does not take effect.

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 ResourceStr Yes Regular expression.
error  Callback< string > No Filtered-out content to return when regular expression matching fails.

textIndent12+

textIndent(value: Dimension)

Sets the indent of the first line 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
value Dimension Yes Indent of the first line text.
Default value: 0

minFontSize12+

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 or layout constraint settings.

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

If minFontSize is less than or equal to 0, the adaptive font size does not take effect. In this case, the value of size in the textFont attribute takes effect. If size is not set, the default value applies.

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 number | string | Resource Yes Minimum font size.
Unit: fp

maxFontSize12+

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 or layout constraint settings.

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

If maxFontSize is less than or equal to 0 or maxFontSize is less than minFontSize, the adaptive font size does not take effect. In this case, the value of size in the textFont attribute takes effect. If size is not set, the default value applies.

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 number | string | Resource Yes Maximum font size.
Unit: fp

halfLeading18+

halfLeading(halfLeading: Optional<boolean>)

Enables half leading for text, which splits the leading equally between the top and bottom of the line.

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
halfLeading Optional<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

minFontScale18+

minFontScale(scale: Optional<number | Resource>)

Sets the minimum font scale factor for text.

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
scale Optional<number | Resource> Yes Minimum font scale factor for text. The undefined type is supported.
Value range: [0, 1]
NOTE
A value less than 0 is handled as 0. A value greater than 1 is handled as 1. Abnormal values are ineffective by default.
Before use, you need to configure the configuration.json and app.json5 files in the project. For details, see Example 19: Setting the Minimum and Maximum Font Scale Factors.

maxFontScale18+

maxFontScale(scale: Optional<number | Resource>)

Sets the maximum font scale factor for text.

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
scale Optional<number | Resource> Yes Maximum font scale factor for text. The undefined type is supported.
Value range: [1, +∞)
NOTE
A value less than 1 is handled as 1. Abnormal values are ineffective by default.
After the maxFontScale attribute is set, the content of the Search component can be scaled up to 2 times at most.
Before use, you need to configure the configuration.json and app.json5 files in the project. For details, see Example 19: Setting the Minimum and Maximum Font Scale Factors.

editMenuOptions12+

editMenuOptions(editMenu: EditMenuOptions)

Sets the extended options of 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.

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.

enablePreviewText12+

enablePreviewText(enable: boolean)

Sets whether to enable preview text.

The preview content is defined as a temporary, uncommitted input state. Currently, the text interception function is 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
enable boolean Yes Whether to enable preview text.
true: Preview text is enabled. false: Preview text is disabled.
Default value: true

NOTE

Preview text represents a temporary, uncommitted input state. This feature requires support from the input method with pre-commit text functionality enabled. During text entry, when candidate words have not been confirmed yet, the text box displays marked text in a provisional state. For example, when users enter Chinese using Pinyin input, the Pinyin letters appear in the input box before a word is selected from the candidate word list. This intermediate state constitutes preview text.

enableHapticFeedback13+

enableHapticFeedback(isEnabled: boolean)

Specifies 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",
 }
]

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: Haptic feedback is enabled. false: Haptic feedback is disabled.
Default value: true

autoCapitalizationMode20+

autoCapitalizationMode(mode: AutoCapitalizationMode)

Sets the text auto-capitalization mode. This API provides the capability, but actual implementation depends on the input method application.

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
mode AutoCapitalizationMode Yes Auto-capitalization mode. The default state is inactive.

keyboardAppearance15+

keyboardAppearance(appearance: Optional<KeyboardAppearance>)

Sets the keyboard appearance for the text box. This setting takes effect only after input method adaptation. For details, see Immersive Mode of the Input Method Application.

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

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
appearance Optional<KeyboardAppearance> Yes Appearance of the keyboard.
Default value: KeyboardAppearance.NONE_IMMERSIVE

strokeWidth20+

strokeWidth(width: Optional<LengthMetrics>)

Sets the text stroke width.

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
width Optional<LengthMetrics> Yes Text stroke width. When the unit of LengthMetrics is px:
Values < 0: solid text.
Values > 0: outlined text.
Default value: 0 (no stroke)

strokeColor20+

strokeColor(color: Optional<ResourceColor>)

Sets the text stroke color.

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
color Optional<ResourceColor> Yes Stroke color. Default value: font color. Invalid values are treated as the default value.

stopBackPress15+

stopBackPress(isStopped: Optional<boolean>)

Sets whether to prevent the back key event from being propagated.

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

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
isStopped Optional<boolean> Yes Whether to prevent the back key event from being propagated.
true: Propagation is prevented. false: Propagation is allowed.
Default value: true The default value is used for abnormal values.

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: Enabled. false: Disabled.
Default value: false

selectedDragPreviewStyle23+

selectedDragPreviewStyle(value: SelectedDragPreviewStyle | undefined)

Sets the drag preview style for text being dragged in the search box.

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 text being dragged in the search box.
If this parameter is set to undefined, the drag preview follows the theme: white in light mode and black in dark mode.

dividerColor23+

dividerColor(color: Optional<ColorMetrics>)

Sets the color of the text box divider.

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
color Optional<ColorMetrics> Yes Divider color.
By default, system theme colors are used: 0x33000000 in light mode (appears as light black), 0x33FFFFFF in dark mode (appears as light white).

compressLeadingPunctuation23+

compressLeadingPunctuation(enabled: Optional<boolean>)

Sets whether to enable leading punctuation compression.

NOTE

  • Leading punctuation is not compressed by default.

  • For the list of punctuation marks that support compression, see the punctuation range at the beginning of a line in 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.

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.

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

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

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

IconOptions10+

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

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Type Read-Only Optional Description
size Length No Yes Icon size. It cannot be set in percentage.
color ResourceColor No Yes Icon color.
src ResourceStr No Yes Image source of the icon.

SearchButtonOptions10+

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Type Read-Only Optional Description
fontSize Length No Yes Font size of the button. It cannot be set in percentage. Atomic service API: This API can be used in atomic services since API version 11.
fontColor ResourceColor No Yes Font color of the button. Atomic service API: This API can be used in atomic services since API version 11.
autoDisable18+ Boolean No Yes Whether to disable the search button when there is no text input.
Default value: false
true: The search button is disabled when there is no text input. false: The search button remains enabled regardless of the text input.
Atomic service API: This API can be used in atomic services since API version 18.

CancelButtonStyle10+

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

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Description
CONSTANT The Cancel button is always displayed.
INVISIBLE The Cancel button is always hidden.
INPUT The Cancel button is displayed when there is text input.

SearchType11+

Enumerates the text input types of a search box.

System capability: SystemCapability.ArkUI.ArkUI.Full

Name Value Description
NORMAL 0 Basic input mode with no special restrictions.
Atomic service API: This API can be used in atomic services since API version 12.
NUMBER 2 Digit input mode.
Atomic service API: This API can be used in atomic services since API version 12.
PHONE_NUMBER 3 Phone number input mode.
In this mode, the following characters are allowed: digits, spaces, plus signs (+), hyphens (-), asterisks (*), and number signs (#); the length is not limited.
Atomic service API: This API can be used in atomic services since API version 12.
EMAIL 5 Email address input mode.
This mode accepts only digits, letters, underscores (_), dots (.), and the following special characters: ! # $ % & ' * + - / = ? ^ ` { | } ~ @ (which can only appear once)
Atomic service API: This API can be used in atomic services since API version 12.
NUMBER_DECIMAL12+ 12 Number input mode with a decimal point.
The value can contain digits and one decimal point.
Atomic service API: This API can be used in atomic services since API version 12.
URL12+ 13 URL input mode with no special restrictions.
Atomic service API: This API can be used in atomic services since API version 12.
ONE_TIME_CODE20+ 14 One-time code (verification code) input mode with no special restrictions.
Atomic service API: This API can be used in atomic services since API version 20.

CancelButtonOptions12+

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
style CancelButtonStyle No Yes Display state of the Cancel button on the right.
icon IconOptions No Yes Icon of the Cancel button on the right.

CancelButtonSymbolOptions12+

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
style CancelButtonStyle No Yes Display state of the Cancel button on the right.
icon SymbolGlyphModifier No Yes Symbol icon of the Cancel button on the right.

Events

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

onSubmit

onSubmit(callback: Callback<string>)

Called when the search icon, search button, or soft keyboard search button is clicked.

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
callback Callback<string> Yes Search submission callback, which returns the text content currently in the search box.

onSubmit14+

onSubmit(callback: SearchSubmitCallback)

Invoked when the search icon, search button, or soft keyboard search button is clicked. The submission event provides a method to maintain the edit state of the Search component.

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
callback SearchSubmitCallback Yes Callback invoked when the search icon, search button, or soft keyboard search button is clicked.

onChange

onChange(callback: EditableTextOnChangeCallback)

Called when the input in the text box changes.

In this callback, if caret operations are performed, you must adjust the caret logic based on the previewText parameter to ensure it works seamlessly within the preview display scenario.

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
callback EditableTextOnChangeCallback Yes Callback invoked when the input in the text box changes.

onCopy

onCopy(callback:Callback<string>)

Called when a copy operation is performed.

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
callback Callback<string> Yes Callback used to return the copied text content.

onCut

onCut(callback:Callback<string>)

Called when a cut operation is performed.

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
callback Callback<string> Yes Callback used to return the cut text content.

onPaste

onPaste(callback:OnPasteCallback )

Called when a paste operation is performed.

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
callback OnPasteCallback Yes Callback used to return the pasted text content.

onTextSelectionChange10+

onTextSelectionChange(callback: OnTextSelectionChangeCallback)

Called when the text selection changes or the caret position changes during editing.

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
callback OnTextSelectionChangeCallback Yes Callback for text selection changes or caret position changes.

onContentScroll10+

onContentScroll(callback: OnContentScrollCallback)

Called when the text content is scrolled.

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
callback OnContentScrollCallback Yes Callback for text content scrolling.

onEditChange12+

onEditChange(callback: Callback< boolean >)

Called when the input state changes. The text box is in the editing state when it has the caret placed in it, and is in the non-editing state otherwise.

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
callback  Callback< boolean > Yes Callback for editing state changes. The value true indicates that the text is being inserted, and false indicates that the text box is out of focus and text cannot be inserted.

onWillInsert12+

onWillInsert(callback: Callback<InsertValue, boolean>)

Called when text is about to be inserted.

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
callback Callback<InsertValue, boolean> Yes Callback invoked when text is about to be inserted.
It returns true if the text is inserted; returns false otherwise.
This callback is not invoked for pre-edit or candidate word operations.
It is available only for system input methods.

onDidInsert12+

onDidInsert(callback: Callback<InsertValue>)

Called when text is inserted.

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
callback Callback<InsertValue> Yes Callback invoked when text is inserted.
It is available only for system input methods.

onWillDelete12+

onWillDelete(callback: Callback<DeleteValue, boolean>)

Called when text is about to be deleted.

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
callback Callback<DeleteValue, boolean> Yes Callback invoked when text is about to be deleted.
It returns true if the text is deleted; returns false otherwise.
This callback is not invoked for text preview.
It is available only for system input methods.

onDidDelete12+

onDidDelete(callback: Callback<DeleteValue>)

Called when text is deleted.

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
callback Callback<DeleteValue> Yes Callback invoked when text is deleted.
It is available only for system input methods.

NOTE

Clicking the clear button does not trigger the onDidDelete callback.

onWillChange15+

onWillChange(callback: Callback<EditableTextChangeValue, boolean>)

Called when the text content is about to change.

This callback is triggered after onWillInsert and onWillDelete, but before onDidInsert and onDidDelete.

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

System capability: SystemCapability.ArkUI.ArkUI.Full

Parameters

Name Type Mandatory Description
callback Callback<EditableTextChangeValue, boolean> Yes Callback invoked when the text content is about to change.
Returning true allows the change to proceed, while returning false cancels the change.

onWillAttachIME20+

onWillAttachIME(callback: Callback<IMEClient>)

Called when the search box is about to be bound to an input method.

Before the search box is bound to an input method, you can use the setKeyboardAppearanceConfig API of UIContext to set the keyboard style.

From API version 22, the setExtraConfig method of IMEClient can be called to set input method extension information. After the input method is bound, it receives this extension information, which can be used to implement custom functionality.

IMEClient is valid only during the execution of onWillAttachIME and cannot be called asynchronously.

NOTE

This API cannot be called within attributeModifier.

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
callback Callback<IMEClient> Yes Called when the search box is about to be bound to an input method.

SearchController

The controller for the Search component inherits from TextContentControllerBase. The APIs involved are as follows: system API getText and other APIs like getTextContentRect, getTextContentLineCount, getCaretOffset, addText, deleteText, getSelection, clearPreviewText, setStyledPlaceholder, and deleteBackward.

Objects to Import

controller: SearchController = new SearchController();

constructor

constructor()

A constructor used to create a SearchController object.

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

System capability: SystemCapability.ArkUI.ArkUI.Full

caretPosition

caretPosition(value: number): void

Sets the position of the caret.

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 Length from the start of the character string to the position where the caret is located.
Values less than 0 are treated as 0. Values greater than the string length are treated as the string length.

stopEditing10+

stopEditing(): void

Exits the editing state.

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

System capability: SystemCapability.ArkUI.ArkUI.Full

setTextSelection12+

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

Sets the text selection range and highlights the selected text when the component is focused. This API works only when the value of selectionStart is less than that of selectionEnd.

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 text selection range. The start position of text in the text box is 0.
A value less than 0 is handled as 0. A value greater than the maximum text length is handled as the maximum text length.
selectionEnd number Yes End position of the text selection range.
A value less than 0 is handled as 0. A value greater than the maximum text length is handled as the maximum text length.
options SelectionOptions No Configuration options for text selection.
Default value: MenuPolicy.DEFAULT

NOTE

If selectionStart or selectionEnd is set to undefined, the value 0 will be used.

If selectionMenuHidden is set to true or a 2-in-1 device is used, calling setTextSelection does not display the text selection menu even when options is set to MenuPolicy.SHOW.

If the selected text contains an emoji, the emoji is selected when its start position is within the text selection range.

SearchSubmitCallback14+

type SearchSubmitCallback = (searchContent: string, event?: SubmitEvent) => void

Called when the search icon, search button, or soft keyboard search button is clicked.

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
searchContent string Yes Current text input.
event SubmitEvent No Submit event.

Example

Example 1: Setting and Obtaining the Caret Position

This example demonstrates how to set and obtain the caret position using controller, available since API version 8.

// xxx.ets
@Entry
@Component
struct SearchExample {
  @State changeValue: string = '';
  @State submitValue: string = '';
  @State positionInfo: CaretOffset = { index: 0, x: 0, y: 0 };
  controller: SearchController = new SearchController();

  build() {
    Column({space: 10}) {
      Text('onSubmit:' + this.submitValue).fontSize(18).margin(15)
      Text('onChange:' + this.changeValue).fontSize(18).margin(15)
      Search({ value: this.changeValue, placeholder: 'Type to search...', controller: this.controller })
        .searchButton('SEARCH')
        .width('95%')
        .height(40)
        .backgroundColor('#F5F5F5')
        .placeholderColor(Color.Grey)
        .placeholderFont({ size: 14, weight: 400 })
        .textFont({ size: 14, weight: 400 })
        .onSubmit((value: string) => {
          this.submitValue = value;
        })
        .onChange((value: string) => {
          this.changeValue = value;
        })
        .margin(20)
      Button('Set caretPosition 1')
        .onClick(() => {
          // Move the caret to after the first entered character.
          this.controller.caretPosition(1);
        })
      Button('Get CaretOffset')
        .onClick(() => {
          this.positionInfo = this.controller.getCaretOffset();
        })
    }.width('100%')
  }
}

search

Example 2: Setting Search and Delete Icons

This example demonstrates the effect of setting the search and delete icons using the searchButton (available since API version 8), searchIcon (available since API version 10), and cancelButton (available since API version 10) attributes.

// xxx.ets
@Entry
@Component
struct SearchExample {
  @State changeValue: string = '';
  @State submitValue: string = '';

  build() {
    Column() {
      Text('onSubmit:' + this.submitValue).fontSize(18).margin(15)
      Search({ value: this.changeValue, placeholder: 'Type to search...' })
        .searchButton('SEARCH')
        .searchIcon({
          src: $r('sys.media.ohos_ic_public_search_filled')
        })
        .cancelButton({
          style: CancelButtonStyle.CONSTANT,
          icon: {
            src: $r('sys.media.ohos_ic_public_cancel_filled')
          }
        })
        .width('90%')
        .height(40)
        .maxLength(20)
        .backgroundColor('#F5F5F5')
        .placeholderColor(Color.Grey)
        .placeholderFont({ size: 14, weight: 400 })
        .textFont({ size: 14, weight: 400 })
        .onSubmit((value: string) => {
          this.submitValue = value;
        })
        .onChange((value: string) => {
          this.changeValue = value;
        })
        .margin(20)
    }.width('100%')
  }
}

searchButton

Example 3: Implementing a Custom Keyboard

This example implements a custom keyboard using the customKeyboard attribute (available since API version 10) to set the input parameter type in value to CustomBuilder and ComponentContent.

Since API version 22, ComponentContent is added to the input parameter type of customKeyboard.

// xxx.ets
import { ComponentContent } from '@kit.ArkUI';
class BuilderParams {
  inputValue: string;
  controller: SearchController;

  constructor(inputValue: string, controller: SearchController) {
    this.inputValue = inputValue;
    this.controller = controller;
  }
}
@Builder
function CustomKeyboardBuilder(builderParams: BuilderParams) {
  Column() {
    Row() {
      Button('x').onClick(() => {
        // Disable the custom keyboard.
        builderParams.controller.stopEditing();
      }).margin(10)
    }

    Grid() {
      ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item: number | string) => {
        GridItem() {
          Button(item + "")
            .width(110).onClick(() => {
            builderParams.inputValue += item;
          })
        }
      })
    }.maxCount(3).columnsGap(10).rowsGap(10).padding(5)
  }.backgroundColor(Color.Gray)
}
@Entry
@Component
struct SearchExample {
  controller: SearchController = new SearchController();
  @State inputValue: string = "";
  @State componentContent ?: ComponentContent<BuilderParams> = undefined;
  @State builderParam: BuilderParams = new BuilderParams(this.inputValue, this.controller);
  @State supportAvoidance: boolean = true;

  aboutToAppear(): void {
    // Create a ComponentContent instance.
    this.componentContent = new ComponentContent(this.getUIContext(), wrapBuilder(CustomKeyboardBuilder), this.builderParam);
  }
  build(){
    Column() {
      Text('Builder').margin(10).border({ width: 1 })
      Search({ controller: this.builderParam.controller, value: this.builderParam.inputValue })
        .customKeyboard(this.componentContent, { supportAvoidance: this.supportAvoidance })
        .margin(10).border({ width: 1 }).height('48vp')

      Text('ComponentContent').margin(10).border({ width: 1 })
      Search({ controller: this.builderParam.controller, value: this.builderParam.inputValue })
        .customKeyboard(CustomKeyboardBuilder(this.builderParam), { supportAvoidance: this.supportAvoidance })
        .margin(10).border({ width: 1 }).height('48vp')
    }
  }
}

customKeyboard

Example 4: Setting the Enter Key Type

This example demonstrates how to dynamically switch the enter key type using the enterKeyType attribute, available since API version 12.

// xxx.ets
@Entry
@Component
struct SearchExample {
  @State text: string = '';
  @State enterTypes: Array<EnterKeyType> = [EnterKeyType.Go, EnterKeyType.Search, EnterKeyType.Send, EnterKeyType.Done, EnterKeyType.Next, EnterKeyType.PREVIOUS, EnterKeyType.NEW_LINE];
  @State index: number = 0;
  build() {
    Column({ space: 20 }) {
      Search({ placeholder: 'Enter text', value: this.text })
        .width(380)
        .enterKeyType(this.enterTypes[this.index])
        .onChange((value: string) => {
          this.text = value;
        })
        .onSubmit((value: string) => {
          console.info("trigger search onsubmit" + value);
        })

      Button('Change EnterKeyType').onClick(() => {
        this.index = (this.index + 1) % this.enterTypes.length;
      })
    }.width('100%')
  }
}

Example 5: Setting the Text Style

This example showcases various text styles by using the lineHeight, letterSpacing, and decoration attributes, available since API version 12.

// xxx.ets
@Entry
@Component
struct SearchExample {
  build() {
    Row() {
      Column() {
        Text('lineHeight').fontSize(9).fontColor(0xCCCCCC)
        Search({value: 'lineHeight unset'})
          .border({ width: 1 }).padding(10)
        Search({value: 'lineHeight 15'})
          .border({ width: 1 }).padding(10).lineHeight(15)
        Search({value: 'lineHeight 30'})
          .border({ width: 1 }).padding(10).lineHeight(30)

        Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC)
        Search({value: 'letterSpacing 0'})
          .border({ width: 1 }).padding(5).letterSpacing(0)
        Search({value: 'letterSpacing 3'})
          .border({ width: 1 }).padding(5).letterSpacing(3)
        Search({value: 'letterSpacing -1'})
          .border({ width: 1 }).padding(5).letterSpacing(-1)

        Text('decoration').fontSize(9).fontColor(0xCCCCCC)
        Search({value: 'LineThrough, Red'})
          .border({ width: 1 }).padding(5)
          .decoration({type: TextDecorationType.LineThrough, color: Color.Red})
        Search({value: 'Overline, Red, DOTTED'})
          .border({ width: 1 }).padding(5)
          .decoration({type: TextDecorationType.Overline, color: Color.Red, style: TextDecorationStyle.DOTTED})
        Search({value: 'Underline, Red, WAVY'})
          .border({ width: 1 }).padding(5)
          .decoration({type: TextDecorationType.Underline, color: Color.Red, style: TextDecorationStyle.WAVY})
      }.height('90%')
    }
    .width('90%')
    .margin(10)
  }
}

SearchDecoration

Example 6: Setting Text Feature Effects

This example demonstrates how to display text with different font features using the fontFeature attribute, available since API version 12.

// xxx.ets
@Entry
@Component
struct SearchExample {
  @State text1: string = 'This is ss01 on : 0123456789';
  @State text2: string = 'This is ss01 off: 0123456789';

  build() {
    Column(){
      Search({value: this.text1})
        .margin({top:200})
        .fontFeature("\"ss01\" on")
      Search({value: this.text2})
        .margin({top:10})
        .fontFeature("\"ss01\" off")
    }
    .width("90%")
    .margin("5%")
  }
}

fontFeature

Example 7: Setting Custom Keyboard Avoidance

This example implements the custom keyboard avoidance effect by configuring the KeyboardOptions API (available since API version 12) through the customKeyboard attribute (available since API version 10).

// xxx.ets
@Entry
@Component
struct SearchExample {
  controller: SearchController = new SearchController();
  @State inputValue: string = "";
  @State height1: string | number = '80%';
  @State supportAvoidance: boolean = true;

  // Create a custom keyboard component.
  @Builder
  CustomKeyboardBuilder() {
    Column() {
      Row() {
        Button('x').onClick(() => {
          // Disable the custom keyboard.
          this.controller.stopEditing();
        }).margin(10)
      }

      Grid() {
        ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item: number | string) => {
          GridItem() {
            Button(item + "")
              .width(110).onClick(() => {
              this.inputValue += item;
            })
          }
        })
      }.maxCount(3).columnsGap(10).rowsGap(10).padding(5)
    }
    .backgroundColor(Color.Gray)
  }

  build() {
    Column() {
      Row() {
        Button("20%")
          .fontSize(24)
          .onClick(() => {
            this.height1 = "20%";
          })
        Button("80%")
          .fontSize(24)
          .margin({ left: 20 })
          .onClick(() => {
            this.height1 = "80%";
          })
      }
      .justifyContent(FlexAlign.Center)
      .alignItems(VerticalAlign.Bottom)
      .height(this.height1)
      .width("100%")
      .padding({ bottom: 50 })

      Search({ controller: this.controller, value: this.inputValue })// Bind a custom keyboard.
        .customKeyboard(this.CustomKeyboardBuilder(), { supportAvoidance: this.supportAvoidance })
        .margin(10)
        .border({ width: 1 })
        .onChange((value: string) => {
          this.inputValue = value;
        })
    }
  }
}

CustomSearchKeyType

Example 8: Setting Text Auto-Adaptation

This example implements the text auto-adaptation effect by using the minFontSize and maxFontSize attributes, both available since API version 12.

// xxx.ets
@Entry
@Component
struct SearchExample {
  build() {
    Row() {
      Column() {
        Text('adaptive font').fontSize(9).fontColor(0xCCCCCC)

        Search({value: 'This is the text without the adaptive font'})
          .width('80%').height(90).borderWidth(1)
        Search({value: 'This is the text without the adaptive font'})
          .width('80%').height(90).borderWidth(1)
          .minFontSize(4)
          .maxFontSize(40)
      }.height('90%')
    }
    .width('90%')
    .margin(10)
  }
}

searchAdaptFont

Example 9: Setting Insert and Delete Callbacks

This example implements the text insertion and deletion effects using the onWillInsert, onDidInsert, onWillDelete, and onDidDelete APIs, available since API version 12. The onWillChange API, available since API version 15, is used to display detailed information about the text content to be changed.

// xxx.ets
class ChangeState {
  changeContent: string = "";
  changePreviewOffset: number | undefined = 0;
  changePreviewValue: string | undefined = "";
  changeTextChangeRangeBeforeX: number | undefined = 0;
  changeTextChangeRangeBeforeY: number | undefined = 0;
  changeTextChangeRangeAfterX: number | undefined = 0;
  changeTextChangeRangeAfterY: number | undefined = 0;
  changeTextChangeOldContent: string | undefined = "";
  changeTextChangechangePreviewOffset: number | undefined = 0;
  changeTextChangechangePreviewValue: string | undefined = "";

  SetInfo(info: EditableTextChangeValue) {
    this.changeContent = info.content;
    this.changePreviewOffset = info.previewText?.offset;
    this.changePreviewValue = info.previewText?.value;
    this.changeTextChangeRangeBeforeX = info.options?.rangeBefore.start;
    this.changeTextChangeRangeBeforeY = info.options?.rangeBefore.end;
    this.changeTextChangeRangeAfterX = info.options?.rangeAfter.start;
    this.changeTextChangeRangeAfterY = info.options?.rangeAfter.end;
    this.changeTextChangeOldContent = info.options?.oldContent;
    this.changeTextChangechangePreviewOffset = info.options?.oldPreviewText.offset;
    this.changeTextChangechangePreviewValue = info.options?.oldPreviewText.value;
  }
}

@Entry
@Component
struct SearchExample {
  @State insertValue: string = "";
  @State deleteValue: string = "";
  @State insertOffset: number = 0;
  @State deleteOffset: number = 0;
  @State deleteDirection: number = 0;
  @State changeState1: ChangeState = new ChangeState();
  @State changeState2: ChangeState = new ChangeState();

  build() {
    Row() {
      Column() {
        Search({ value: "Insert callbacks are supported" })
          .height(60)
          .onWillInsert((info: InsertValue) => {
            this.insertValue = info.insertValue;
            return true;
          })
          .onWillChange((info: EditableTextChangeValue) => {
            this.changeState1.SetInfo(info);
            return true;
          })
          .onDidInsert((info: InsertValue) => {
            this.insertOffset = info.insertOffset;
          })

        Text("insertValue:" + this.insertValue + "  insertOffset:" + this.insertOffset).height(20)

        Blank(30)

        Text("context:" + this.changeState1.changeContent).height(20)
        Text("previewText-offset:" + this.changeState1.changePreviewOffset).height(20)
        Text("previewText-value:" + this.changeState1.changePreviewValue).height(20)
        Text("options-rangeBefore-start:" + this.changeState1.changeTextChangeRangeBeforeX).height(20)
        Text("options-rangeBefore-end:" + this.changeState1.changeTextChangeRangeBeforeY).height(20)
        Text("options-rangeAfter-start:" + this.changeState1.changeTextChangeRangeAfterX).height(20)
        Text("options-rangeAfter-end:" + this.changeState1.changeTextChangeRangeAfterY).height(20)
        Text("options-oldContent:" + this.changeState1.changeTextChangeOldContent).height(20)
        Text("options-oldPreviewText-offset:" + this.changeState1.changeTextChangechangePreviewOffset).height(20)
        Text("options-oldPreviewText-value:" + this.changeState1.changeTextChangechangePreviewValue).height(20)

        Search({ value: "Delete callbacks are supported" })
          .height(60)
          .onWillDelete((info: DeleteValue) => {
            this.deleteValue = info.deleteValue;
            this.deleteDirection = info.direction;
            return true;
          })
          .onWillChange((info: EditableTextChangeValue) => {
            this.changeState2.SetInfo(info);
            return true;
          })
          .onDidDelete((info: DeleteValue) => {
            this.deleteOffset = info.deleteOffset;
            this.deleteDirection = info.direction;
          })

        Text("deleteValue:" + this.deleteValue + "  deleteOffset:" + this.deleteOffset).height(20)
        Text("deleteDirection:" + (this.deleteDirection == 0 ? "BACKWARD" : "FORWARD")).height(20)

        Blank(30)

        Text("context:" + this.changeState2.changeContent).height(20)
        Text("previewText-offset:" + this.changeState2.changePreviewOffset).height(20)
        Text("previewText-value:" + this.changeState2.changePreviewValue).height(20)
        Text("options-rangeBefore-start:" + this.changeState2.changeTextChangeRangeBeforeX).height(20)
        Text("options-rangeBefore-end:" + this.changeState2.changeTextChangeRangeBeforeY).height(20)
        Text("options-rangeAfter-start:" + this.changeState2.changeTextChangeRangeAfterX).height(20)
        Text("options-rangeAfter-end:" + this.changeState2.changeTextChangeRangeAfterY).height(20)
        Text("options-oldContent:" + this.changeState2.changeTextChangeOldContent).height(20)
        Text("options-oldPreviewText-offset:" + this.changeState2.changeTextChangechangePreviewOffset).height(20)
        Text("options-oldPreviewText-value:" + this.changeState2.changeTextChangechangePreviewValue).height(20)

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

SearchInsertAndDelete

Example 10: 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 also be configured through the onPrepareMenu callback (available since API version 20).

// xxx.ets
@Entry
@Component
struct SearchExample {
  @State text: string = 'Search 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.AI_WRITER));
    if (targetIndex !== -1) {
      menuItems.splice(targetIndex, 1); // Delete an element at the target index.
    }
    // TextMenuItemId.autoFill is supported since API version 23.
    targetIndex = menuItems.findIndex(item => item.id.equals(TextMenuItemId.autoFill));
    if (targetIndex !== -1) {
      menuItems.splice(targetIndex, 1); // Delete an element at the target index.
    }
    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() {
      Search({ value: this.text })
        .width('95%')
        .editMenuOptions(this.editMenuOptions)
        .margin({ top: 100 })
        .onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
          this.endIndex = selectionEnd;
        })
    }
    .width("90%")
    .margin("5%")
  }
}

searchEditMenuOptions

Example 11: Setting a Custom Symbol-Type Cancel Button

This example demonstrates how to use the searchIcon and cancelButton attributes to customize the style of the symbol-type cancel button on the right side of the text box, available since API version 10.

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

@Entry
@Component
struct SearchExample {
  controller: SearchController = new SearchController();
  @State changeValue: string = '';
  @State submitValue: string = '';

  build() {
    Column() {
      Search({ value: this.changeValue, placeholder: 'Type to search...', controller: this.controller })
        .searchIcon(new SymbolGlyphModifier($r('sys.symbol.magnifyingglass')).fontColor([Color.Red]))
        .cancelButton({
          style: CancelButtonStyle.CONSTANT,
          icon: new SymbolGlyphModifier($r('sys.symbol.xmark')).fontColor([Color.Green])
        })
        .searchButton('SEARCH')
        .width('95%')
        .height(40)
        .backgroundColor('#F5F5F5')
        .placeholderColor(Color.Grey)
        .placeholderFont({ size: 14, weight: 400 })
        .textFont({ size: 14, weight: 400 })
        .margin(10)
    }
    .width('100%')
    .height('100%')
  }
}

searchSymbolGlyphModifierIcon

Example 12: Setting Whether Text is Copyable

This example demonstrates how to set whether text is copyable using the copyOption attribute, available since API version 9.

// xxx.ets

@Entry
@Component
struct SearchExample {
  controller: SearchController = new SearchController();
  @State copyValue: string = '';
  @State cutValue: string = '';

  build() {
    Column({ space: 3 }) {
      Text("copy: " + this.copyValue)
      Text("cut:" + this.cutValue)
      Search({ value: 'Search CopyOption:None', controller: this.controller })
        .width('95%')
        .height(40)
        .copyOption(CopyOptions.None)
        .onCopy((value: string) => {
          this.copyValue = value;
        })
        .onCut((value: string) => {
          this.cutValue = value;
        })
      Search({ value: 'Search CopyOption:InApp', controller: this.controller })
        .width('95%')
        .height(40)
        .copyOption(CopyOptions.InApp)
        .onCopy((value: string) => {
          this.copyValue = value;
        })
        .onCut((value: string) => {
          this.cutValue = value;
        })
      Search({ value: 'Search CopyOption:LocalDevice', controller: this.controller })
        .width('95%')
        .height(40)
        .copyOption(CopyOptions.LocalDevice)
        .onCopy((value: string) => {
          this.copyValue = value;
        })
        .onCut((value: string) => {
          this.cutValue = value;
        })
    }
    .width('100%')
    .height('100%')
  }
}

searchCopyOption

Example 13: Setting the Horizontal Alignment, Caret Style, and Background Color of the Selected Text

This example demonstrates how to set the horizontal alignment, caret style, and background color of the selected text using the textAlign (available since API version 9), caretStyle (available since API version 10), and selectedBackgroundColor (available since API version 12) attributes.

// xxx.ets

@Entry
@Component
struct SearchExample {
  controller: SearchController = new SearchController();

  build() {
    Column({ space: 3 }) {
      Search({ value: 'Search textAlign sample', controller: this.controller })
        .width('95%')
        .height(40)
        .stopBackPress(true)
        .textAlign(TextAlign.Center)
        .caretStyle({ width: 3, color: Color.Green })
        .selectedBackgroundColor(Color.Gray)
    }
    .width('100%')
    .height('100%')
  }
}

searchTextAlign

Example 14: Configuring the Text Box to Receive Default Focus and Bring Up the Soft Keyboard

This example demonstrates how to configure the text box to receive default focus and bring up the soft keyboard using the defaultFocus (available since API version 9) and enableKeyboardOnFocus (available since API version 10) attributes.

// xxx.ets

@Entry
@Component
struct SearchExample {
  controller: SearchController = new SearchController();
  @State value: string = 'false';

  build() {
    Column({ space: 3 }) {
      Text('editing: ' + this.value)
      Search({ placeholder: 'please enter...', controller: this.controller })
        .width('95%')
        .height(40)
        .defaultFocus(true)
        .enableKeyboardOnFocus(true)
        .enablePreviewText(true)
        .enableHapticFeedback(true)
        .onEditChange((data: boolean) => {
          this.value = data ? 'true' : 'false';
        })
    }
    .width('100%')
    .height('100%')
  }
}

searchEnableKeyboardOnFocus

Example 15: Disabling the System Text Selection Menu

This example demonstrates how to disable the system text selection menu by using the selectionMenuHidden attribute, available since API version 10.

// xxx.ets

@Entry
@Component
struct SearchExample {
  controller: SearchController = new SearchController();

  build() {
    Column({ space: 3 }) {
      Search({ value: '123456', controller: this.controller })
        .width('95%')
        .height(40)
        .type(SearchType.NUMBER)
        .selectionMenuHidden(true)
    }
    .width('100%')
    .height('100%')
  }
}

searchSelectionMenuHidden

Example 16: Setting Input Filtering

This example demonstrates how to set input filtering using the inputFilter attribute, available since API version 12.

// xxx.ets

@Entry
@Component
struct SearchExample {
  controller: SearchController = new SearchController();
  @State filterValue: string = '';

  build() {
    Column({ space: 3 }) {
      Text('Filter:' + this.filterValue)
      Search({ placeholder: 'please enter...', controller: this.controller })
        .width('95%')
        .height(40)
        .textIndent(5)
        .halfLeading(true)
        .inputFilter('[a-z]', (filterValue: string) => {
          this.filterValue = filterValue;
        })
    }
    .width('100%')
    .height('100%')
  }
}

searchInputFilter

Example 17: Setting Text Selection for a Specified Region

This example demonstrates how to set text selection for a specified region and the display/hide strategy of the menu using the setTextSelection API, available since API version 12.

// xxx.ets

@Entry
@Component
struct SearchExample {
  controller: SearchController = new SearchController();
  @State startIndex: number = 0;
  @State endIndex: number = 0;

  build() {
    Column({ space: 3 }) {
      Text('Selection start:' + this.startIndex + ' end:' + this.endIndex)
      Search({ value: 'Hello World', controller: this.controller })
        .width('95%')
        .height(40)
        .minFontScale(1)
        .maxFontScale(1.5)
        .defaultFocus(true)
        .onTextSelectionChange((selectionStart: number, selectionEnd: number) => {
          this.startIndex = selectionStart;
          this.endIndex = selectionEnd;
        })

      Button('Selection [0,3]')
        .onClick(() => {
          this.controller.setTextSelection(0, 3, { menuPolicy: MenuPolicy.SHOW });
        })
    }
    .width('100%')
    .height('100%')
  }
}

searchSetTextSelection

Example 18: Handling Text Scrolling Events

This example demonstrates how to set the callback for text scrolling events using the onContentScroll event, available since API version 10.

// xxx.ets

@Entry
@Component
struct SearchExample {
  controller: SearchController = new SearchController();
  @State offsetX: number = 0;
  @State offsetY: number = 0;

  build() {
    Column({ space: 3 }) {
      Text('offset x:' + this.offsetX + ' y:' + this.offsetY)
      Search({ value: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', controller: this.controller })
        .width(200)
        .height(40)
        .onContentScroll((totalOffsetX: number, totalOffsetY: number) => {
          this.offsetX = totalOffsetX;
          this.offsetY = totalOffsetY;
        })
    }
    .width('100%')
    .height('100%')
  }
}

searchOnContentScroll

Example 19: Setting the Minimum and Maximum Font Scale Factors

Since API version 18, minFontScale and maxFontScale are used to set the minimum and maximum font scale factors. When the system font size is adjusted, the text font size remains within the range defined by minFontScale and maxFontScale. The following example demonstrates how the Search component scales its font size according to system font size changes, within different font size limits.

// Enable application font scaling to follow system settings.
// Create a new directory named profile in the following path: AppScope/resources/base.
// Inside the newly created profile directory, create a file named configuration.json.
// Add the following code to the configuration.json file:
{
  "configuration": {
    "fontSizeScale": "followSystem",
    "fontSizeMaxScale": "3.2"
  }
}
// Modify the app.json5 file in AppScope as follows:
{
  "app": {
    "bundleName": "com.example.myapplication",
    "vendor": "example",
    "versionCode": 1000000,
    "versionName": "1.0.0",
    "icon": "$media:app_icon",
    "label": "$string:app_name",
    "configuration": "$profile:configuration"
  }
}
// xxx.ets
@Entry
@Component
struct SearchExample {
  @State minFontScale: number = 1.0;
  @State maxFontScale: number = 1.0;
  @State minFontScale2: number = 0.5;
  @State maxFontScale2: number = 2.0;

  build() {
    Column() {
      Column() {
        Text("System font scales up and down: aaaaaaaAAAAAA")
        Blank(30)
        Text("minFontScale = " + this.minFontScale)
        Text("maxFontScale = " + this.maxFontScale)
        Search({
          placeholder: 'The text area can hold an unlimited amount of text. input your word...',
        })
          .minFontScale(this.minFontScale) // Set the minimum font scale factor. If the parameter is set to undefined, the default scale factor is used.
          .maxFontScale(this.maxFontScale) // Set the maximum font scale factor. If the parameter is set to undefined, the default scale factor is used.

        Blank(30)

        Text("minFontScale = " + this.minFontScale2)
        Text("maxFontScale = " + this.maxFontScale2)
        Search({
          placeholder: 'The text area can hold an unlimited amount of text. input your word...',
        })
          .minFontScale(this.minFontScale2) // Set the minimum font scale factor. If the parameter is set to undefined, the default scale factor is used.
          .maxFontScale(this.maxFontScale2) // Set the maximum font scale factor. If the parameter is set to undefined, the default scale factor is used.
      }.width('100%')
    }
  }
}

Example 20: Setting Text Stroke

This example demonstrates how to set the stroke width and color for text using the strokeWidth and strokeColor attributes, available since API version 20.

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

@Entry
@Component
struct SearchExample {
  build() {
    Row() {
      Column() {
        Text('stroke feature').fontSize(9).fontColor(0xCCCCCC)

        Search({ value: 'Text without stroke' })
          .width('100%')
          .height(60)
          .borderWidth(1)
          .minFontSize(40)
          .maxFontSize(40)
        Search({ value: 'Text with stroke' })
          .width('100%')
          .height(60)
          .borderWidth(1)
          .minFontSize(40)
          .maxFontSize(40)
          .strokeWidth(LengthMetrics.px(-3.0))
          .strokeColor(Color.Red)
        Search({ value: 'Text with stroke' })
          .width('100%')
          .height(60)
          .borderWidth(1)
          .minFontSize(40)
          .maxFontSize(40)
          .strokeWidth(LengthMetrics.px(3.0))
          .strokeColor(Color.Red)
      }.height('90%')
    }
    .width('90%')
    .margin(10)
  }
}

searchSetStroke

Example 21: 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 SearchExample {
  build() {
    Row() {
      Column() {
        Text('Automatic spacing: Enabled').margin(5)
        Search({value: '中文 Text'})
          .enableAutoSpacing(true)
        Text('Automatic spacing: Disabled').margin(5)
        Search({value: '中文Text'})
          .enableAutoSpacing(false)
      }.height('100%')
    }
    .width('60%')
  }
}

searchEnableAutoSpacing

Example 22: Setting the Placeholder Rich Text Style

This example illustrates how to set the placeholder rich text style using the setStyledPlaceholder API, available since API version 22.

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

@Entry
@Component
struct SearchExample {
  styledString: MutableStyledString =
    new MutableStyledString("Text box rich text: Text",
      [
        {
          start: 0,
          length: 7,
          styledKey: StyledStringKey.FONT,
          styledValue: new TextStyle({
            fontColor: Color.Orange,
            fontSize: LengthMetrics.fp(24)
          })
        },
        {
          start: 7,
          length: 4,
          styledKey: StyledStringKey.FONT,
          styledValue: new TextStyle({
            fontColor: Color.Gray,
            fontSize: LengthMetrics.fp(20),
            strokeWidth: LengthMetrics.px(-5),
            strokeColor: Color.Black,
          })
        },
        {
          start: 0,
          length: 1,
          styledKey: StyledStringKey.PARAGRAPH_STYLE,
          styledValue: new ParagraphStyle({
            textVerticalAlign: TextVerticalAlign.CENTER
          })
        }
      ]);
  controller: SearchController = new SearchController();

  aboutToAppear() {
    this.controller.setStyledPlaceholder(this.styledString)
  }

  build() {
    Scroll() {
      Column() {
        Text("Search Placeholder Rich Text"")
          .fontSize(8)
        Search({
          controller: this.controller
        })
          .textFont({ size: 24 })
          .margin(10)
      }
      .width('100%')
    }
  }
}

searchPlaceholder

Example 23: Setting Input Method Extension Information

This example illustrates how to set input method extension information using the setExtraConfig method of IMEClient, available since API version 22.

// xxx.ets
@Entry
@Component
struct SearchExample {
  build() {
    Column() {
      Search({ value: 'Execute onWillAttachIME callback before launching the input method' })
        .onWillAttachIME((client: IMEClient) => {
          client.setExtraConfig({
            customSettings: {
              name: "Search", // Custom property
              id: client.nodeId // Custom Property
            }
          })
        })
    }.height('100%')
  }
}

Example 24: Setting the Color of the Text Box Divider

This example demonstrates how to set the color of the text box divider using the dividerColor API, supported since API version 23.

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

@Entry
@Component
struct SearchExample {
  @State colorTypeRGB: ColorMetrics = ColorMetrics.numeric(0x00FF00);
  @State colorTypeARGB: ColorMetrics = ColorMetrics.numeric(0x3300FF00);
  @State colorTypeColorWithSpace: ColorMetrics = ColorMetrics.colorWithSpace(ColorSpace.DISPLAY_P3, 0, 1.0, 0, 1.0);
  @State colorTypeRGBA: ColorMetrics = ColorMetrics.rgba(255, 0, 0, 1.0);
  // Replace the file with the image resource file you use.
  @State colorTypeRes: ColorMetrics = ColorMetrics.resourceColor($r('app.color.color'));
  @State colorType: ColorMetrics[] =
    [this.colorTypeRGB, this.colorTypeARGB, this.colorTypeColorWithSpace, this.colorTypeRGBA, this.colorTypeRes];
  @State colorTypeName: string[] =
    ["colorTypeRGB", "colorTypeARGB", "colorTypeColorWithSpace", "colorTypeRGBA", "colorTypeRes"];
  @State count: number = 0;

  build() {
    Column() {
      Blank(30)
      Search({ value: "Input search text" })
        .searchButton("SEARCH", { fontSize: '14vp' })
        .dividerColor(this.colorType[this.count])
      Button("Change ColorType: " + this.colorTypeName[this.count]).onClick(() => {
        this.count = (this.count + 1) % (this.colorType.length)
      })
        .fontSize('14vp')
        .width('100%')
    }
  }
}

searchDividerColor

Example 25: 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(){
      Search({ value: "\u300CLeading punctuation compression enabled" })
        .compressLeadingPunctuation(true)
        .margin(5)
        .textFont({size:30})
        .width("90%")
      Search({ value: "\u300CLeading punctuation compression disabled" })
        .compressLeadingPunctuation(false)
        .textFont({size:30})
        .width("90%")
    }
  }
}

searchCompressLeadingPunctuation

Example 26: Setting Adaptative 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() {
      Search({
        value: this.displayText,
        placeholder: 'Enter'
      })
        .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)
  }
}

searchIncludeFontPadding

Example 27: 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 SearchTest {
  build() {
    Column() {
      Search({ value: 'HelloWorld', placeholder: 'please input words' })
        .copyOption(CopyOptions.InApp)
        .width(200)
        .height(50)
        .margin(150)
        .draggable(true)
        .selectedDragPreviewStyle({color: 'rgba(227, 248, 249, 1)'})
    }
    .height('100%')
  }
}

selectedDragPreviewStyle

Example 28: Deleting the Last Character in a Text Box

This example demonstrates how to delete the last character in a text box using the deleteBackward API.

The deleteBackward API is supported since API version 23.

@Entry
@Component
struct Page {
  controller: SearchController = new SearchController();

  build() {
    Column() {
      Search({ placeholder: 'Enter', controller: this.controller })
      Button('Delete backward')
        .onClick(() => {
          this.controller.deleteBackward();
        })
    }
  }
}

searchDeleteBackward

Example 29: 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 SearchExample {
  @State text: string = 'Search text direction example';

  build() {
    Column({ space: 3 }) {
      Text('Search text direction: RTL, component layout direction: default')
        .fontSize(12).width('90%').margin(5)
      Search({ value: this.text })
        .width('95%')
        .height(40)
        .textDirection(TextDirection.RTL)
      Text('Search text direction: RTL, component layout direction: default, horizontal alignment: LEFT')
        .fontSize(12).width('90%').margin(5)
      Search({ value: this.text })
        .width('95%')
        .height(40)
        .textDirection(TextDirection.RTL)
        .textAlign(TextAlign.LEFT)
      Text('Search text direction: LTR, component layout direction: RTL')
        .fontSize(12).width('90%').margin(5)
      Search({ value: this.text })
        .width('95%')
        .height(40)
        .textDirection(TextDirection.LTR)
        .direction(Direction.Rtl)
    }
    .width('100%')
    .height('100%')
  }
}

searchTextDirection

Example 30: Scrolling the Text in a Specified Range to the Visible Area

This example demonstrates how to scroll the text in a specified range to the visible area using the scrollToVisible API.

The scrollToVisible API is supported since API version 23.

// xxx.ets
@Entry
@Component
struct SearchExample {
  @State text: string = '1234567891234567891234😁😁😁6789123456789123456789012121214521';
  controller: SearchController = new SearchController();

  build() {
    Column() {
      Search({ value: this.text, controller: this.controller })
        .width(336)
        .height(56)
      Button("Scroll Text to Visible Area").onClick(()=> {
        this.controller.scrollToVisible({ start: 22, end: 30})
      })
    }.width('100%').height('100%').backgroundColor('#F1F3F5')
  }
}

searchscrolltovisible