• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# TextInput
2
3The **TextInput** component provides single-line text input.
4
5>  **NOTE**
6>
7>  This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
8
9
10## Child Components
11
12Not supported
13
14
15## APIs
16
17TextInput(value?: TextInputOptions)
18
19**Atomic service API**: This API can be used in atomic services since API version 11.
20
21**System capability**: SystemCapability.ArkUI.ArkUI.Full
22
23**Parameters**
24
25| Name| Type| Mandatory| Description|
26| ----- | ----- | ---- | ---- |
27| value | [TextInputOptions](#textinputoptions) | No | Parameters of the **TextInput** component.|
28
29## TextInputOptions
30
31**Atomic service API**: This API can be used in atomic services since API version 11.
32
33**System capability**: SystemCapability.ArkUI.ArkUI.Full
34
35| Name| Type | Mandatory  | Description|
36| ---- | ----- | ---- | ---- |
37| placeholder             | [ResourceStr](ts-types.md#resourcestr)   | No   | Text displayed when there is no input.                            |
38| text                    | [ResourceStr](ts-types.md#resourcestr)   | No   | Current text input.<br>You are advised to bind the state variable to the text in real time through the **onChange** event,<br>so as to prevent display errors when the component is updated.<br>Since API version 10, this parameter supports two-way binding through [$$](../../../quick-start/arkts-two-way-sync.md).<br>Since API version 18, this parameter supports two-way binding through [!!](../../../quick-start/arkts-new-binding.md#two-way-binding-between-built-in-component-parameters).|
39| controller<sup>8+</sup> | [TextInputController](#textinputcontroller8) | No   | Text input controller.                         |
40
41## Attributes
42
43In addition to the [universal attributes](ts-component-general-attributes.md), the following attributes are supported.
44
45>  **NOTE**
46>
47>  When no underline is set, the default value of the universal attribute [padding](ts-universal-attributes-size.md#padding) is as follows:<br>{<br> top: '8vp',<br> right: '16vp',<br> bottom: '8vp',<br> left: '16vp'<br> }
48>
49>  When an underline is set, the default value of **padding** is as follows:<br>{<br> top: '12vp',<br> right: '0vp',<br> bottom: '12vp',<br> left: '0vp'<br> }
50>
51>  When **padding** is set to **0**, set **borderRadius** to **0** to avoid truncation of the cursor.
52>
53>  Since API version 10, **.width('auto')** can be set for the **TextInput** component. Under this setting, the component auto-adapts its width to the text width, while respecting the **constraintSize** configuration and the maximum and minimum width restrictions imposed by the parent container. For details, see [Size](ts-universal-attributes-size.md).
54
55### type
56
57type(value: InputType)
58
59Sets the text box type.
60
61**Atomic service API**: This API can be used in atomic services since API version 11.
62
63**System capability**: SystemCapability.ArkUI.ArkUI.Full
64
65**Parameters**
66
67| Name| Type                           | Mandatory| Description                                     |
68| ------ | ------------------------------- | ---- | ----------------------------------------- |
69| value  | [InputType](#inputtype) | Yes  | Text box type.<br>Default value: **InputType.Normal**|
70
71### placeholderColor
72
73placeholderColor(value: ResourceColor)
74
75Sets the placeholder text color.
76
77The default value on wearable devices is **'#99ffffff'**.
78
79**Atomic service API**: This API can be used in atomic services since API version 11.
80
81**System capability**: SystemCapability.ArkUI.ArkUI.Full
82
83**Parameters**
84
85| Name| Type                                      | Mandatory| Description                                        |
86| ------ | ------------------------------------------ | ---- | -------------------------------------------- |
87| value  | [ResourceColor](ts-types.md#resourcecolor) | Yes  | Placeholder text color.<br>The default value follows the theme.|
88
89### placeholderFont
90
91placeholderFont(value?: Font)
92
93Sets the placeholder text style, including the font size, font width, font family, and font style. The 'HarmonyOS Sans' font and [registered custom fonts](../js-apis-font.md) are supported.
94
95The default value on wearable devices is **18fp**.
96
97**Atomic service API**: This API can be used in atomic services since API version 11.
98
99**System capability**: SystemCapability.ArkUI.ArkUI.Full
100
101**Parameters**
102
103| Name| Type                    | Mandatory| Description                 |
104| ------ | ------------------------ | ---- | --------------------- |
105| value  | [Font](ts-types.md#font) | No  | Placeholder text style.|
106
107### enterKeyType
108
109enterKeyType(value: EnterKeyType)
110
111Sets the type of the Enter key.
112
113**Atomic service API**: This API can be used in atomic services since API version 11.
114
115**System capability**: SystemCapability.ArkUI.ArkUI.Full
116
117**Parameters**
118
119| Name| Type                                            | Mandatory| Description                                            |
120| ------ | ------------------------------------------------ | ---- | ------------------------------------------------ |
121| value  | [EnterKeyType](#enterkeytype) | Yes  | Type of the Enter key.<br>Default value: **EnterKeyType.Done**|
122
123### caretColor
124
125caretColor(value: ResourceColor)
126
127Sets the color of the caret in the text box.
128
129**Atomic service API**: This API can be used in atomic services since API version 11.
130
131**System capability**: SystemCapability.ArkUI.ArkUI.Full
132
133**Parameters**
134
135| Name| Type                                      | Mandatory| Description                                  |
136| ------ | ------------------------------------------ | ---- | -------------------------------------- |
137| value  | [ResourceColor](ts-types.md#resourcecolor) | Yes  | Color of the caret in the text box.<br>Default value: **'#007DFF'**|
138
139>  **NOTE**
140>
141>  Since API version 12, this API can be used to set the text handle color, which is the same as the caret color.
142
143### maxLength
144
145maxLength(value: number)
146
147Sets the maximum number of characters for text input.
148
149**Atomic service API**: This API can be used in atomic services since API version 11.
150
151**System capability**: SystemCapability.ArkUI.ArkUI.Full
152
153**Parameters**
154
155| Name| Type  | Mandatory| Description                                                        |
156| ------ | ------ | ---- | ------------------------------------------------------------ |
157| value  | number | Yes  | Maximum number of characters for text input.<br>Default value: **Infinity**, indicating that there is no upper limit on the number of characters that can be entered<br>**NOTE**<br>If this attribute is not set or is set to an invalid value, the default value is used. If a decimal number is specified, the integer part is used.|
158
159### fontColor
160
161fontColor(value: ResourceColor)
162
163Sets the font color.
164
165The default value on wearable devices is **'#dbffffff'**.
166
167**Atomic service API**: This API can be used in atomic services since API version 11.
168
169**System capability**: SystemCapability.ArkUI.ArkUI.Full
170
171**Parameters**
172
173| Name| Type                                      | Mandatory| Description      |
174| ------ | ------------------------------------------ | ---- | ---------- |
175| value  | [ResourceColor](ts-types.md#resourcecolor) | Yes  | Font color.|
176
177### fontSize
178
179fontSize(value: Length)
180
181Sets the font size.
182
183The default value on wearable devices is **18fp**.
184
185**Atomic service API**: This API can be used in atomic services since API version 11.
186
187**System capability**: SystemCapability.ArkUI.ArkUI.Full
188
189**Parameters**
190
191| Name| Type                        | Mandatory| Description                                                        |
192| ------ | ---------------------------- | ---- | ------------------------------------------------------------ |
193| value  | [Length](ts-types.md#length) | Yes  | Font size. If **fontSize** is of the number type, the unit fp is used. The default font size is 16 fp. The value cannot be a percentage.|
194
195### fontStyle
196
197fontStyle(value: FontStyle)
198
199Sets the font style.
200
201**Atomic service API**: This API can be used in atomic services since API version 11.
202
203**System capability**: SystemCapability.ArkUI.ArkUI.Full
204
205**Parameters**
206
207| Name| Type                                       | Mandatory| Description                                   |
208| ------ | ------------------------------------------- | ---- | --------------------------------------- |
209| value  | [FontStyle](ts-appendix-enums.md#fontstyle) | Yes  | Font style.<br>Default value: **FontStyle.Normal**|
210
211### fontWeight
212
213fontWeight(value: number | FontWeight | string)
214
215Sets the font weight. If the value is too large, the text may be clipped depending on the font.
216
217**Atomic service API**: This API can be used in atomic services since API version 11.
218
219**System capability**: SystemCapability.ArkUI.ArkUI.Full
220
221**Parameters**
222
223| Name| Type                                                        | Mandatory| Description                                                        |
224| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
225| value  | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Yes  | Font weight. For the number type, the value range is [100, 900], at an interval of 100. The default value is **400**. A larger value indicates a heavier font weight. For the string type, only strings that represent a number, for example, **"400"**, and the following enumerated values of **FontWeight** are supported: **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**.<br>Default value: **FontWeight.Normal**|
226
227### fontFamily
228
229fontFamily(value: ResourceStr)
230
231Sets the font family.
232
233**Atomic service API**: This API can be used in atomic services since API version 11.
234
235**System capability**: SystemCapability.ArkUI.ArkUI.Full
236
237**Parameters**
238
239| Name| Type                                  | Mandatory| Description                                                        |
240| ------ | -------------------------------------- | ---- | ------------------------------------------------------------ |
241| value  | [ResourceStr](ts-types.md#resourcestr) | Yes  | Font family. Default font: **'HarmonyOS Sans'**<br>The 'HarmonyOS Sans' font and [registered custom fonts](../js-apis-font.md) are supported for applications.<br>Only the 'HarmonyOS Sans' font is supported for widgets.|
242
243### inputFilter<sup>8+</sup>
244
245inputFilter(value: ResourceStr, error?: Callback\<string>)
246
247Sets the regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified regular expression can match single characters, but not strings.
248
249Since API version 11, 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.
250
251**Atomic service API**: This API can be used in atomic services since API version 11.
252
253**System capability**: SystemCapability.ArkUI.ArkUI.Full
254
255**Parameters**
256
257| Name| Type                                  | Mandatory| Description                              |
258| ------ | -------------------------------------- | ---- | ---------------------------------- |
259| value  | [ResourceStr](ts-types.md#resourcestr) | Yes  | Regular expression.                      |
260| error  | Callback\<string>                | No  | Filtered-out content to return when regular expression matching fails.|
261
262### copyOption<sup>9+</sup>
263
264copyOption(value: CopyOptions)
265
266Sets whether copy and paste is allowed. If this attribute is set to **CopyOptions.None**, the text can only be pasted; all other actions, such as copying, cutting, and sharing, are disabled.
267
268Dragging is not allowed when **CopyOptions.None** is set.
269
270**Atomic service API**: This API can be used in atomic services since API version 11.
271
272**System capability**: SystemCapability.ArkUI.ArkUI.Full
273
274**Parameters**
275
276| Name| Type                                            | Mandatory| Description                                                        |
277| ------ | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
278| value  | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Yes  | Whether copy and paste is allowed.<br>Default value: **CopyOptions.LocalDevice**|
279
280### showPasswordIcon<sup>9+</sup>
281
282showPasswordIcon(value: boolean)
283
284Sets whether to display the password icon at the end of the password text box.
285
286**Atomic service API**: This API can be used in atomic services since API version 11.
287
288**System capability**: SystemCapability.ArkUI.ArkUI.Full
289
290**Parameters**
291
292| Name| Type   | Mandatory| Description                                                       |
293| ------ | ------- | ---- | ----------------------------------------------------------- |
294| value  | boolean | Yes  | Whether to display the password icon at the end of the password text box.<br>Default value: **true**|
295
296### style<sup>9+</sup>
297
298style(value: TextInputStyle  | TextContentStyle)
299
300Sets the text input style. The inline input style only supports **InputType.Normal**.
301
302**Atomic service API**: This API can be used in atomic services since API version 11.
303
304**System capability**: SystemCapability.ArkUI.ArkUI.Full
305
306**Parameters**
307
308| Name| Type                                                        | Mandatory| Description                                                        |
309| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
310| value  | [TextInputStyle](#textinputstyle9) \| [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Yes  | Text input style.<br>Default value: **TextInputStyle.Default**|
311
312### textAlign<sup>9+</sup>
313
314textAlign(value: TextAlign)
315
316Sets the horizontal alignment of the text.
317
318Available options are **TextAlign.Start**, **TextAlign.Center**, and **TextAlign.End**.
319
320To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text.
321
322**Atomic service API**: This API can be used in atomic services since API version 11.
323
324**System capability**: SystemCapability.ArkUI.ArkUI.Full
325
326**Parameters**
327
328| Name| Type                                       | Mandatory| Description                                                      |
329| ------ | ------------------------------------------- | ---- | ---------------------------------------------------------- |
330| value  | [TextAlign](ts-appendix-enums.md#textalign) | Yes  | Horizontal alignment of the text.<br>Default value: **TextAlign.Start**|
331
332### selectedBackgroundColor<sup>10+</sup>
333
334selectedBackgroundColor(value: ResourceColor)
335
336Sets the background color of the selected text. If the opacity is not set, a 20% opacity will be used.
337
338**Atomic service API**: This API can be used in atomic services since API version 11.
339
340**System capability**: SystemCapability.ArkUI.ArkUI.Full
341
342**Parameters**
343
344| Name| Type                                      | Mandatory| Description                                      |
345| ------ | ------------------------------------------ | ---- | ------------------------------------------ |
346| value  | [ResourceColor](ts-types.md#resourcecolor) | Yes  | Background color of the selected text.<br>By default, a 20% opacity is applied.|
347
348### caretStyle<sup>10+</sup>
349
350caretStyle(value: CaretStyle)
351
352Sets the caret style.
353
354**Atomic service API**: This API can be used in atomic services since API version 11.
355
356**System capability**: SystemCapability.ArkUI.ArkUI.Full
357
358**Parameters**
359
360| Name| Type                               | Mandatory| Description        |
361| ------ | ----------------------------------- | ---- | ------------ |
362| value  | [CaretStyle](ts-text-common.md#caretstyle10) | Yes  | Caret style.|
363
364### caretPosition<sup>10+</sup>
365
366caretPosition(value: number)
367
368Sets the caret position.
369
370**Atomic service API**: This API can be used in atomic services since API version 11.
371
372**System capability**: SystemCapability.ArkUI.ArkUI.Full
373
374**Parameters**
375
376| Name| Type  | Mandatory| Description        |
377| ------ | ------ | ---- | ------------ |
378| value  | number | Yes  | Caret position.|
379
380### showUnit<sup>10+</sup>
381
382showUnit(value: CustomBuilder)
383
384Sets the unit displayed with the text box. This attribute effective only when [showUnderline](#showunderline10) is set to **true**.
385
386**Atomic service API**: This API can be used in atomic services since API version 11.
387
388**System capability**: SystemCapability.ArkUI.ArkUI.Full
389
390**Parameters**
391
392| Name| Type                                       | Mandatory| Description                          |
393| ------ | ------------------------------------------- | ---- | ------------------------------ |
394| value  | [CustomBuilder](ts-types.md#custombuilder8) | Yes  | Unit displayed with the text box.|
395
396### showError<sup>10+</sup>
397
398showError(value?: ResourceStr | undefined)
399
400Sets the error message displayed when an error occurs.
401
402On wearable devices, the error message is displayed at a font size of 13 fp and center-aligned.
403
404If the data type is **ResourceStr** and the input content does not comply with specifications, the error message is displayed. If the error message does not fit in one line, an ellipsis (…) is displayed to represent clipped text. If the data type is **undefined**, no error message is displayed. For details, see [Example 2](#example-2-setting-underlines).
405
406**Atomic service API**: This API can be used in atomic services since API version 11.
407
408**System capability**: SystemCapability.ArkUI.ArkUI.Full
409
410**Parameters**
411
412| Name| Type                         | Mandatory| Description                                                        |
413| ------ | ----------------------------- | ---- | ------------------------------------------------------------ |
414| value  | [ResourceStr](ts-types.md#resourcestr) \| undefined | No  | Error message displayed when an error occurs.<br>By default, no error message is displayed.<br>**NOTE**<br>The Resource type is supported since API version 12.|
415
416### showUnderline<sup>10+</sup>
417
418showUnderline(value: boolean)
419
420Sets whether to show an underline. By default, the underline comes in the color of **'#33182431'**, thickness of 1 px, and text box size of 48 vp. The underline is only available for the **InputType.Normal** type.
421
422**Atomic service API**: This API can be used in atomic services since API version 11.
423
424**System capability**: SystemCapability.ArkUI.ArkUI.Full
425
426**Parameters**
427
428| Name| Type   | Mandatory| Description                              |
429| ------ | ------- | ---- | ---------------------------------- |
430| value  | boolean | Yes  | Whether to show an underline.<br>Default value: **false**|
431
432### passwordIcon<sup>10+</sup>
433
434passwordIcon(value: PasswordIcon)
435
436Sets the password icon to display at the end of the password text box.
437
438Images in JPG, PNG, BMP, HEIC, and WEBP formats are supported.
439
440The icon size is fixed at 24 vp (or 28 vp on wearable devices), regardless of the source image size.
441
442**Atomic service API**: This API can be used in atomic services since API version 11.
443
444**System capability**: SystemCapability.ArkUI.ArkUI.Full
445
446**Parameters**
447
448| Name| Type                                   | Mandatory| Description                                                        |
449| ------ | --------------------------------------- | ---- | ------------------------------------------------------------ |
450| value  | [PasswordIcon](#passwordicon10) | Yes  | Password icon to display at the end of the password text box.<br>By default, the system-provided icon is used.|
451
452### enableKeyboardOnFocus<sup>10+</sup>
453
454enableKeyboardOnFocus(value: boolean)
455
456Sets whether to enable the input method when the **TextInput** component obtains focus in a way other than clicking.
457
458Since API version 10, the **TextInput** component brings up the keyboard by default when it obtains focus.
459
460**Atomic service API**: This API can be used in atomic services since API version 11.
461
462**System capability**: SystemCapability.ArkUI.ArkUI.Full
463
464**Parameters**
465
466| Name| Type   | Mandatory| Description                                                       |
467| ------ | ------- | ---- | ----------------------------------------------------------- |
468| value  | boolean | Yes  | Whether to enable the input method when the **TextInput** component obtains focus in a way other than clicking.<br>Default value: **true**|
469
470### selectionMenuHidden<sup>10+</sup>
471
472selectionMenuHidden(value: boolean)
473
474Sets whether to hide the system text selection menu.
475
476**Atomic service API**: This API can be used in atomic services since API version 11.
477
478**System capability**: SystemCapability.ArkUI.ArkUI.Full
479
480**Parameters**
481
482| Name| Type   | Mandatory| Description                                                        |
483| ------ | ------- | ---- | ------------------------------------------------------------ |
484| value  | boolean | Yes  | Whether to hide the system text selection menu.<br>**true**: The system text selection menu does not appear under the following circumstances: clicking the text box cursor, long-pressing the text box, double-tapping the text box, triple-tapping the text box, or right-clicking the text box.<br>**false**: The system text selection menu appears under the following circumstances: clicking the text box cursor, long-pressing the text box, double-tapping the text box, triple-tapping the text box, or right-clicking the text box.<br>Default value: **false**|
485
486### barState<sup>10+</sup>
487
488barState(value: BarState)
489
490Sets the scrollbar state when the inline input style is used.
491
492**Atomic service API**: This API can be used in atomic services since API version 11.
493
494**System capability**: SystemCapability.ArkUI.ArkUI.Full
495
496**Parameters**
497
498| Name| Type                                     | Mandatory| Description                                                        |
499| ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ |
500| value  | [BarState](ts-appendix-enums.md#barstate) | Yes  | Scrollbar state when the inline input style is used.<br>Default value: **BarState.Auto**|
501
502### maxLines<sup>10+</sup>
503
504maxLines(value: number)
505
506Sets the maximum number of lines that can be displayed when the inline input style is used.
507
508**Atomic service API**: This API can be used in atomic services since API version 11.
509
510**System capability**: SystemCapability.ArkUI.ArkUI.Full
511
512**Parameters**
513
514| Name| Type                                     | Mandatory| Description                                                        |
515| ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ |
516| value  | number | Yes  | Maximum number of lines that can be displayed with the inline style in the editing state or with the non-inline style.<br>Default value: **3**<br>Value range: (0, +∞)|
517
518### customKeyboard<sup>10+</sup>
519
520customKeyboard(value: CustomBuilder, options?: KeyboardOptions)
521
522Sets a custom keyboard.
523
524When a custom keyboard is set, activating the text box opens the specified custom component, instead of the system input method.
525
526The 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.
527
528The custom keyboard is presented by overlaying the original screen, which is not compressed or lifted if avoid mode is not enabled or avoidance is not needed for the text box.
529
530The custom keyboard cannot obtain the focus, but it blocks gesture events.
531
532By default, the custom keyboard is closed when the input component loses the focus. You can also use the [TextInputController](#textinputcontroller8).[stopEditing](#stopediting10) API to close the keyboard.
533
534When a custom keyboard is set, the text box does not support camera input, even when the device supports.
535
536When setting a custom keyboard, you can bind the [onKeyPrelme](ts-universal-events-key.md#onkeypreime12) event to prevent input from the physical keyboard.
537
538**Atomic service API**: This API can be used in atomic services since API version 11.
539
540**System capability**: SystemCapability.ArkUI.ArkUI.Full
541
542**Parameters**
543
544| Name               | Type                                       | Mandatory| Description                                                        |
545| --------------------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
546| value                 | [CustomBuilder](ts-types.md#custombuilder8) | Yes  | Custom keyboard.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
547| options<sup>12+</sup> | [KeyboardOptions](ts-basic-components-richeditor.md#keyboardoptions12)       | No  | Whether to support keyboard avoidance.                            |
548
549### enableAutoFill<sup>11+</sup>
550
551enableAutoFill(value: boolean)
552
553Sets whether to enable autofill.
554
555**Atomic service API**: This API can be used in atomic services since API version 12.
556
557**System capability**: SystemCapability.ArkUI.ArkUI.Full
558
559**Parameters**
560
561| Name| Type   | Mandatory| Description                                                        |
562| ------ | ------- | ---- | ------------------------------------------------------------ |
563| value  | boolean | Yes  | Whether to enable autofill.<br>**true**: enable<br>**false**: disable<br><br>Default value: **true**|
564
565### passwordRules<sup>11+</sup>
566
567passwordRules(value: string)
568
569Rules for generating passwords. When autofill is used, these rules are transparently transmitted to Password Vault for generating a new password.<!--RP1--><!--RP1End-->
570
571**Atomic service API**: This API can be used in atomic services since API version 12.
572
573**System capability**: SystemCapability.ArkUI.ArkUI.Full
574
575**Parameters**
576
577| Name| Type  | Mandatory| Description                |
578| ------ | ------ | ---- | -------------------- |
579| value  | string | Yes  | Rules for generating passwords.|
580
581### cancelButton<sup>11+</sup>
582
583cancelButton(options: CancelButtonOptions)
584
585Sets the style of the cancel button on the right. This attribute is not available for the inline input style.
586
587The default value is **28fp** on wearable devices.
588
589**Atomic service API**: This API can be used in atomic services since API version 12.
590
591**System capability**: SystemCapability.ArkUI.ArkUI.Full
592
593**Parameters**
594
595| Name| Type                                                        | Mandatory| Description                                                        |
596| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
597| options  | [CancelButtonOptions](ts-basic-components-search.md#cancelbuttonoptions12) | Yes  | Options of the cancel button on the right.<br>Default value:<br>{<br>style: CancelButtonStyle.INPUT<br>} |
598
599### selectAll<sup>11+</sup>
600
601selectAll(value: boolean)
602
603Sets whether to select all text in the initial state. This attribute is not available for the inline input style.
604
605**Atomic service API**: This API can be used in atomic services since API version 12.
606
607**System capability**: SystemCapability.ArkUI.ArkUI.Full
608
609**Parameters**
610
611| Name| Type   | Mandatory| Description                             |
612| ------ | ------- | ---- | --------------------------------- |
613| value  | boolean | Yes  | Whether to select all text in the initial state.<br>Default value: **false**|
614
615### showCounter<sup>11+</sup>
616
617showCounter(value: boolean, options?: InputCounterOptions)
618
619Sets the character counter displayed when the number of characters entered exceeds the threshold.
620
621**options** can be set only when **value** is set to **true**, in which case a character counter is displayed below the text box. This attribute must be used together with **maxLength**. The character counter is displayed in this format: Number of characters entered/Character limit.
622
623It is visible when the number of characters entered is greater than the character limit multiplied by the threshold percentage value. If **options** is not set, the text box border and character counter subscript turn red when the number of characters entered exceeds the limit. If **value** is set to **true** and **options** is set, the text box border and character counter subscript turn red and the text box shakes when the number of characters entered reaches the limit, provided that the value of **thresholdPercentage** is valid. If **highlightBorder** is set to **false**, the text box border does not turn red. By default, **highlightBorder** is set to **true**.
624
625The character counter is not displayed for text boxes in inline or password input style.
626
627**Atomic service API**: This API can be used in atomic services since API version 11.
628
629**System capability**: SystemCapability.ArkUI.ArkUI.Full
630
631**Parameters**
632
633| Name               | Type                                                 | Mandatory| Description            |
634| --------------------- | ----------------------------------------------------- | ---- | ---------------- |
635| value                 | boolean                                               | Yes  | Whether to display the character counter.|
636| options<sup>11+</sup> | [InputCounterOptions](ts-types.md#inputcounteroptions11) | No  | Threshold percentage of the character counter.|
637
638### contentType<sup>12+</sup>
639
640contentType(value: ContentType)
641
642Sets the content type for autofill.
643
644**Atomic service API**: This API can be used in atomic services since API version 12.
645
646**System capability**: SystemCapability.ArkUI.ArkUI.Full
647
648**Parameters**
649
650| Name| Type                                 | Mandatory| Description          |
651| ------ | ------------------------------------- | ---- | -------------- |
652| value  | [ContentType](#contenttype12-1) | Yes  | Content type for autofill.|
653
654### underlineColor<sup>12+</sup>
655
656underlineColor(value: ResourceColor|UnderlineColor|undefined)
657
658Sets the color of the underline when it is shown.
659
660**Atomic service API**: This API can be used in atomic services since API version 12.
661
662**System capability**: SystemCapability.ArkUI.ArkUI.Full
663
664| Name| Type                                                        | Mandatory| Description                                                        |
665| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
666| value  | [ResourceColor](ts-types.md#resourcecolor) \| [UnderlineColor](#underlinecolor12) \| undefined | Yes  | Color of the underline.<br>The underline color changes with the underline mode. If the underline color is only set for the normal state, you can directly enter a value of the ResourceColor type. If the value specified is **undefined**, **null**, or invalid, all underlines are restored to the default value.<br>Default value: underline color configured for the theme, which is **#33182431** by default|
667
668### lineHeight<sup>12+</sup>
669
670lineHeight(value: number | string | Resource)
671
672Sets the text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value is of the number type, the unit fp is used. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported.
673
674**Atomic service API**: This API can be used in atomic services since API version 12.
675
676**System capability**: SystemCapability.ArkUI.ArkUI.Full
677
678**Parameters**
679
680| Name| Type                                                        | Mandatory| Description            |
681| ------ | ------------------------------------------------------------ | ---- | ---------------- |
682| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Text line height.|
683
684### decoration<sup>12+</sup>
685
686decoration(value: TextDecorationOptions)
687
688Sets the color, type, and style of the text decorative line. This attribute does not take effect for the password input mode.
689
690**Atomic service API**: This API can be used in atomic services since API version 12.
691
692**System capability**: SystemCapability.ArkUI.ArkUI.Full
693
694**Parameters**
695
696| Name| Type                                                        | Mandatory| Description                                                        |
697| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
698| value  | [TextDecorationOptions](ts-types.md#textdecorationoptions12) | Yes  | Text decorative line options.<br>Default value: {<br> type: TextDecorationType.None,<br> color: Color.Black,<br> style: TextDecorationStyle.SOLID <br>} |
699
700### letterSpacing<sup>12+</sup>
701
702letterSpacing(value: number | string | Resource)
703
704Sets 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.
705
706If 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.
707
708**Atomic service API**: This API can be used in atomic services since API version 12.
709
710**System capability**: SystemCapability.ArkUI.ArkUI.Full
711
712**Parameters**
713
714| Name| Type                      | Mandatory| Description          |
715| ------ | -------------------------- | ---- | -------------- |
716| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Letter spacing.<br>Unit: fp|
717
718### fontFeature<sup>12+</sup>
719
720fontFeature(value: string)
721
722Sets the font feature, for example, monospaced digits.
723
724Format: normal \| \<feature-tag-value\>
725
726Format of **\<feature-tag-value\>**: \<string\> \[ \<integer\> \| on \| off ]
727
728There can be multiple **\<feature-tag-value\>** values, which are separated by commas (,).
729
730For example, the input format for monospaced clock fonts is "ss01" on.
731
732**Atomic service API**: This API can be used in atomic services since API version 12.
733
734**System capability**: SystemCapability.ArkUI.ArkUI.Full
735
736**Parameters**
737
738| Name| Type  | Mandatory| Description          |
739| ------ | ------ | ---- | -------------- |
740| value  | string | Yes  | Font feature.|
741
742For details about the supported font features, see [Font Feature List](ts-basic-components-text.md#fontfeature12).
743Font 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.
744For more information about the font features, see [Low-level font feature settings control: the font-feature-settings property](https://www.w3.org/TR/css-fonts-3/#font-feature-settings-prop) and [The Complete CSS Demo for OpenType Features](https://sparanoid.com/lab/opentype-features/).
745
746>  **NOTE**
747>
748>  This attribute is not available when **type** is set to an enum value that indicates the password input mode, such as Password, **NEW_PASSWORD**, or **NUMBER_PASSWORD**.
749
750### wordBreak<sup>12+</sup>
751
752wordBreak(value: WordBreak)
753
754Sets the word break rule. This attribute is effective for the inline input style, but does not apply to the placeholder text.
755
756**Atomic service API**: This API can be used in atomic services since API version 12.
757
758**System capability**: SystemCapability.ArkUI.ArkUI.Full
759
760**Parameters**
761
762| Name| Type                                         | Mandatory| Description                                         |
763| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
764| value  | [WordBreak](ts-appendix-enums.md#wordbreak11) | Yes  | Word break rule in the inline input style.<br>Default value: **WordBreak.BREAK_WORD**|
765
766>  **NOTE**
767>
768>  The component does not support the **clip** attribute. Therefore, setting this attribute does not affect text clipping.
769
770### textOverflow<sup>12+</sup>
771
772textOverflow(value: TextOverflow)
773
774Sets the display mode when the text is too long. This attribute is only available for the inline input style.
775
776Text is clipped at the transition between words. To clip text in the middle of a word, set **wordBreak** to **WordBreak.BREAK_ALL**.
777
778**TextOverflow.None** produces the same effect as **TextOverflow.Clip**.
779
780**Atomic service API**: This API can be used in atomic services since API version 12.
781
782**System capability**: SystemCapability.ArkUI.ArkUI.Full
783
784**Parameters**
785
786| Name| Type                                                         | Mandatory| Description                                                                                               |
787| ------ | ------------------------------------------------------------ | ---- | -------------------------------------------------------------------------------------------------- |
788| value  | [TextOverflow](ts-appendix-enums.md#textoverflow)            | Yes  | Display mode when the text is too long.<br>Default value in non-editing state in the inline input style: **TextOverflow.Ellipsis**<br>Default value in editing state in the inline input style: **TextOverflow.Clip**                    |
789
790>  **NOTE**
791>
792>  The **TextInput** component does not support the **TextOverflow.MARQUEE** mode. If **TextOverflow.MARQUEE** is set, the component automatically switches to **TextOverflow.Ellipsis** for the non-editing state in the inline input style and **TextOverflow.Clip** for the non-inline input style and the editing state in the inline input style.
793
794### textIndent<sup>12+</sup>
795
796textIndent(value: Dimension)
797
798Sets the indent of the first line text.
799
800**Atomic service API**: This API can be used in atomic services since API version 12.
801
802**System capability**: SystemCapability.ArkUI.ArkUI.Full
803
804**Parameters**
805
806| Name| Type                                 | Mandatory| Description                        |
807| ------ | ------------------------------------ | ---- | ---------------------------- |
808| value  | [Dimension](ts-types.md#dimension10) | Yes  | Indent of the first line text.<br>Default value: **0**|
809
810### minFontSize<sup>12+</sup>
811
812minFontSize(value: number | string | Resource)
813
814Sets the minimum font size. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported.
815
816For the setting to take effect, this attribute must be used together with [maxFontSize](#maxfontsize12) and [maxLines](#maxlines10) (when the component is in editing state in the inline input style), or layout constraint settings.
817
818When the adaptive font size is used, the **fontSize** settings do not take effect.
819
820**Atomic service API**: This API can be used in atomic services since API version 12.
821
822**System capability**: SystemCapability.ArkUI.ArkUI.Full
823
824**Parameters**
825
826| Name| Type                                                        | Mandatory| Description              |
827| ------ | ------------------------------------------------------------ | ---- | ------------------ |
828| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Minimum font size.<br>Unit: fp|
829
830### maxFontSize<sup>12+</sup>
831
832maxFontSize(value: number | string | Resource)
833
834Sets the maximum font size. For the string type, numeric string values with optional units, for example, **"10"** or **"10fp"**, are supported.
835
836For the setting to take effect, this attribute must be used together with [minFontSize](#minfontsize12) and [maxLines](#maxlines10) (when the component is in editing state in the inline input style), or layout constraint settings.
837
838When the adaptive font size is used, the **fontSize** settings do not take effect.
839
840**Atomic service API**: This API can be used in atomic services since API version 12.
841
842**System capability**: SystemCapability.ArkUI.ArkUI.Full
843
844**Parameters**
845
846| Name| Type                                                        | Mandatory| Description              |
847| ------ | ------------------------------------------------------------ | ---- | ------------------ |
848| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Maximum font size.<br>Unit: fp|
849
850### heightAdaptivePolicy<sup>12+</sup>
851
852heightAdaptivePolicy(value: TextHeightAdaptivePolicy)
853
854Sets how the adaptive height is determined for the text in the inline input style.
855
856When this attribute is set to **TextHeightAdaptivePolicy.MAX_LINES_FIRST**, the [maxLines](#maxlines10) attribute takes precedence for adjusting the text height. If the **maxLines** setting results in a layout beyond the layout constraints, the text will shrink to a font size between [minFontSize](#minfontsize12) and [maxFontSize](#maxfontsize12) to allow for more content to be shown.
857
858If this attribute is set to **TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST**, the **minFontSize** attribute takes precedence for adjusting the text height. If the text can fit in one line with the **minFontSize** setting, the text will enlarge to the largest possible font size between **minFontSize** and **maxFontSize**.
859
860**TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST** produces the same effect as **TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST**.
861
862When the component is in the non-inline input style, the three values of **TextHeightAdaptivePolicy** have the same effect, that is, the text will shrink to a font size between **minFontSize** and **maxFontSize** to allow for more content to be shown.
863
864>  **NOTE**
865>
866>  If the text box is in inline input style, the font size in the editing state is different from that in the non-editing state.
867
868**Atomic service API**: This API can be used in atomic services since API version 12.
869
870**System capability**: SystemCapability.ArkUI.ArkUI.Full
871
872**Parameters**
873
874| Name| Type                                                        | Mandatory| Description                                                        |
875| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
876| value  | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | Yes  | How the adaptive height is determined for the text.<br>Default value: **TextHeightAdaptivePolicy.MAX_LINES_FIRST**|
877
878### showPassword<sup>12+</sup>
879
880showPassword(visible: boolean)
881
882Sets whether to show the password.
883
884This API has effect only when the [input type](#inputtype) is set to **Password**, **NEWPASSWORD**, or **NUMBERPASSWORD** mode. It does not work in other modes.
885
886When in password mode, there may be inconsistency between the backend state of the text box and the frontend application's state management variables. This can cause issues with the icon at the end of the password text box. To avoid such issues, use the [onSecurityStateChange](#onsecuritystatechange12) callback to sync the states. For details, see [Example 1](#example-1-setting-and-obtaining-the-cursor-position).
887
888**Atomic service API**: This API can be used in atomic services since API version 12.
889
890**System capability**: SystemCapability.ArkUI.ArkUI.Full
891
892**Parameters**
893
894| Name| Type                                                        | Mandatory| Description                                                        |
895| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
896| visible  | boolean | Yes | Whether to show the password.<br>Default value: **false**|
897
898### lineBreakStrategy<sup>12+</sup>
899
900lineBreakStrategy(strategy: LineBreakStrategy)
901
902Sets the line break rule. This attribute takes effect when **wordBreak** is not set to **breakAll**. Hyphens are not supported.
903
904**Atomic service API**: This API can be used in atomic services since API version 12.
905
906**System capability**: SystemCapability.ArkUI.ArkUI.Full
907
908**Parameters**
909
910| Name  | Type                                                        | Mandatory| Description                                                        |
911| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
912| strategy | [LineBreakStrategy](ts-appendix-enums.md#linebreakstrategy12) | Yes  | Line break rule.<br>Default value: **LineBreakStrategy.GREEDY**<br>**NOTE**<br> This attribute does not take effect for the non-inline input style.|
913
914### editMenuOptions<sup>12+</sup>
915
916editMenuOptions(editMenu: EditMenuOptions)
917
918Sets the extended options of the custom context menu on selection, including the text content, icon, and callback.
919
920**Atomic service API**: This API can be used in atomic services since API version 12.
921
922**System capability**: SystemCapability.ArkUI.ArkUI.Full
923
924**Parameters**
925
926| Name| Type                                         | Mandatory| Description                                         |
927| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
928| editMenu  | [EditMenuOptions](ts-text-common.md#editmenuoptions) | Yes  | Extended options of the custom context menu on selection.|
929
930### enablePreviewText<sup>12+</sup>
931
932enablePreviewText(enable: boolean)
933
934Sets whether to enable preview text.
935
936Preview text is in a temporary state and does not support text interception. As such, it does not trigger **onWillInsert**, **onDidInsert**, **onWillDelete**, or **onDidDelete** callbacks.
937
938**Atomic service API**: This API can be used in atomic services since API version 12.
939
940**System capability**: SystemCapability.ArkUI.ArkUI.Full
941
942**Parameters**
943
944| Name| Type   | Mandatory| Description                              |
945| ------ | ------- | ---- | ---------------------------------- |
946| enable | boolean | Yes  | Whether to enable preview text.<br>Default value: **true**|
947
948### enableHapticFeedback<sup>13+</sup>
949
950enableHapticFeedback(isEnabled: boolean)
951
952Specifies whether to enable haptic feedback.
953
954**Atomic service API**: This API can be used in atomic services since API version 13.
955
956**System capability**: SystemCapability.ArkUI.ArkUI.Full
957
958**Parameters**
959
960| Name| Type   | Mandatory| Description                              |
961| ------ | ------- | ---- | ---------------------------------- |
962| isEnabled | boolean | Yes  | Whether to enable haptic feedback.<br>Default value: **true**|
963
964>  **NOTE**
965>
966>  To enable haptic feedback, you must declare the ohos.permission.VIBRATE permission under **requestPermissions** in the **module.json5** file of the project.
967> ```json
968> "requestPermissions": [
969>  {
970>     "name": "ohos.permission.VIBRATE",
971>  }
972> ]
973> ```
974
975### keyboardAppearance<sup>15+</sup>
976
977keyboardAppearance(appearance: Optional\<KeyboardAppearance>)
978
979Sets the appearance of the keyboard when the text box is focused.
980
981**Atomic service API**: This API can be used in atomic services since API version 15.
982
983**System capability**: SystemCapability.ArkUI.ArkUI.Full
984
985**Parameters**
986
987| Name| Type| Mandatory| Description|
988| ------ | ----------------------------------------- | ---- | ------------------------------------------------------ |
989| appearance | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[KeyboardAppearance](ts-text-common.md#keyboardappearance15)> | Yes  | Appearance of the keyboard.<br>Default value: **KeyboardAppearance.NONE_IMMERSIVE**|
990
991### stopBackPress<sup>15+<sup>
992
993stopBackPress(isStopped: Optional\<boolean>)
994
995Sets whether to prevent the back button press from being propagated to other components or applications.
996
997**Atomic service API**: This API can be used in atomic services since API version 15.
998
999**System capability**: SystemCapability.ArkUI.ArkUI.Full
1000
1001**Parameters**
1002
1003| Name| Type                                               | Mandatory| Description                                     |
1004| ------ | --------------------------------------------------- | ---- | ----------------------------------------- |
1005| isStopped  | [Optional](ts-universal-attributes-custom-property.md#optional12)\<boolean> | Yes  | Whether to consume the back button press.<br>Default value: **true**|
1006
1007### halfLeading<sup>18+</sup>
1008
1009halfLeading(halfLeading: Optional\<boolean>)
1010
1011Sets whether half leading is enabled.
1012
1013**Atomic service API**: This API can be used in atomic services since API version 18.
1014
1015**System capability**: SystemCapability.ArkUI.ArkUI.Full
1016
1017**Parameters**
1018
1019| Name| Type                                         | Mandatory| Description                                         |
1020| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
1021| halfLeading | [Optional](ts-universal-attributes-custom-property.md#optional12)\<boolean> | Yes | Whether half leading is enabled.<br>Half leading is the leading split in half and applied equally to the top and bottom edges. The value **true** means that half leading is enabled, and **false** means the opposite.<br>Default value: **false**|
1022
1023### minFontScale<sup>18+</sup>
1024
1025minFontScale(scale: Optional\<number | Resource>)
1026
1027Sets the minimum font scale factor for text.
1028
1029**Atomic service API**: This API can be used in atomic services since API version 18.
1030
1031**System capability**: SystemCapability.ArkUI.ArkUI.Full
1032
1033**Parameters**
1034
1035| Name| Type                                         | Mandatory| Description                                         |
1036| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
1037| scale  | [Optional](ts-universal-attributes-custom-property.md#optional12)\<number \| [Resource](ts-types.md#resource)> | Yes  | Minimum font scale factor for text. The **undefined** type is supported.<br>Value range: [0, 1]<br>**NOTE**<br>A value less than 0 is handled as 0. A value greater than 1 is handled as 1. Abnormal values are ineffective by default.|
1038
1039### maxFontScale<sup>18+</sup>
1040
1041maxFontScale(scale: Optional\<number | Resource>)
1042
1043Sets the maximum font scale factor for text.
1044
1045**Atomic service API**: This API can be used in atomic services since API version 18.
1046
1047**System capability**: SystemCapability.ArkUI.ArkUI.Full
1048
1049**Parameters**
1050
1051| Name| Type                                         | Mandatory| Description                                         |
1052| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
1053| scale  | [Optional](ts-universal-attributes-custom-property.md#optional12)\<number \| [Resource](ts-types.md#resource)> | Yes  | Maximum font scale factor for text. The **undefined** type is supported.<br>Value range: [1, +∞)<br>**NOTE**<br>A value less than 1 is handled as 1. Abnormal values are ineffective by default.|
1054
1055### cancelButton<sup>18+</sup>
1056
1057cancelButton(symbolOptions: CancelButtonSymbolOptions)
1058
1059Sets the style of the cancel button on the right. This attribute is not available for the inline input style.
1060
1061**Atomic service API**: This API can be used in atomic services since API version 18.
1062
1063**System capability**: SystemCapability.ArkUI.ArkUI.Full
1064
1065**Parameters**
1066
1067| Name| Type                                                        | Mandatory| Description                                                        |
1068| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
1069| symbolOptions  | [CancelButtonSymbolOptions](ts-basic-components-search.md#cancelbuttonsymboloptions12) | Yes  | Style of the cancel button on the right.<br>Default value:<br>{<br>style: CancelButtonStyle.INPUT<br>} |
1070
1071### ellipsisMode<sup>18+</sup>
1072
1073ellipsisMode(mode: Optional\<EllipsisMode>)
1074
1075Sets the ellipsis position. For the settings to work, **overflow** must be set to **TextOverflow.Ellipsis**. Setting **ellipsisMode** alone does not take effect.
1076
1077**EllipsisMode.START** and **EllipsisMode.CENTER** take effect only when **maxLines** is set to **1** in inline style.
1078
1079**Atomic service API**: This API can be used in atomic services since API version 18.
1080
1081**System capability**: SystemCapability.ArkUI.ArkUI.Full
1082
1083**Parameters**
1084
1085| Name| Type                                               | Mandatory| Description                                     |
1086| ------ | --------------------------------------------------- | ---- | ----------------------------------------- |
1087| mode  | [Optional](ts-universal-attributes-custom-property.md#optional12)\<[EllipsisMode](ts-appendix-enums.md#ellipsismode11)> | Yes  | Ellipsis position.<br>Default value: **EllipsisMode.END**|
1088
1089## InputType
1090
1091**System capability**: SystemCapability.ArkUI.ArkUI.Full
1092
1093| Name                         | Description                                                    |
1094| ----------------------------- | ------------------------------------------------------------ |
1095| Normal                        | Normal input mode. In this mode, there is no special restriction on the input characters.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
1096| Password                      | Password input mode.<br>An eye icon is used to show or hide the password. By default, the entered characters are temporarily shown before being obscured by dots; they are directly obscured by dots since API version 12 on certain devices. The password input mode does not support underlines. If Password Vault is enabled, autofill is available for the username and password.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
1097| Email                         | Email address input mode.<br>This mode accepts only digits, letters, underscores (_), dots (.), and the following special characters: ! # $ % & ' " * + - / = ? ^ ` \{ \| \} ~ @ (which can only appear once)<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
1098| Number                        | Digit input mode.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
1099| PhoneNumber<sup>9+</sup>      | Phone number input mode.<br>In this mode, the following are allowed: digits, spaces, plus signs (+), hyphens (-), asterisks (*), and number signs (#); the length is not limited.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
1100| USER_NAME<sup>11+</sup>       | Username input mode.<br>If Password Vault is enabled, autofill is available for the username and password.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1101| NEW_PASSWORD<sup>11+</sup>    | New password input mode.<br>An eye icon is used to show or hide the password. By default, the entered characters are temporarily shown before being obscured by dots; they are directly obscured by dots since API version 12 on certain devices. If Password Vault is enabled, a new password can be automatically generated.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1102| NUMBER_PASSWORD<sup>11+</sup> | Numeric password input mode.<br>An eye icon is used to show or hide the password. By default, the entered characters are temporarily shown before being obscured by dots; they are directly obscured by dots since API version 12 on certain devices. The password input mode does not support underlines.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1103| NUMBER_DECIMAL<sup>11+</sup>  | Number input mode with a decimal point.<br>The value can contain digits and one decimal point.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
1104| URL<sup>12+</sup>  | URL input mode.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1105
1106## ContentType<sup>12+</sup>
1107
1108Enumerates the content types for autofill.
1109
1110**System capability**: SystemCapability.ArkUI.ArkUI.Full
1111
1112| Name                      | Value  | Description                                                        |
1113| -------------------------- | ---- | ------------------------------------------------------------ |
1114| USER_NAME                  | 0    | Username. Password Vault, when enabled, can automatically save and fill in usernames.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1115| PASSWORD                   | 1    | Password. Password Vault, when enabled, can automatically save and fill in passwords.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1116| NEW_PASSWORD               | 2    | New password. Password Vault, when enabled, can automatically generate a new password.<br>**Atomic service API**: This API can be used in atomic services since API version 12.  |
1117| FULL_STREET_ADDRESS        | 3    | Full street address. The scenario-based autofill feature, when enabled, can automatically save and fill in full street addresses.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1118| HOUSE_NUMBER               | 4    | House number. The scenario-based autofill feature, when enabled, can automatically save and fill in house numbers.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1119| DISTRICT_ADDRESS           | 5    | District and county. The scenario-based autofill feature, when enabled, can automatically save and fill in districts and counties.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1120| CITY_ADDRESS               | 6    | City. The scenario-based autofill feature, when enabled, can automatically save and fill in cities.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1121| PROVINCE_ADDRESS           | 7    | Province. The scenario-based autofill feature, when enabled, can automatically save and fill in provinces.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1122| COUNTRY_ADDRESS            | 8    | Country. The scenario-based autofill feature, when enabled, can automatically save and fill in countries.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1123| PERSON_FULL_NAME           | 9    | Full name. The scenario-based autofill feature, when enabled, can automatically save and fill in full names.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1124| PERSON_LAST_NAME           | 10   | Last name. The scenario-based autofill feature, when enabled, can automatically save and fill in last names.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1125| PERSON_FIRST_NAME          | 11   | First name. The scenario-based autofill feature, when enabled, can automatically save and fill in first names.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1126| PHONE_NUMBER               | 12   | Phone number. The scenario-based autofill feature, when enabled, can automatically save and fill in phone numbers.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1127| PHONE_COUNTRY_CODE         | 13   | Country code. The scenario-based autofill feature, when enabled, can automatically save and fill in country codes.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1128| FULL_PHONE_NUMBER          | 14   | Phone number with country code. The scenario-based autofill feature, when enabled, can automatically save and fill in phone numbers with country codes.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1129| EMAIL_ADDRESS              | 15   | Email address. The scenario-based autofill feature, when enabled, can automatically save and fill in email addresses.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1130| BANK_CARD_NUMBER           | 16   | Bank card number. The scenario-based autofill feature, when enabled, can automatically save and fill in bank card numbers.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1131| ID_CARD_NUMBER             | 17   | ID card number. The scenario-based autofill feature, when enabled, can automatically save and fill in ID card numbers.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1132| NICKNAME                   | 23   | Nickname. The scenario-based autofill feature, when enabled, can automatically save and fill in nicknames.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1133| DETAIL_INFO_WITHOUT_STREET | 24   | Address information without street address. The scenario-based autofill feature, when enabled, can automatically save and fill in address information without street addresses.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1134| FORMAT_ADDRESS             | 25   | Standard address. The scenario-based autofill feature, when enabled, can automatically save and fill in standard addresses.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1135| PASSPORT_NUMBER<sup>18+</sup>            | 26   | Passport number. The scenario-based autofill feature, when enabled, can automatically save and fill in passport numbers.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
1136| VALIDITY<sup>18+</sup>                   | 27   | Passport validity period. The scenario-based autofill feature, when enabled, can automatically save and fill in passport validity periods.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
1137| ISSUE_AT<sup>18+</sup>                   | 28   | Passport place of issue. The scenario-based autofill feature, when enabled, can automatically save and fill in the place of issue for passports.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
1138| ORGANIZATION<sup>18+</sup>               | 29   | Invoice title. The scenario-based autofill feature, when enabled, can automatically save and fill in invoice titles.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
1139| TAX_ID<sup>18+</sup>                     | 30   | Tax ID. The scenario-based autofill feature, when enabled, can automatically save and fill in tax IDs.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
1140| ADDRESS_CITY_AND_STATE<sup>18+</sup>     | 31   | Location. The scenario-based autofill feature, when enabled, can automatically save and fill in locations.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
1141| FLIGHT_NUMBER<sup>18+</sup>              | 32   | Flight number. Currently not supported for automatic saving and auto-filling.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
1142| LICENSE_NUMBER<sup>18+</sup>             | 33   | Driver's license number. Currently not supported for automatic saving and auto-filling.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
1143| LICENSE_FILE_NUMBER<sup>18+</sup>        | 34   | Driver's license file number. Currently not supported for automatic saving and auto-filling.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
1144| LICENSE_PLATE<sup>18+</sup>              | 35   | License plate number. The scenario-based autofill feature, when enabled, can automatically save and fill in license plate numbers.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
1145| ENGINE_NUMBER<sup>18+</sup>              | 36   | Vehicle registration engine number. Currently not supported for automatic saving and auto-filling.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
1146| LICENSE_CHASSIS_NUMBER<sup>18+</sup>     | 37   | Chassis number. Currently not supported for automatic saving and auto-filling.<br>**Atomic service API**: This API can be used in atomic services since API version 18.|
1147
1148## TextInputStyle<sup>9+</sup>
1149
1150**Atomic service API**: This API can be used in atomic services since API version 11.
1151
1152**System capability**: SystemCapability.ArkUI.ArkUI.Full
1153
1154| Name   | Description                                                        |
1155| ------- | ------------------------------------------------------------ |
1156| Default | Default style. The caret width is fixed at 1.5 vp, and the caret height is subject to the background height and font size of the selected text.|
1157| Inline  | Inline input style. The background height of the selected text is the same as the height of the text box.<br>This style is used in scenarios where editing and non-editing states are obvious, for example, renaming in the file list view.<br>The **showError** attribute is not supported for this style.<br>This style does not allow for text dragging and dropping.|
1158
1159## PasswordIcon<sup>10+</sup>
1160
1161**Atomic service API**: This API can be used in atomic services since API version 11.
1162
1163**System capability**: SystemCapability.ArkUI.ArkUI.Full
1164
1165| Name| Type | Mandatory  | Description|
1166| ---- | ----- | ---- | ---- |
1167| onIconSrc  | string \| [Resource](ts-types.md#resource) | No   | Icon that can be used to hide the password in password input mode.<br>The string type can be used to load network images and local images.|
1168| offIconSrc | string \| [Resource](ts-types.md#resource) | No   | Icon that can be used to show the password in password input mode.<br>The string type can be used to load network images and local images.|
1169
1170## EnterKeyType
1171
1172Enumerates the Enter key types.
1173
1174**System capability**: SystemCapability.ArkUI.ArkUI.Full
1175
1176| Name                  | Value| Description              |
1177| ---------------------- | --- | ------------------ |
1178| Go                     | 2 | The Enter key is labeled "Go."<br>**Atomic service API**: This API can be used in atomic services since API version 11.  |
1179| Search                 | 3 | The Enter key is labeled "Search."<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
1180| Send                   | 4 | The Enter key is labeled "Send."<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
1181| Next                   | 5 | The Enter key is labeled "Next."<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
1182| Done                   | 6 | The Enter key is labeled "Done."<br>**Atomic service API**: This API can be used in atomic services since API version 11. |
1183| PREVIOUS<sup>11+</sup> | 7 | The Enter key is labeled "Previous."<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
1184| NEW_LINE<sup>11+</sup> | 8 | The Enter key is labeled "New Line."<br>**Atomic service API**: This API can be used in atomic services since API version 12. |
1185
1186
1187## Events
1188
1189In addition to the [universal events](ts-component-general-events.md), the following events are supported.
1190
1191### onChange
1192
1193onChange(callback: EditableTextOnChangeCallback)
1194
1195Triggered when the input in the text box changes.
1196
1197In this callback, if cursor operations are performed, you need to adjust the cursor logic based on the **previewText** parameter to ensure it works seamlessly within the preview display scenario.
1198
1199**Atomic service API**: This API can be used in atomic services since API version 11.
1200
1201**System capability**: SystemCapability.ArkUI.ArkUI.Full
1202
1203**Parameters**
1204
1205| Name| Type  | Mandatory| Description                |
1206| ------ | ------ | ---- | -------------------- |
1207| callback  | [EditableTextOnChangeCallback](ts-text-common.md#editabletextonchangecallback12) | Yes  | Callback invoked when the input in the text box changes.|
1208
1209### onSubmit
1210
1211onSubmit(callback: OnSubmitCallback)
1212
1213Triggered when the Enter key on the keyboard is pressed for submission.
1214
1215**Atomic service API**: This API can be used in atomic services since API version 11.
1216
1217**System capability**: SystemCapability.ArkUI.ArkUI.Full
1218
1219**Parameters**
1220
1221| Name             | Type                                            | Mandatory| Description                                                        |
1222| ------------------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
1223| callback            | [OnSubmitCallback](#onsubmitcallback18) | Yes  | Callback for submission.|
1224
1225### onEditChanged<sup>(deprecated)</sup>
1226
1227onEditChanged(callback: (isEditing: boolean) =&gt; void)
1228
1229Triggered when the input status changes.
1230
1231This API is deprecated since API version 8. You are advised to use **onEditChange** instead.
1232
1233**System capability**: SystemCapability.ArkUI.ArkUI.Full
1234
1235**Parameters**
1236
1237| Name   | Type   | Mandatory| Description                |
1238| --------- | ------- | ---- | -------------------- |
1239| isEditing | boolean | Yes  | Whether the text box is in the editing state. The value **true** indicates that the text box is in the editing state.|
1240
1241### onEditChange<sup>8+</sup>
1242
1243onEditChange(callback: Callback\<boolean>)
1244
1245Triggered when the input status 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.
1246
1247**Atomic service API**: This API can be used in atomic services since API version 11.
1248
1249**System capability**: SystemCapability.ArkUI.ArkUI.Full
1250
1251**Parameters**
1252
1253| Name   | Type   | Mandatory| Description                |
1254| --------- | ------- | ---- | -------------------- |
1255| callback | Callback\<boolean> | Yes  | Callback for input status changes. It returns **true** if the input operation is currently in progress.|
1256
1257### onCopy<sup>8+</sup>
1258
1259onCopy(callback: Callback\<string>)
1260
1261Triggered when a copy operation is performed.
1262
1263**Atomic service API**: This API can be used in atomic services since API version 11.
1264
1265**System capability**: SystemCapability.ArkUI.ArkUI.Full
1266
1267**Parameters**
1268
1269| Name   | Type   | Mandatory| Description            |
1270| --------- | ------- | ---- | ---------------- |
1271| callback | Callback\<string> | Yes  | Callback used to return the copied text content.|
1272
1273### onCut<sup>8+</sup>
1274
1275onCut(callback: Callback\<string>)
1276
1277Triggered when a cut operation is performed.
1278
1279**Atomic service API**: This API can be used in atomic services since API version 11.
1280
1281**System capability**: SystemCapability.ArkUI.ArkUI.Full
1282
1283**Parameters**
1284
1285| Name   | Type   | Mandatory| Description            |
1286| --------- | ------- | ---- | ---------------- |
1287| callback | Callback\<string> | Yes  | Callback used to return the cut text content.|
1288
1289### onPaste<sup>8+</sup>
1290
1291onPaste(callback: OnPasteCallback)
1292
1293Triggered when a paste operation is performed.
1294
1295**Atomic service API**: This API can be used in atomic services since API version 11.
1296
1297**System capability**: SystemCapability.ArkUI.ArkUI.Full
1298
1299**Parameters**
1300| Name             | Type                                                        | Mandatory| Description                  |
1301| ------------------- | ------------------------------------------------------------ | ---- | ---------------------- |
1302| callback | [OnPasteCallback](#onpastecallback18)       | Yes  | Callback used to return the pasted text content.|
1303
1304### onTextSelectionChange<sup>10+</sup>
1305
1306onTextSelectionChange(callback: OnTextSelectionChangeCallback)
1307
1308Triggered when the position of the text selection changes or when the cursor position changes during the editing state.
1309
1310**Atomic service API**: This API can be used in atomic services since API version 11.
1311
1312**System capability**: SystemCapability.ArkUI.ArkUI.Full
1313
1314**Parameters**
1315
1316| Name        | Type  | Mandatory| Description                                   |
1317| -------------- | ------ | ---- | --------------------------------------- |
1318| callback | [OnTextSelectionChangeCallback](#ontextselectionchangecallback18) | Yes  | Callback for text selection changes or cursor position changes.|
1319
1320### onContentScroll<sup>10+</sup>
1321
1322onContentScroll(callback: OnContentScrollCallback)
1323
1324Triggered when the text content is scrolled.
1325
1326**Atomic service API**: This API can be used in atomic services since API version 11.
1327
1328**System capability**: SystemCapability.ArkUI.ArkUI.Full
1329
1330**Parameters**
1331
1332| Name      | Type  | Mandatory| Description                              |
1333| ------------ | ------ | ---- | ---------------------------------- |
1334| callback | [OnContentScrollCallback](#oncontentscrollcallback18) | Yes  | Callback for text content scrolling.|
1335
1336### onSecurityStateChange<sup>12+</sup>
1337
1338onSecurityStateChange(callback: Callback\<boolean>)
1339
1340Triggered when the password visibility changes.
1341
1342**Atomic service API**: This API can be used in atomic services since API version 12.
1343
1344**System capability**: SystemCapability.ArkUI.ArkUI.Full
1345
1346**Parameters**
1347
1348| Name      | Type  | Mandatory| Description                              |
1349| ------------ | ------ | ---- | ---------------------------------- |
1350| callback | Callback\<boolean> | Yes  | Callback used to return the result.|
1351
1352### onWillInsert<sup>12+</sup>
1353
1354onWillInsert(callback: Callback\<InsertValue, boolean>)
1355
1356Triggered when text is about to be inserted.
1357
1358**Atomic service API**: This API can be used in atomic services since API version 12.
1359
1360**System capability**: SystemCapability.ArkUI.ArkUI.Full
1361
1362**Parameters**
1363
1364| Name| Type                                                        | Mandatory| Description              |
1365| ------ | ------------------------------------------------------------ | ---- | ------------------ |
1366| callback  | Callback\<[InsertValue](ts-text-common.md#insertvalue12), boolean> | Yes  | Callback triggered when text is about to be inserted.<br>It returns **true** if the text is inserted; returns **false** otherwise.<br>This callback is not triggered for pre-edit or candidate word operations.<br>It is available only for system input methods.|
1367
1368### onDidInsert<sup>12+</sup>
1369
1370onDidInsert(callback: Callback\<InsertValue>)
1371
1372Triggered when text is inserted.
1373
1374**Atomic service API**: This API can be used in atomic services since API version 12.
1375
1376**System capability**: SystemCapability.ArkUI.ArkUI.Full
1377
1378**Parameters**
1379
1380| Name| Type                                                        | Mandatory| Description              |
1381| ------ | ------------------------------------------------------------ | ---- | ------------------ |
1382| callback  | Callback\<[InsertValue](ts-text-common.md#insertvalue12)> | Yes  | Callback triggered when text is inserted.<br>It is available only for system input methods.|
1383
1384### onWillDelete<sup>12+</sup>
1385
1386onWillDelete(callback: Callback\<DeleteValue, boolean>)
1387
1388Triggered when text is about to be deleted.
1389
1390**Atomic service API**: This API can be used in atomic services since API version 12.
1391
1392**System capability**: SystemCapability.ArkUI.ArkUI.Full
1393
1394**Parameters**
1395
1396| Name| Type                                                        | Mandatory| Description              |
1397| ------ | ------------------------------------------------------------ | ---- | ------------------ |
1398| callback  | Callback\<[DeleteValue](ts-text-common.md#deletevalue12), boolean> | Yes  | Callback triggered when text is about to be deleted.<br>It returns **true** if the text is deleted; returns **false** otherwise.<br>This callback is not called for text preview.<br>It is available only for system input methods.|
1399
1400### onDidDelete<sup>12+</sup>
1401
1402onDidDelete(callback: Callback\<DeleteValue>)
1403
1404Triggered when text is deleted.
1405
1406**Atomic service API**: This API can be used in atomic services since API version 12.
1407
1408**System capability**: SystemCapability.ArkUI.ArkUI.Full
1409
1410**Parameters**
1411
1412| Name| Type                                                        | Mandatory| Description              |
1413| ------ | ------------------------------------------------------------ | ---- | ------------------ |
1414| callback  | Callback\<[DeleteValue](ts-text-common.md#deletevalue12)> | Yes  | Callback triggered when text is deleted.<br>It is available only for system input methods.|
1415
1416### onWillChange<sup>15+</sup>
1417
1418onWillChange(callback: Callback\<EditableTextChangeValue, boolean>)
1419
1420Called when the text content is about to change.
1421
1422This callback is triggered after **onWillInsert** and **onWillDelete**, but before **onDidInsert** and **onDidDelete**.
1423
1424**Atomic service API**: This API can be used in atomic services since API version 15.
1425
1426**System capability**: SystemCapability.ArkUI.ArkUI.Full
1427
1428**Parameters**
1429
1430| Name| Type                                                        | Mandatory| Description              |
1431| ------ | ------------------------------------------------------------ | ---- | ------------------ |
1432| callback  | Callback\<[EditableTextChangeValue](ts-text-common.md#editabletextchangevalue15), boolean> | Yes  | Callback triggered when the text content is about to change.<br>Returning **true** allows the change to proceed, while returning **false** cancels the change.|
1433
1434## TextInputController<sup>8+</sup>
1435
1436Inherits from [TextContentControllerBase](ts-types.md#textcontentcontrollerbase10).
1437
1438**Atomic service API**: This API can be used in atomic services since API version 11.
1439
1440**System capability**: SystemCapability.ArkUI.ArkUI.Full
1441
1442### Objects to Import
1443```
1444controller: TextInputController = new TextInputController()
1445```
1446
1447### constructor<sup>8+</sup>
1448
1449constructor()
1450
1451A constructor used to create a **TextInputController** object.
1452
1453**Atomic service API**: This API can be used in atomic services since API version 11.
1454
1455**System capability**: SystemCapability.ArkUI.ArkUI.Full
1456
1457### caretPosition<sup>8+</sup>
1458
1459caretPosition(value: number): void
1460
1461Sets the position of the caret. If the value is less than 0, the value **0** is used. If the value exceeds the text length, the caret is placed at the end of the text.
1462
1463**Atomic service API**: This API can be used in atomic services since API version 11.
1464
1465**System capability**: SystemCapability.ArkUI.ArkUI.Full
1466
1467**Parameters**
1468
1469| Name  | Type  | Mandatory  | Description |
1470| ----- | ------ | ---- | ------ |
1471| value | number | Yes   | Length from the start of the string to the position where the caret is located.|
1472### setTextSelection<sup>10+</sup>
1473
1474setTextSelection(selectionStart: number, selectionEnd: number, options?: SelectionOptions): void
1475
1476Sets the text selection area, which will be highlighted.
1477
1478**Atomic service API**: This API can be used in atomic services since API version 11.
1479
1480**System capability**: SystemCapability.ArkUI.ArkUI.Full
1481
1482**Parameters**
1483
1484| Name | Type  | Mandatory  | Description |
1485| ------- | ------ | ---- | ----- |
1486| selectionStart | number | Yes   | Start position of the text selection range. The start position of text in the text box is 0.|
1487| selectionEnd   | number | Yes   | End position of the text selection range.|
1488| options<sup>12+</sup>   | [SelectionOptions](ts-types.md#selectionoptions12) | No   | Configuration options for text selection.<br>Default value: **MenuPolicy.DEFAULT**<br>This API can be used in atomic services since API version 12.|
1489
1490>  **NOTE**
1491>
1492>  If **selectionStart** or **selectionEnd** is set to **undefined**, the value **0** will be used.
1493>
1494>  If **selectionMenuHidden** is set to **true** or a 2-in-1 device is used, calling **setTextSelection** does not display the context menu even when **options** is set to **MenuPolicy.SHOW**.
1495>
1496>  If the selected text contains an emoji, the emoji is selected when its start position is within the text selection range.
1497
1498### stopEditing<sup>10+</sup>
1499
1500stopEditing(): void
1501
1502Exits the editing state.
1503
1504**Atomic service API**: This API can be used in atomic services since API version 11.
1505
1506**System capability**: SystemCapability.ArkUI.ArkUI.Full
1507
1508## UnderlineColor<sup>12+</sup>
1509
1510**Atomic service API**: This API can be used in atomic services since API version 12.
1511
1512**System capability**: SystemCapability.ArkUI.ArkUI.Full
1513
1514| Name| Type | Mandatory  | Description|
1515| ---- | ----- | ---- | ---- |
1516| typing  | [ResourceColor](ts-types.md#resourcecolor) \| undefined | No  | Underline color in the typing state. If no value is specified or if the value specified is **undefined**, **null**, or invalid, the default value is used.|
1517| normal  | [ResourceColor](ts-types.md#resourcecolor) \| undefined | No  | Underline color in the normal state. If no value is specified or if the value specified is **undefined**, **null**, or invalid, the default value is used.|
1518| error   | [ResourceColor](ts-types.md#resourcecolor) \| undefined | No  | Underline color when an error occurs. If no value is specified or if the value specified is **undefined**, **null**, or invalid, the default value is used. This option changes the color used in the **showCounter** attribute when the maximum number of characters is reached.|
1519| disable | [ResourceColor](ts-types.md#resourcecolor) \| undefined | No  | Underline color in the disabled state. If no value is specified or if the value specified is **undefined**, **null**, or invalid, the default value is used.|
1520
1521## SubmitEvent<sup>11+</sup>
1522
1523Defines the user submission event.
1524
1525**Atomic service API**: This API can be used in atomic services since API version 11.
1526
1527**System capability**: SystemCapability.ArkUI.ArkUI.Full
1528
1529### Properties
1530
1531**Atomic service API**: This API can be used in atomic services since API version 11.
1532
1533**System capability**: SystemCapability.ArkUI.ArkUI.Full
1534
1535| Name| Type | Mandatory  | Description|
1536| ---- | ----- | ---- | ---- |
1537| text              | string     | Yes  | Text in the text box.                                  |
1538
1539### keepEditableState
1540
1541keepEditableState(): void
1542
1543Maintains the editable state of the text box when called.
1544
1545**Atomic service API**: This API can be used in atomic services since API version 11.
1546
1547**System capability**: SystemCapability.ArkUI.ArkUI.Full
1548
1549## OnPasteCallback<sup>18+</sup>
1550
1551type OnPasteCallback = (content: string, event: PasteEvent) => void
1552
1553Defines the callback used to return the pasted text content.
1554
1555**Atomic service API**: This API can be used in atomic services since API version 18.
1556
1557**System capability**: SystemCapability.ArkUI.ArkUI.Full
1558
1559**Parameters**
1560
1561| Name             | Type                                                        | Mandatory| Description                  |
1562| ------------------- | ------------------------------------------------------------ | ---- | ---------------------- |
1563| content               | string                                                       | Yes  | Text to be pasted.      |
1564| event | [PasteEvent](ts-basic-components-richeditor.md#pasteevent11) | Yes  | Custom paste event.|
1565
1566## OnSubmitCallback<sup>18+</sup>
1567
1568type OnSubmitCallback = (enterKey: EnterKeyType, event: SubmitEvent) => void
1569
1570Defines the callback for submission.
1571
1572**Atomic service API**: This API can be used in atomic services since API version 18.
1573
1574**System capability**: SystemCapability.ArkUI.ArkUI.Full
1575
1576**Parameters**
1577
1578| Name             | Type                                            | Mandatory| Description                                                        |
1579| ------------------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
1580| enterKey            | [EnterKeyType](#enterkeytype) | Yes  | Type of the Enter key.|
1581| event | [SubmitEvent](#submitevent11)         | Yes  | Submit event.                                                  |
1582
1583## OnTextSelectionChangeCallback<sup>18+</sup>
1584
1585type OnTextSelectionChangeCallback = (selectionStart: number, selectionEnd: number) => void
1586
1587Defines the callback for text selection changes or cursor position changes.
1588
1589**Atomic service API**: This API can be used in atomic services since API version 18.
1590
1591**System capability**: SystemCapability.ArkUI.ArkUI.Full
1592
1593**Parameters**
1594
1595| Name        | Type  | Mandatory| Description                                   |
1596| -------------- | ------ | ---- | --------------------------------------- |
1597| selectionStart | number | Yes  | Start position of the selected text. The start position of text is **0**.|
1598| selectionEnd   | number | Yes  | End position of the selected text.                   |
1599
1600## OnContentScrollCallback<sup>18+</sup>
1601
1602type OnContentScrollCallback = (totalOffsetX: number, totalOffsetY: number) => void
1603
1604Defines the callback for text content scrolling.
1605
1606**Atomic service API**: This API can be used in atomic services since API version 18.
1607
1608**System capability**: SystemCapability.ArkUI.ArkUI.Full
1609
1610**Parameters**
1611
1612| Name      | Type  | Mandatory| Description                              |
1613| ------------ | ------ | ---- | ---------------------------------- |
1614| totalOffsetX | number | Yes  | Offset in the X coordinate of the text in the content area, in px.|
1615| totalOffsetY | number | Yes  | Offset in the Y coordinate of the text in the content area, in px.|
1616
1617## Example
1618
1619### Example 1: Setting and Obtaining the Cursor Position
1620
1621This example demonstrates how to use the controller to set and obtain the cursor position within a text box.
1622
1623```ts
1624// xxx.ets
1625@Entry
1626@Component
1627struct TextInputExample {
1628  @State text: string = ''
1629  @State positionInfo: CaretOffset = { index: 0, x: 0, y: 0 }
1630  @State passwordState: boolean = false
1631  controller: TextInputController = new TextInputController()
1632
1633  build() {
1634    Column() {
1635      // Use !! to implement two-way binding of the text parameter.
1636      TextInput({ text: this.text!!, placeholder: 'input your word...', controller: this.controller })
1637        .placeholderColor(Color.Grey)
1638        .placeholderFont({ size: 14, weight: 400 })
1639        .caretColor(Color.Blue)
1640        .width('95%')
1641        .height(40)
1642        .margin(20)
1643        .fontSize(14)
1644        .fontColor(Color.Black)
1645        .inputFilter('[a-z]', (e) => {
1646          console.log(JSON.stringify(e))
1647        })
1648      Text(this.text)
1649      Button('Set caretPosition 1')
1650        .margin(15)
1651        .onClick(() => {
1652          // Move the caret to after the first entered character.
1653          this.controller.caretPosition(1)
1654        })
1655      Button('Get CaretOffset')
1656        .margin(15)
1657        .onClick(() => {
1658          this.positionInfo = this.controller.getCaretOffset()
1659        })
1660      // Password text box.
1661      TextInput({ placeholder: 'input your password...' })
1662        .width('95%')
1663        .height(40)
1664        .margin(20)
1665        .type(InputType.Password)
1666        .maxLength(9)
1667        .showPasswordIcon(true)
1668        .showPassword(this.passwordState)
1669        .onSecurityStateChange(((isShowPassword: boolean) => {
1670          // Update the password visibility.
1671          console.info('isShowPassword', isShowPassword)
1672          this.passwordState = isShowPassword
1673        }))
1674      // Email address autofill.
1675      TextInput({ placeholder: 'input your email...' })
1676        .width('95%')
1677        .height(40)
1678        .margin(20)
1679        .contentType(ContentType.EMAIL_ADDRESS)
1680        .maxLength(9)
1681      // Inline-style text box.
1682      TextInput({ text: 'inline style' })
1683        .width('95%')
1684        .height(50)
1685        .margin(20)
1686        .borderRadius(0)
1687        .style(TextInputStyle.Inline)
1688    }.width('100%')
1689  }
1690}
1691```
1692
1693![TextInput](figures/TextInput.gif)
1694
1695### Example 2: Setting Underlines
1696
1697This example showcases the effects of underlines in different scenarios using the **showUnderline**, **showError**, **showUnit**, and **passwordIcon** attributes.
1698
1699```ts
1700// xxx.ets
1701@Entry
1702@Component
1703struct TextInputExample {
1704  @State passWordSrc1: Resource = $r('app.media.ImageOne');
1705  @State passWordSrc2: Resource = $r('app.media.ImageTwo');
1706  @State textError: string = '';
1707  @State text: string = '';
1708  @State nameText: string = 'test';
1709
1710  @Builder
1711  itemEnd() {
1712    Select([{ value: 'KB' },
1713      { value: 'MB' },
1714      { value: 'GB' },
1715      { value: 'TB', }])
1716      .height("48vp")
1717      .borderRadius(0)
1718      .selected(2)
1719      .align(Alignment.Center)
1720      .value('MB')
1721      .font({ size: 20, weight: 500 })
1722      .fontColor('#182431')
1723      .selectedOptionFont({ size: 20, weight: 400 })
1724      .optionFont({ size: 20, weight: 400 })
1725      .backgroundColor(Color.Transparent)
1726      .responseRegion({
1727        height: "40vp",
1728        width: "80%",
1729        x: '10%',
1730        y: '6vp'
1731      })
1732      .onSelect((index: number) => {
1733        console.info('Select:' + index);
1734      })
1735  }
1736
1737  build() {
1738    Column({ space: 20 }) {
1739      // Customize the password icon.
1740      TextInput({ placeholder: 'Custom password icon' })
1741        .type(InputType.Password)
1742        .width(350)
1743        .height(60)
1744        .passwordIcon({ onIconSrc: this.passWordSrc1, offIconSrc: this.passWordSrc2 })
1745      // Show an underline.
1746      TextInput({ placeholder: 'Underline style' })
1747        .showUnderline(true)
1748        .width(350)
1749        .height(60)
1750        .showError('Error')
1751        .showUnit(this.itemEnd)
1752
1753      Text(`User name: ${this.text}`)
1754        .width(350)
1755      TextInput({ placeholder: 'Enter user name', text: this.text })
1756        .showUnderline(true)
1757        .width(350)
1758        .showError(this.textError)
1759        .onChange((value: string) => {
1760          this.text = value
1761        })
1762        .onSubmit((enterKey: EnterKeyType, event: SubmitEvent) => {
1763          // If the entered user name is incorrect, clear the text box and display an error message.
1764          if (this.text == this.nameText) {
1765            this.textError = '';
1766          } else {
1767            this.textError = 'Incorrect user name.';
1768            this.text = '';
1769            // Call keepEditableState to maintain the editable state of the text box.
1770            event.keepEditableState();
1771          }
1772        })
1773      // Set the color of the underline.
1774      TextInput({ placeholder: 'Placeholder text' })
1775        .width(350)
1776        .showUnderline(true)
1777        .underlineColor({
1778          normal: Color.Orange,
1779          typing: Color.Green,
1780          error: Color.Red,
1781          disable: Color.Gray
1782        });
1783      TextInput({ placeholder: 'Placeholder text' })
1784        .width(350)
1785        .showUnderline(true)
1786        .underlineColor(Color.Gray);
1787
1788    }.width('100%').margin({ top: 10 })
1789  }
1790}
1791```
1792
1793![TextInputError](figures/TextInputUnderline.png)
1794
1795### Example 3: Implementing a Custom Keyboard
1796
1797This example demonstrates how to implement a custom keyboard using the **customKeyboard** attribute.
1798
1799```ts
1800// xxx.ets
1801@Entry
1802@Component
1803struct TextInputExample {
1804  controller: TextInputController = new TextInputController();
1805  @State inputValue: string = "";
1806
1807  // Create a custom keyboard component.
1808  @Builder
1809  CustomKeyboardBuilder() {
1810    Column() {
1811      Button('x').onClick(() => {
1812        // Disable the custom keyboard.
1813        this.controller.stopEditing();
1814      })
1815      Grid() {
1816        ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item: number | string) => {
1817          GridItem() {
1818            Button(item + "")
1819              .width(110).onClick(() => {
1820              this.inputValue += item;
1821            })
1822          }
1823        })
1824      }.maxCount(3).columnsGap(10).rowsGap(10).padding(5)
1825    }.backgroundColor(Color.Gray)
1826  }
1827
1828  build() {
1829    Column() {
1830      TextInput({ controller: this.controller, text: this.inputValue })// Bind a custom keyboard.
1831        .customKeyboard(this.CustomKeyboardBuilder()).margin(10).border({ width: 1 }).height('48vp')
1832    }
1833  }
1834}
1835```
1836
1837![customKeyboard](figures/textInputCustomKeyboard.png)
1838
1839### Example 4: Customizing the Cancel Button Style on the Right
1840
1841This example demonstrates how to use the **cancelButton** attribute to customize the style of the cancel button on the right side of the text box.
1842
1843```ts
1844// xxx.ets
1845@Entry
1846@Component
1847struct TextInputExample {
1848  @State text: string = '';
1849  controller: TextInputController = new TextInputController();
1850
1851  build() {
1852    Column() {
1853      TextInput({ placeholder: 'input ...', controller: this.controller })
1854        .width(380)
1855        .height(60)
1856        .cancelButton({
1857          style: CancelButtonStyle.CONSTANT,
1858          icon: {
1859            size: 45,
1860            src: $r('app.media.app_icon'),
1861            color: Color.Blue
1862          }
1863        })
1864        .onChange((value: string) => {
1865          this.text = value;
1866        })
1867    }
1868  }
1869}
1870```
1871
1872![cancelButton](figures/TextInputCancelButton.png)
1873
1874### Example 5: Implementing a Counter
1875
1876This example showcases the implementation of a counter feature using the **maxLength**, **showCounter**, and **showUnderline** attributes.
1877
1878```ts
1879// xxx.ets
1880@Entry
1881@Component
1882struct TextInputExample {
1883  @State text: string = '';
1884  controller: TextInputController = new TextInputController();
1885
1886  build() {
1887    Column() {
1888      TextInput({ text: this.text, controller: this.controller })
1889        .placeholderFont({ size: 16, weight: 400 })
1890        .width(336)
1891        .height(56)
1892        .maxLength(6)
1893        .showUnderline(true)
1894        .showCounter(true,
1895          { thresholdPercentage: 50, highlightBorder: true })// The character counter is in this format: Number of characters that have been entered/Maximum number of characters allowed, which is specified by maxLength().
1896          // The character counter is displayed when the number of characters that have been entered is greater than the maximum number of characters multiplied by 50% (threshold percentage).
1897          // When highlightBorder is set to false, the text box border turns red when the number of entered characters reaches the maximum. The default value is true.
1898        .onChange((value: string) => {
1899          this.text = value;
1900        })
1901    }.width('100%').height('100%').backgroundColor('#F1F3F5')
1902  }
1903}
1904```
1905
1906![TextInputCounter](figures/TextInputShowCounter.jpg)
1907
1908
1909### Example 6: Formatting Phone Numbers
1910
1911This example illustrates how to format phone numbers using the **onChange callback** API.
1912
1913```ts
1914// xxx.ets
1915@Entry
1916@Component
1917struct TextInputExample {
1918  @State submitValue: string = '';
1919  @State text: string = '';
1920  public readonly NUM_TEXT_MAXSIZE_LENGTH = 13;
1921  @State teleNumberNoSpace: string = "";
1922  @State nextCaret: number = -1; // Used to record the position for the next caret setting.
1923  @State actualCh: number = -1; // Used to record the insertion or deletion position relative to the i-th digit of the caret.
1924  @State lastCaretPosition: number = 0;
1925  @State lastCaretPositionEnd: number = 0;
1926  controller: TextInputController = new TextInputController();
1927
1928  isEmpty(str?: string): boolean {
1929    return str == 'undefined' || !str || !new RegExp("[^\\s]").test(str);
1930  }
1931
1932  checkNeedNumberSpace(numText: string) {
1933    let isSpace: RegExp = new RegExp('[\\+;,#\\*]', 'g');
1934    let isRule: RegExp = new RegExp('^\\+.*');
1935
1936    if (isSpace.test(numText)) {
1937      // If the phone number contains special characters, no space is added.
1938      if (isRule.test(numText)) {
1939        return true;
1940      } else {
1941        return false;
1942      }
1943    }
1944    return true;
1945  }
1946
1947  removeSpace(str: string): string {
1948    if (this.isEmpty(str)) {
1949      return '';
1950    }
1951    return str.replace(new RegExp("[\\s]", "g"), '');
1952  }
1953
1954  setCaret() {
1955    if (this.nextCaret != -1) {
1956      console.log("to keep caret position right, change caret to", this.nextCaret);
1957      this.controller.caretPosition(this.nextCaret);
1958      this.nextCaret = -1;
1959    }
1960  }
1961
1962  calcCaretPosition(nextText: string) {
1963    let befNumberNoSpace: string = this.removeSpace(this.text);
1964    this.actualCh = 0;
1965    if (befNumberNoSpace.length < this.teleNumberNoSpace.length) { // Insertion scenario
1966      for (let i = 0; i < this.lastCaretPosition; i++) {
1967        if (this.text[i] != ' ') {
1968          this.actualCh += 1;
1969        }
1970      }
1971      this.actualCh += this.teleNumberNoSpace.length - befNumberNoSpace.length;
1972      console.log("actualCh: " + this.actualCh);
1973      for (let i = 0; i < nextText.length; i++) {
1974        if (nextText[i] != ' ') {
1975          this.actualCh -= 1;
1976          if (this.actualCh <= 0) {
1977            this.nextCaret = i + 1;
1978            break;
1979          }
1980        }
1981      }
1982    } else if (befNumberNoSpace.length > this.teleNumberNoSpace.length) { // Deletion scenario
1983      if (this.lastCaretPosition === this.text.length) {
1984        console.log("Caret at last, no need to change");
1985      } else if (this.lastCaretPosition === this.lastCaretPositionEnd) {
1986        // Scenario where the backspace key on the keyboard is used to delete characters one by one
1987        for (let i = this.lastCaretPosition; i < this.text.length; i++) {
1988          if (this.text[i] != ' ') {
1989            this.actualCh += 1;
1990          }
1991        }
1992        for (let i = nextText.length - 1; i >= 0; i--) {
1993          if (nextText[i] != ' ') {
1994            this.actualCh -= 1;
1995            if (this.actualCh <= 0) {
1996              this.nextCaret = i;
1997              break;
1998            }
1999          }
2000        }
2001      } else {
2002        // When cutting or selecting text with a handle to delete multiple characters at once
2003        this.nextCaret = this.lastCaretPosition; // Maintain the caret position.
2004      }
2005    }
2006  }
2007
2008  build() {
2009    Column() {
2010      Row() {
2011        TextInput({ text: `${this.text}`, controller: this.controller }).type(InputType.PhoneNumber).height('48vp')
2012          .onChange((number: string) => {
2013            this.teleNumberNoSpace = this.removeSpace(number);
2014            let nextText: string = "";
2015            if (this.teleNumberNoSpace.length > this.NUM_TEXT_MAXSIZE_LENGTH - 2) {
2016              nextText = this.teleNumberNoSpace;
2017            } else if (this.checkNeedNumberSpace(number)) {
2018              if (this.teleNumberNoSpace.length <= 3) {
2019                nextText = this.teleNumberNoSpace;
2020              } else {
2021                let split1: string = this.teleNumberNoSpace.substring(0, 3);
2022                let split2: string = this.teleNumberNoSpace.substring(3);
2023                nextText = split1 + ' ' + split2;
2024                if (this.teleNumberNoSpace.length > 7) {
2025                  split2 = this.teleNumberNoSpace.substring(3, 7);
2026                  let split3: string = this.teleNumberNoSpace.substring(7);
2027                  nextText = split1 + ' ' + split2 + ' ' + split3;
2028                }
2029              }
2030            } else {
2031              nextText = number;
2032            }
2033            console.log("onChange Triggered:" + this.text + "|" + nextText + "|" + number);
2034            if (this.text === nextText && nextText === number) {
2035              // The number has been formatted. Changing the caret position at this time will not reset the number.
2036              this.setCaret();
2037            } else {
2038              this.calcCaretPosition(nextText);
2039            }
2040            this.text = nextText;
2041          })
2042          .onTextSelectionChange((selectionStart, selectionEnd) => {
2043            // Record the caret position.
2044            console.log("selection change: ", selectionStart, selectionEnd);
2045            this.lastCaretPosition = selectionStart;
2046            this.lastCaretPositionEnd = selectionEnd;
2047          })
2048      }
2049    }
2050    .width('100%')
2051    .height("100%")
2052  }
2053}
2054```
2055![phone_example](figures/phone_number.PNG)
2056
2057### Example 7: Setting Text Wrapping Rules
2058
2059This example demonstrates the effects of different text wrapping rules using the **wordBreak** attribute.
2060
2061```ts
2062// xxx.ets
2063@Entry
2064@Component
2065struct TextInputExample {
2066  @State textStrEn: string =
2067    'This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.';
2068  @State textStrZn: string =
2069    'The TextArea component provides multi-line text input and automatically wraps text to ensure that no line extends beyond the component's width.\nWhen the height is not set, the component has no default height and adapts to the content height. When the width is not set, it defaults to the maximum width.';';
2070
2071  build() {
2072    Row() {
2073      Column() {
2074        Text("WordBreakType as NORMAL in the inline input style:").fontSize(16).fontColor(0xCCCCCC)
2075        TextInput({
2076          text: this.textStrEn
2077        })
2078          .margin(10)
2079          .fontSize(16)
2080          .style(TextInputStyle.Inline)// Inline input style
2081          .wordBreak(WordBreak.NORMAL) // This attribute does not take effect for the non-inline input style.
2082
2083        Text("WordBreakType as BREAK_ALL in the inline input style:").fontSize(16).fontColor(0xCCCCCC)
2084        TextInput({
2085          text: this.textStrEn
2086        })
2087          .margin(10)
2088          .fontSize(16)
2089          .style(TextInputStyle.Inline)
2090          .wordBreak(WordBreak.BREAK_ALL)
2091
2092        Text("WordBreakType as BREAK_WORD in the inline input style:").fontSize(16).fontColor(0xCCCCCC)
2093        TextInput({
2094          text: this.textStrEn
2095        })
2096          .margin(10)
2097          .fontSize(16)
2098          .style(TextInputStyle.Inline)
2099          .wordBreak(WordBreak.BREAK_WORD)
2100      }.width('100%')
2101    }.height('100%').margin(10)
2102  }
2103}
2104```
2105![TextInputWordBreak](figures/TextInputWordBreak.png)
2106
2107### Example 8: Setting the Text Style
2108
2109This example showcases various text styles by using the **lineHeight**, **letterSpacing**, and **decoration** attributes.
2110
2111```ts
2112// xxx.ets
2113@Entry
2114@Component
2115struct TextInputExample {
2116  build() {
2117    Row() {
2118      Column() {
2119        Text('lineHeight').fontSize(9).fontColor(0xCCCCCC)
2120        TextInput({ text: 'lineHeight unset' })
2121          .border({ width: 1 }).padding(10).margin(5)
2122        TextInput({ text: 'lineHeight 15' })
2123          .border({ width: 1 }).padding(10).margin(5).lineHeight(15)
2124        TextInput({ text: 'lineHeight 30' })
2125          .border({ width: 1 }).padding(10).margin(5).lineHeight(30)
2126
2127        Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC)
2128        TextInput({ text: 'letterSpacing 0' })
2129          .border({ width: 1 }).padding(5).margin(5).letterSpacing(0)
2130        TextInput({ text: 'letterSpacing 3' })
2131          .border({ width: 1 }).padding(5).margin(5).letterSpacing(3)
2132        TextInput({ text: 'letterSpacing -1' })
2133          .border({ width: 1 }).padding(5).margin(5).letterSpacing(-1)
2134
2135        Text('decoration').fontSize(9).fontColor(0xCCCCCC)
2136        TextInput({ text: 'LineThrough, Red' })
2137          .border({ width: 1 }).padding(5).margin(5)
2138          .decoration({ type: TextDecorationType.LineThrough, color: Color.Red })
2139        TextInput({ text: 'Overline, Red, DASHED' })
2140          .border({ width: 1 }).padding(5).margin(5)
2141          .decoration({ type: TextDecorationType.Overline, color: Color.Red, style: TextDecorationStyle.DASHED })
2142        TextInput({ text: 'Underline, Red, WAVY' })
2143          .border({ width: 1 }).padding(5).margin(5)
2144          .decoration({ type: TextDecorationType.Underline, color: Color.Red, style: TextDecorationStyle.WAVY })
2145      }.height('90%')
2146    }
2147    .width('90%')
2148    .margin(10)
2149  }
2150}
2151```
2152
2153![TextInputDecoration](figures/textinput_decoration.png)
2154
2155### Example 9: Setting Text Feature Effects
2156
2157This example demonstrates how to use the **fontFeature** attribute to display text with various typographic features.
2158
2159```ts
2160// xxx.ets
2161@Entry
2162@Component
2163struct TextInputExample {
2164  @State text1: string = 'This is ss01 on : 0123456789';
2165  @State text2: string = 'This is ss01 off: 0123456789';
2166
2167  build() {
2168    Column() {
2169      TextInput({ text: this.text1 })
2170        .fontSize(20)
2171        .margin({ top: 200 })
2172        .fontFeature("\"ss01\" on")
2173      TextInput({ text: this.text2 })
2174        .margin({ top: 10 })
2175        .fontSize(20)
2176        .fontFeature("\"ss01\" off")
2177    }
2178    .width("90%")
2179    .margin("5%")
2180  }
2181}
2182```
2183
2184![fontFeature](figures/textInputFontFeature.png)
2185
2186### Example 10: Setting Custom Keyboard Avoidance
2187
2188This example illustrates the implementation of a custom keyboard that automatically adjusts its position to avoid covering the text box.
2189
2190```ts
2191// xxx.ets
2192@Entry
2193@Component
2194struct TextInputExample {
2195  controller: TextInputController = new TextInputController();
2196  @State inputValue: string = "";
2197  @State height1: string | number = '80%';
2198  @State supportAvoidance: boolean = true;
2199
2200  // Create a custom keyboard component.
2201  @Builder
2202  CustomKeyboardBuilder() {
2203    Column() {
2204      Row() {
2205        Button('x').onClick(() => {
2206          // Disable the custom keyboard.
2207          this.controller.stopEditing();
2208        }).margin(10)
2209      }
2210
2211      Grid() {
2212        ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item: number | string) => {
2213          GridItem() {
2214            Button(item + "")
2215              .width(110).onClick(() => {
2216              this.inputValue += item;
2217            })
2218          }
2219        })
2220      }.maxCount(3).columnsGap(10).rowsGap(10).padding(5)
2221    }.backgroundColor(Color.Gray)
2222  }
2223
2224  build() {
2225    Column() {
2226      Row() {
2227        Button("20%")
2228          .fontSize(24)
2229          .onClick(() => {
2230            this.height1 = "20%";
2231          })
2232        Button("80%")
2233          .fontSize(24)
2234          .margin({ left: 20 })
2235          .onClick(() => {
2236            this.height1 = "80%";
2237          })
2238      }
2239      .justifyContent(FlexAlign.Center)
2240      .alignItems(VerticalAlign.Bottom)
2241      .height(this.height1)
2242      .width("100%")
2243      .padding({ bottom: 50 })
2244
2245      TextInput({ controller: this.controller, text: this.inputValue })// Bind a custom keyboard.
2246        .customKeyboard(this.CustomKeyboardBuilder(), { supportAvoidance: this.supportAvoidance })
2247        .margin(10)
2248        .border({ width: 1 })
2249
2250    }
2251  }
2252}
2253```
2254
2255![CustomTextInputType](figures/textInputCustomKeyboard.gif)
2256
2257### Example 11: Setting Text Auto-Adaptation
2258
2259This example showcases the implementation of text auto-adaptation features using the **minFontSize**, **maxFontSize**, and **heightAdaptivePolicy** attributes.
2260
2261```ts
2262// xxx.ets
2263@Entry
2264@Component
2265struct TextInputExample {
2266  build() {
2267    Row() {
2268      Column() {
2269        Text('heightAdaptivePolicy').fontSize(9).fontColor(0xCCCCCC)
2270        TextInput({ text: 'This is the text without the height adaptive policy set' })
2271          .width('80%').height(50).borderWidth(1).margin(1)
2272        TextInput({ text: 'This is the text with the height adaptive policy set' })
2273          .width('80%')
2274          .height(50)
2275          .borderWidth(1)
2276          .margin(1)
2277          .minFontSize(4)
2278          .maxFontSize(40)
2279          .maxLines(3)
2280          .heightAdaptivePolicy(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
2281        TextInput({ text: 'This is the text with the height adaptive policy set' })
2282          .width('80%')
2283          .height(50)
2284          .borderWidth(1)
2285          .margin(1)
2286          .minFontSize(4)
2287          .maxFontSize(40)
2288          .maxLines(3)
2289          .heightAdaptivePolicy(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST)
2290        TextInput({ text: 'This is the text with the height adaptive policy set' })
2291          .width('80%')
2292          .height(50)
2293          .borderWidth(1)
2294          .margin(1)
2295          .minFontSize(4)
2296          .maxFontSize(40)
2297          .maxLines(3)
2298          .heightAdaptivePolicy(TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST)
2299      }.height('90%')
2300    }
2301    .width('90%')
2302    .margin(10)
2303  }
2304}
2305```
2306
2307![TextInputAdaptFont](figures/textinput_adapt_font.png)
2308
2309### Example 12: Setting Line Break Rules
2310
2311This example demonstrates the effects of different line break rules using the **wordBreak** attribute.
2312
2313```ts
2314// xxx.ets
2315@Entry
2316@Component
2317struct TextInputExample {
2318  @State message1: string =
2319    "They can be classified as built-in components–those directly provided by the ArkUI framework and custom components – those defined by developers" +
2320      "The built-in components include buttons radio buttonsprogress indicators and text You can set the rendering effectof thesecomponents in method chaining mode," +
2321      "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.";
2322  @State lineBreakStrategyIndex: number = 0;
2323  @State lineBreakStrategy: LineBreakStrategy[] =
2324    [LineBreakStrategy.GREEDY, LineBreakStrategy.HIGH_QUALITY, LineBreakStrategy.BALANCED];
2325  @State lineBreakStrategyStr: string[] = ['GREEDY', 'HIGH_QUALITY', 'BALANCED'];
2326
2327  build() {
2328    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
2329      Text('lineBreakStrategy').fontSize(9).fontColor(0xCCCCCC)
2330      TextInput({ text: this.message1 })
2331        .fontSize(12)
2332        .border({ width: 1 })
2333        .padding(10)
2334        .width('100%')
2335        .maxLines(12)
2336        .style(TextInputStyle.Inline)
2337        .lineBreakStrategy(this.lineBreakStrategy[this.lineBreakStrategyIndex])
2338      Row() {
2339        Button('Current lineBreakStrategy value: ' + this.lineBreakStrategyStr[this.lineBreakStrategyIndex]).onClick(() => {
2340          this.lineBreakStrategyIndex++;
2341          if (this.lineBreakStrategyIndex > (this.lineBreakStrategyStr.length - 1)) {
2342            this.lineBreakStrategyIndex = 0;
2343          }
2344        })
2345      }
2346    }.height(700).width(370).padding({ left: 35, right: 35, top: 35 })
2347  }
2348}
2349```
2350
2351![textInputLineBreakStrategy](figures/textInputLineBreakStrategy.gif)
2352
2353### Example 13: Setting Insert and Delete Callbacks
2354This example showcases the implementation of insert and delete operations using the **onWillInsert**, **onDidInsert**, **onWillDelete**, and **onDidDelete** APIs.
2355```ts
2356// xxx.ets
2357@Entry
2358@Component
2359struct TextInputExample {
2360  @State insertValue: string = "";
2361  @State deleteValue: string = "";
2362  @State insertOffset: number = 0;
2363  @State deleteOffset: number = 0;
2364  @State deleteDirection: number = 0;
2365
2366  build() {
2367    Row() {
2368      Column() {
2369        TextInput({ text: "Insert callbacks" })
2370          .height(60)
2371          .onWillInsert((info: InsertValue) => {
2372            this.insertValue = info.insertValue;
2373            return true;
2374          })
2375          .onDidInsert((info: InsertValue) => {
2376            this.insertOffset = info.insertOffset;
2377          })
2378
2379        Text("insertValue:" + this.insertValue + "  insertOffset:" + this.insertOffset).height(30)
2380
2381        TextInput({ text: "Delete callbacks" })
2382          .height(60)
2383          .onWillDelete((info: DeleteValue) => {
2384            this.deleteValue = info.deleteValue;
2385            info.direction;
2386            return true;
2387          })
2388          .onDidDelete((info: DeleteValue) => {
2389            this.deleteOffset = info.deleteOffset;
2390            this.deleteDirection = info.direction;
2391          })
2392
2393        Text("deleteValue:" + this.deleteValue + "  deleteOffset:" + this.deleteOffset).height(30)
2394        Text("deleteDirection:" + (this.deleteDirection == 0 ? "BACKWARD" : "FORWARD")).height(30)
2395
2396      }.width('100%')
2397    }
2398    .height('100%')
2399  }
2400}
2401```
2402
2403![TextInputInsertAndDelete](figures/TextInputInsertAndDelete.PNG)
2404
2405### Example 14: Setting Custom Menu Extensions
2406
2407This example demonstrates how to use the **editMenuOptions** API to create custom menu extensions for text settings. It includes customizing text content, icons, and callbacks for these extensions.
2408
2409```ts
2410// xxx.ets
2411@Entry
2412@Component
2413struct TextInputExample {
2414  @State text: string = 'TextInput editMenuOptions'
2415  onCreateMenu = (menuItems: Array<TextMenuItem>) => {
2416    let item1: TextMenuItem = {
2417      content: 'custom1',
2418      icon: $r('app.media.startIcon'),
2419      id: TextMenuItemId.of('custom1'),
2420    };
2421    let item2: TextMenuItem = {
2422      content: 'custom2',
2423      id: TextMenuItemId.of('custom2'),
2424      icon: $r('app.media.startIcon'),
2425    };
2426    menuItems.push(item1);
2427    menuItems.unshift(item2);
2428    return menuItems;
2429  }
2430  onMenuItemClick = (menuItem: TextMenuItem, textRange: TextRange) => {
2431    if (menuItem.id.equals(TextMenuItemId.of("custom2"))) {
2432      console.log("Intercept id: custom2 start:" + textRange.start + "; end:" + textRange.end);
2433      return true;
2434    }
2435    if (menuItem.id.equals(TextMenuItemId.COPY)) {
2436      console.log("Intercept COPY start:" + textRange.start + "; end:" + textRange.end);
2437      return true;
2438    }
2439    if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) {
2440      console.log("Do not intercept SELECT_ALL start:" + textRange.start + "; end:" + textRange.end);
2441      return false;
2442    }
2443    return false;
2444  }
2445  @State editMenuOptions: EditMenuOptions = {
2446    onCreateMenu: this.onCreateMenu, onMenuItemClick: this.onMenuItemClick
2447  }
2448
2449  build() {
2450    Column() {
2451      TextInput({ text: this.text })
2452        .width('95%')
2453        .height(50)
2454        .editMenuOptions(this.editMenuOptions)
2455        .margin({ top: 100 })
2456    }
2457    .width("90%")
2458    .margin("5%")
2459  }
2460}
2461```
2462
2463![textInputEditMenuOptions](figures/textInputEditMenuOptions.gif)
2464
2465### Example 15: Setting a Symbol-Type Cancel Button
2466
2467This example demonstrates how to use the **cancelButton** attribute to customize the style of the symbol-type cancel button on the right side of the text box.
2468
2469```ts
2470import { SymbolGlyphModifier } from '@kit.ArkUI';
2471
2472// xxx.ets
2473@Entry
2474@Component
2475struct TextInputExample {
2476  @State text: string = '';
2477  symbolModifier: SymbolGlyphModifier =
2478    new SymbolGlyphModifier($r('sys.symbol.trash')).fontColor([Color.Red]).fontSize(16).fontWeight(FontWeight.Regular);
2479
2480  build() {
2481    Column() {
2482      TextInput({ text: this.text, placeholder: 'input your word...' })
2483        .cancelButton({
2484          style: CancelButtonStyle.CONSTANT,
2485          icon: this.symbolModifier
2486        })
2487    }
2488  }
2489}
2490```
2491
2492![cancelButton](figures/TextInputCancelButton_SymbolGlyphModifier.jpg)
2493
2494### Example 16: Setting Text Overflow
2495
2496This example demonstrates how to use **textOverflow**, **ellipsisMode**, and **style** to display excess content with an ellipsis (...) when the text is too long.
2497
2498```ts
2499// xxx.ets
2500@Entry
2501@Component
2502struct EllipsisModeExample {
2503  @State text: string = "As the sun begins to set, casting a warm golden hue across the sky," +
2504    "the world seems to slow down and breathe a sigh of relief. The sky is painted with hues of orange, " +
2505    " pink, and lavender, creating a breath taking tapestry that stretches as far as the eye can see." +
2506    "The air is filled with the sweet scent of blooming flowers, mingling with the earthy aroma of freshly turned soil."
2507  @State ellipsisModeIndex: number = 0
2508  @State ellipsisMode: (EllipsisMode | undefined | null)[] = [EllipsisMode.END, EllipsisMode.START, EllipsisMode.CENTER]
2509  @State ellipsisModeStr: string[] = ['END ', 'START', 'CENTER']
2510  @State textOverflowIndex: number = 0
2511  @State textOverflow: TextOverflow[] = [TextOverflow.Ellipsis, TextOverflow.Clip]
2512  @State textOverflowStr: string[] = ['Ellipsis', 'Clip']
2513  @State styleInputIndex: number = 0
2514  @State styleInput: TextInputStyle[] = [TextInputStyle.Inline, TextInputStyle.Default]
2515  @State styleInputStr: string[] = ['Inline', 'Default']
2516  build() {
2517    Row() {
2518      Column({ space: 20 }) {
2519        Text('Test TextInput').fontSize(30)
2520        TextInput({ text: this.text})
2521          .textOverflow( this.textOverflow[this.textOverflowIndex])
2522          .ellipsisMode( this.ellipsisMode[this.ellipsisModeIndex])
2523          .style(this.styleInput[this.styleInputIndex])
2524          .fontSize(30)
2525          .margin(30)
2526        Button('ellipsisMode Value: ' + this.ellipsisModeStr[this.ellipsisModeIndex]).onClick(() => {
2527          this.ellipsisModeIndex++
2528          if (this.ellipsisModeIndex > (this.ellipsisModeStr.length - 1)) {
2529            this.ellipsisModeIndex = 0
2530          }
2531        }).fontSize(20)
2532        Button('textOverflow Value: ' + this.textOverflowStr[this.textOverflowIndex]).onClick(() => {
2533          this.textOverflowIndex++
2534          if (this.textOverflowIndex > (this.textOverflowStr.length - 1)) {
2535            this.textOverflowIndex = 0
2536          }
2537        }).fontSize(20)
2538        Button('Style Value: ' + this.styleInputStr[this.styleInputIndex]).onClick(() => {
2539          this.styleInputIndex++
2540          if (this.styleInputIndex > (this.styleInputStr.length - 1)) {
2541            this.styleInputIndex = 0
2542          }
2543        }).fontSize(20)
2544      }
2545    }
2546  }
2547}
2548```
2549
2550![textInputEllipsisMode](figures/textInputEllipsisMode.png)
2551
2552### Example 17: Implementing Callbacks for Input Status Changes, Copy, Cut, Paste, and Content Scrolling
2553
2554This example demonstrates how to monitor input status changes, copy, cut, paste, and text content scrolling events using the **onEditChange**, **onCopy**, **onCut**, **onPaste**, and **onContentScroll** APIs.
2555
2556```ts
2557// xxx.ets
2558@Entry
2559@Component
2560struct TextInputExample {
2561  @State editStatus: boolean = false;
2562  @State copyValue: string = "";
2563  @State cutValue: string = "";
2564  @State pasteValue: string = "";
2565  @State totalOffsetX: number = 0;
2566  @State totalOffsetY: number = 0;
2567
2568  build() {
2569    Row() {
2570      Column() {
2571        TextInput({ text: "TextInput supports the callback on input status changes" })
2572          .height(60)
2573          .fontStyle(FontStyle.Italic)
2574          .fontWeight(FontWeight.Bold)
2575          .fontFamily("HarmonyOS Sans")
2576          .copyOption(CopyOptions.LocalDevice)
2577          .textAlign(TextAlign.Center)
2578          .selectedBackgroundColor(Color.Blue)
2579          .caretStyle({ width: '4vp' })
2580          .caretPosition(10)// Set the caret position in the TextInput component.
2581          .selectionMenuHidden(true)// Hide the system text selection menu.
2582          .onEditChange((status: boolean) => {
2583            this.editStatus = status;
2584          })
2585          .defaultFocus (true)// Set the TextInput component as the default focus.
2586          .enableKeyboardOnFocus (false)// Prevent the keyboard from appearing when the TextArea component obtains focus in a way other than clicking.
2587          .selectAll(false)
2588
2589        Text("editStatus:" + this.editStatus).height(30)
2590
2591        TextInput({ text: "TextInput supports the callback on copy operations" })
2592          .height(60)
2593          .fontStyle(FontStyle.Italic)
2594          .fontWeight(FontWeight.Bold)
2595          .fontFamily("HarmonyOS Sans")
2596          .copyOption(CopyOptions.LocalDevice)
2597          .textAlign(TextAlign.Center)
2598          .selectedBackgroundColor(Color.Blue)
2599          .caretStyle({ width: '4vp' })
2600          .onCopy((copyValue: string) => {
2601            this.copyValue = copyValue;
2602          })
2603
2604        Text("copyValue:" + this.copyValue).height(30)
2605
2606        TextInput({ text: "TextInput supports the callback on cut operations" })
2607          .height(60)
2608          .fontStyle(FontStyle.Italic)
2609          .fontWeight(FontWeight.Bold)
2610          .fontFamily("HarmonyOS Sans")
2611          .copyOption(CopyOptions.LocalDevice)
2612          .textAlign(TextAlign.Center)
2613          .selectedBackgroundColor(Color.Blue)
2614          .caretStyle({ width: '4vp' })
2615          .onCut((cutValue: string) => {
2616            this.cutValue = cutValue;
2617          })
2618
2619        Text("cutValue:" + this.cutValue).height(30)
2620
2621        TextInput({ text: "TextInput supports the callback on paste operations" })
2622          .height(60)
2623          .fontStyle(FontStyle.Italic)
2624          .fontWeight(FontWeight.Bold)
2625          .fontFamily("HarmonyOS Sans")
2626          .copyOption(CopyOptions.LocalDevice)
2627          .textAlign(TextAlign.Center)
2628          .selectedBackgroundColor(Color.Blue)
2629          .caretStyle({ width: '4vp' })
2630          .onPaste((pasteValue: string) => {
2631            this.pasteValue = pasteValue;
2632          })
2633
2634        Text("pasteValue:" + this.pasteValue).height(30)
2635
2636        TextInput({ text: "TextInput supports the callback on content scrolling: Scroll the text to see offset changes when the text width exceeds the text box width" })
2637          .height(60)
2638          .fontStyle(FontStyle.Italic)
2639          .fontWeight(FontWeight.Bold)
2640          .fontFamily("HarmonyOS Sans")
2641          .copyOption(CopyOptions.LocalDevice)
2642          .textAlign(TextAlign.Center)
2643          .selectedBackgroundColor(Color.Blue)
2644          .caretStyle({ width: '4vp' })
2645          .onContentScroll((totalOffsetX: number, totalOffsetY: number) => {
2646            this.totalOffsetX = totalOffsetX;
2647            this.totalOffsetY = totalOffsetY;
2648          })
2649
2650        Text("totalOffsetX:" + this.totalOffsetX + "  totalOffsetY:" + this.totalOffsetY).height(30)
2651
2652      }.width('100%')
2653    }
2654    .height('100%')
2655  }
2656}
2657```
2658
2659![TextInputEditChange](figures/TextInputEditChange.png)
2660
2661### Example 18: Setting the Minimum and Maximum Font Scale Factor
2662
2663This example demonstrates how to set the minimum and maximum font scale factor using **minFontScale** and **maxFontScale**.
2664
2665```ts
2666import { abilityManager, Configuration } from '@kit.AbilityKit';
2667import { BusinessError } from '@kit.BasicServicesKit';
2668
2669// xxx.ets
2670@Entry
2671@Component
2672export struct TextAreaExample11 {
2673  @State minFontScale: number = 0.85;
2674  @State maxFontScale: number = 2;
2675  @State changeValue: string = 'abcde';
2676
2677  build() {
2678    Column() {
2679      Column({ space: 30 }) {
2680        Text("System font size changes: small and large, small and large")
2681        TextArea({
2682          placeholder: 'The text area can hold an unlimited amount of text. input your word...',
2683        })
2684        // Set the minimum font scale factor; if the value is undefined, the text follows the default font scale factor.
2685          .minFontScale(0.85)
2686          // Set the maximum font scale factor; if the value is undefined, the text follows the default font scale factor.
2687          .maxFontScale(2)
2688      }.width('100%')
2689    }
2690  }
2691}
2692```
2693
2694```ts
2695Create a new directory named profile in the following path: AppScope/resources/base.
2696Inside the newly created profile directory, create a file named configuration.json.
2697Add the following JSON code to the **configuration.json** file:
2698{
2699  "configuration":{
2700    "fontSizeScale": "followSystem",
2701    "fontSizeMaxScale": "3.2"
2702}
2703}
2704```
2705
2706```ts
2707Modify the app.json5 file in AppScope as follows:
2708{
2709  "app": {
2710    "bundleName": "com.example.myapplication",
2711    "vendor": "example",
2712    "versionCode": 1000000,
2713    "versionName": "1.0.0",
2714    "icon": "$media:app_icon",
2715    "label": "$string:app_name",
2716    "configuration": "$profile:configuration"
2717  }
2718}
2719```
2720