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).|
39| controller<sup>8+</sup> | [TextInputController](#textinputcontroller8) | No   | Text input controller.                         |
40
41## Attributes
42
43Among the [universal attributes](ts-universal-attributes-size.md) and [universal text attributes](ts-universal-attributes-text-style.md), **fontColor**, **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are supported. In addition, the following attributes are supported.
44
45>  **NOTE**   
46>  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> } 
47>  
48>  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> }
49>
50>   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 received by the parent container. For details, see [Size](ts-universal-attributes-size.md).
51
52### type
53
54type(value: InputType)
55
56Sets the text box type.
57
58**Atomic service API**: This API can be used in atomic services since API version 11.
59
60**System capability**: SystemCapability.ArkUI.ArkUI.Full
61
62**Parameters**
63
64| Name| Type                           | Mandatory| Description                                     |
65| ------ | ------------------------------- | ---- | ----------------------------------------- |
66| value  | [InputType](#inputtype) | Yes  | Text box type.<br>Default value: **InputType.Normal**|
67
68### contentType<sup>12+</sup>
69
70contentType(value: ContentType)
71
72Sets the content type for autofill.
73
74**Atomic service API**: This API can be used in atomic services since API version 12.
75
76**System capability**: SystemCapability.ArkUI.ArkUI.Full
77
78**Parameters**
79
80| Name| Type                                 | Mandatory| Description          |
81| ------ | ------------------------------------- | ---- | -------------- |
82| value  | [ContentType](#contenttype12) | Yes  | Content type for autofill.|
83
84### placeholderColor
85
86placeholderColor(value: ResourceColor)
87
88Sets the placeholder text color.
89
90**Atomic service API**: This API can be used in atomic services since API version 11.
91
92**System capability**: SystemCapability.ArkUI.ArkUI.Full
93
94**Parameters**
95
96| Name| Type                                      | Mandatory| Description                                        |
97| ------ | ------------------------------------------ | ---- | -------------------------------------------- |
98| value  | [ResourceColor](ts-types.md#resourcecolor) | Yes  | Placeholder text color.<br>The default value follows the theme.|
99
100### placeholderFont
101
102placeholderFont(value?: Font)
103
104Sets the placeholder text style, including the font size, font width, font family, and font style. Currently, only the default font family is supported.
105
106**Atomic service API**: This API can be used in atomic services since API version 11.
107
108**System capability**: SystemCapability.ArkUI.ArkUI.Full
109
110**Parameters**
111
112| Name| Type                    | Mandatory| Description                 |
113| ------ | ------------------------ | ---- | --------------------- |
114| value  | [Font](ts-types.md#font) | No  | Placeholder text style.|
115
116### enterKeyType
117
118enterKeyType(value: EnterKeyType)
119
120Sets the type of the Enter key.
121
122**Atomic service API**: This API can be used in atomic services since API version 11.
123
124**System capability**: SystemCapability.ArkUI.ArkUI.Full
125
126**Parameters**
127
128| Name| Type                                            | Mandatory| Description                                            |
129| ------ | ------------------------------------------------ | ---- | ------------------------------------------------ |
130| value  | [EnterKeyType](ts-types.md#enterkeytype) | Yes  | Type of the Enter key.<br>Default value: **EnterKeyType.Done**|
131
132### caretColor
133
134caretColor(value: ResourceColor)
135
136Sets the color of the caret in the text box.
137
138**Atomic service API**: This API can be used in atomic services since API version 11.
139
140**System capability**: SystemCapability.ArkUI.ArkUI.Full
141
142**Parameters**
143
144| Name| Type                                      | Mandatory| Description                                  |
145| ------ | ------------------------------------------ | ---- | -------------------------------------- |
146| value  | [ResourceColor](ts-types.md#resourcecolor) | Yes  | Color of the caret in the text box.<br>Default value: **'#007DFF'**|
147
148>  **NOTE**    
149>   Since API version 12, this API can be used to set the text handle color, which is the same as the caret color.
150
151### maxLength
152
153maxLength(value: number)
154
155Sets the maximum number of characters for text input.
156
157**Atomic service API**: This API can be used in atomic services since API version 11.
158
159**System capability**: SystemCapability.ArkUI.ArkUI.Full
160
161**Parameters**
162
163| Name| Type  | Mandatory| Description                                                        |
164| ------ | ------ | ---- | ------------------------------------------------------------ |
165| value  | number | Yes  | Maximum number of characters for text input.<br>Default value: **Infinity**, indicating that there is no maximum number.<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.|
166
167### inputFilter<sup>8+</sup>
168
169inputFilter(value: ResourceStr, error?: (value: string) => void)
170
171Sets 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.
172
173Since 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.
174
175**Atomic service API**: This API can be used in atomic services since API version 11.
176
177**System capability**: SystemCapability.ArkUI.ArkUI.Full
178
179**Parameters**
180
181| Name| Type                                  | Mandatory| Description                              |
182| ------ | -------------------------------------- | ---- | ---------------------------------- |
183| value  | [ResourceStr](ts-types.md#resourcestr) | Yes  | Regular expression.                      |
184| error  | (value: string) => void                | No  | Filtered-out content to return when regular expression matching fails.|
185
186### copyOption<sup>9+</sup>
187
188copyOption(value: CopyOptions)
189
190Sets whether copy and paste is allowed. If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.
191
192For dragging, **copyOption** only restricts whether text is selected and does not involve the dragging scope.
193
194**Atomic service API**: This API can be used in atomic services since API version 11.
195
196**System capability**: SystemCapability.ArkUI.ArkUI.Full
197
198**Parameters**
199
200| Name| Type                                            | Mandatory| Description                                                        |
201| ------ | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
202| value  | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Yes  | Whether copy and paste is allowed.<br>Default value: **CopyOptions.LocalDevice**|
203
204### showPasswordIcon<sup>9+</sup>
205
206showPasswordIcon(value: boolean)
207
208Sets whether to display the password icon at the end of the password text box.
209
210**Atomic service API**: This API can be used in atomic services since API version 11.
211
212**System capability**: SystemCapability.ArkUI.ArkUI.Full
213
214**Parameters**
215
216| Name| Type   | Mandatory| Description                                                       |
217| ------ | ------- | ---- | ----------------------------------------------------------- |
218| value  | boolean | Yes  | Whether to display the password icon at the end of the password text box.<br>Default value: **true**|
219
220### style<sup>9+</sup>
221
222style(value: TextInputStyle  | TextContentStyle)
223
224Sets the text input style. The inline input style only supports **InputType.Normal**.
225
226**Atomic service API**: This API can be used in atomic services since API version 11.
227
228**System capability**: SystemCapability.ArkUI.ArkUI.Full
229
230**Parameters**
231
232| Name| Type                                                        | Mandatory| Description                                                        |
233| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
234| value  | [TextInputStyle](#textinputstyle9) \| [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Yes  | Text input style.<br>Default value: **TextInputStyle.Default**|
235
236### textAlign<sup>9+</sup>
237
238textAlign(value: TextAlign)
239
240Sets the horizontal alignment of the text.
241
242Available options are **TextAlign.Start**, **TextAlign.Center**, and **TextAlign.End**.
243
244To 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.
245
246**Atomic service API**: This API can be used in atomic services since API version 11.
247
248**System capability**: SystemCapability.ArkUI.ArkUI.Full
249
250**Parameters**
251
252| Name| Type                                       | Mandatory| Description                                                      |
253| ------ | ------------------------------------------- | ---- | ---------------------------------------------------------- |
254| value  | [TextAlign](ts-appendix-enums.md#textalign) | Yes  | Horizontal alignment of the text.<br>Default value: **TextAlign.Start**|
255
256### selectedBackgroundColor<sup>10+</sup>
257
258selectedBackgroundColor(value: ResourceColor)
259
260Sets the background color of the selected text. If the opacity is not set, a 20% opacity will be used.
261
262**Atomic service API**: This API can be used in atomic services since API version 11.
263
264**System capability**: SystemCapability.ArkUI.ArkUI.Full
265
266**Parameters**
267
268| Name| Type                                      | Mandatory| Description                                      |
269| ------ | ------------------------------------------ | ---- | ------------------------------------------ |
270| value  | [ResourceColor](ts-types.md#resourcecolor) | Yes  | Background color of the selected text.<br>By default, a 20% opacity is applied.|
271
272### caretStyle<sup>10+</sup>
273
274caretStyle(value: CaretStyle)
275
276Sets the caret style.
277
278**Atomic service API**: This API can be used in atomic services since API version 11.
279
280**System capability**: SystemCapability.ArkUI.ArkUI.Full
281
282**Parameters**
283
284| Name| Type                               | Mandatory| Description        |
285| ------ | ----------------------------------- | ---- | ------------ |
286| value  | [CaretStyle](ts-text-common.md#caretstyle10) | Yes  | Caret style.|
287
288### caretPosition<sup>10+</sup>
289
290caretPosition(value: number)
291
292Sets the caret position.
293
294**Atomic service API**: This API can be used in atomic services since API version 11.
295
296**System capability**: SystemCapability.ArkUI.ArkUI.Full
297
298**Parameters**
299
300| Name| Type  | Mandatory| Description        |
301| ------ | ------ | ---- | ------------ |
302| value  | number | Yes  | Caret position.|
303
304### showUnit<sup>10+</sup>
305
306showUnit(value: CustomBuilder)
307
308Sets the unit for content in the component. This attribute takes effect only when [showUnderline](#showunderline10) is set to **true**.
309
310**Atomic service API**: This API can be used in atomic services since API version 11.
311
312**System capability**: SystemCapability.ArkUI.ArkUI.Full
313
314**Parameters**
315
316| Name| Type                                       | Mandatory| Description                          |
317| ------ | ------------------------------------------- | ---- | ------------------------------ |
318| value  | [CustomBuilder](ts-types.md#custombuilder8) | Yes  | Unit to display as content in the text input.|
319
320### showError<sup>10+</sup>
321
322showError(value?: ResourceStr | undefined)
323
324Sets the error message displayed when an error occurs.
325
326If 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. See [Example 2](#example-2).
327
328**Atomic service API**: This API can be used in atomic services since API version 11.
329
330**System capability**: SystemCapability.ArkUI.ArkUI.Full
331
332**Parameters**
333
334| Name| Type                         | Mandatory| Description                                                        |
335| ------ | ----------------------------- | ---- | ------------------------------------------------------------ |
336| 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.|
337
338### showUnderline<sup>10+</sup>
339
340showUnderline(value: boolean)
341
342Sets 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.
343
344**Atomic service API**: This API can be used in atomic services since API version 11.
345
346**System capability**: SystemCapability.ArkUI.ArkUI.Full
347
348**Parameters**
349
350| Name| Type   | Mandatory| Description                              |
351| ------ | ------- | ---- | ---------------------------------- |
352| value  | boolean | Yes  | Whether to show an underline.<br>Default value: **false**|
353
354### underlineColor<sup>12+</sup>
355
356underlineColor(value: ResourceColor|UnderlineColor|undefined)
357
358Sets the color of the underline when it is shown.
359
360**Atomic service API**: This API can be used in atomic services since API version 12.
361
362**System capability**: SystemCapability.ArkUI.ArkUI.Full
363
364| Name| Type                                                        | Mandatory| Description                                                        |
365| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
366| 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|
367
368### passwordIcon<sup>10+</sup>
369
370passwordIcon(value: PasswordIcon)
371
372Sets the password icon to display at the end of the password text box.
373
374**Atomic service API**: This API can be used in atomic services since API version 11.
375
376**System capability**: SystemCapability.ArkUI.ArkUI.Full
377
378**Parameters**
379
380| Name| Type                                   | Mandatory| Description                                                        |
381| ------ | --------------------------------------- | ---- | ------------------------------------------------------------ |
382| 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.|
383
384### enableKeyboardOnFocus<sup>10+</sup>
385
386enableKeyboardOnFocus(value: boolean)
387
388Sets whether to enable the input method when the component obtains focus in a way other than clicking.
389
390 
391
392**Atomic service API**: This API can be used in atomic services since API version 11.
393
394**System capability**: SystemCapability.ArkUI.ArkUI.Full
395
396**Parameters**
397
398| Name| Type   | Mandatory| Description                                                       |
399| ------ | ------- | ---- | ----------------------------------------------------------- |
400| value  | boolean | Yes  | Whether to enable the input method when the component obtains focus in a way other than clicking.<br>Default value: **true**|
401
402### selectionMenuHidden<sup>10+</sup>
403
404selectionMenuHidden(value: boolean)
405
406Sets whether to hide the text selection menu when the text box is long-pressed, double-touched, or right-clicked.
407
408**Atomic service API**: This API can be used in atomic services since API version 11.
409
410**System capability**: SystemCapability.ArkUI.ArkUI.Full
411
412**Parameters**
413
414| Name| Type   | Mandatory| Description                                                        |
415| ------ | ------- | ---- | ------------------------------------------------------------ |
416| value  | boolean | Yes  | Whether to hide the text selection menu when the text box is long-pressed, double-touched, or right-clicked.<br>Default value: **false**|
417
418### barState<sup>10+</sup>
419
420barState(value: BarState)
421
422Sets the scrollbar state when the inline input style is used.
423
424**Atomic service API**: This API can be used in atomic services since API version 11.
425
426**System capability**: SystemCapability.ArkUI.ArkUI.Full
427
428**Parameters**
429
430| Name| Type                                     | Mandatory| Description                                                        |
431| ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ |
432| value  | [BarState](ts-appendix-enums.md#barstate) | Yes  | Scrollbar state when the inline input style is used.<br>Default value: **BarState.Auto**|
433
434### maxLines<sup>10+</sup>
435
436maxLines(value: number)
437
438Sets the maximum number of lines that can be displayed when the inline input style is used.
439
440**Atomic service API**: This API can be used in atomic services since API version 11.
441
442**System capability**: SystemCapability.ArkUI.ArkUI.Full
443
444**Parameters**
445
446| Name| Type                                     | Mandatory| Description                                                        |
447| ------ | ----------------------------------------- | ---- | ------------------------------------------------------------ |
448| 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, +∞)|
449
450### customKeyboard<sup>10+</sup>
451
452customKeyboard(value: CustomBuilder, options?: KeyboardOptions)
453
454Sets a custom keyboard.
455
456When a custom keyboard is set, activating the text box opens the specified custom component, instead of the system input method.
457
458The 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.
459
460The custom keyboard is displayed on top of the current page, without compressing or raising the page.
461
462The custom keyboard cannot obtain the focus, but it blocks gesture events.
463
464By 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.
465
466When a custom keyboard is set, the text box does not support camera input, even when the device supports.
467
468**Atomic service API**: This API can be used in atomic services since API version 11.
469
470**System capability**: SystemCapability.ArkUI.ArkUI.Full
471
472**Parameters**
473
474| Name               | Type                                       | Mandatory| Description                                                        |
475| --------------------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
476| 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.|
477| options<sup>12+</sup> | [KeyboardOptions](ts-basic-components-richeditor.md#keyboardoptions12)       | No  | Whether to support keyboard avoidance.                            |
478
479### enableAutoFill<sup>11+</sup>
480
481enableAutoFill(value: boolean)
482
483Sets whether to enable autofill.
484
485**Atomic service API**: This API can be used in atomic services since API version 12.
486
487**System capability**: SystemCapability.ArkUI.ArkUI.Full
488
489**Parameters**
490
491| Name| Type   | Mandatory| Description                                                        |
492| ------ | ------- | ---- | ------------------------------------------------------------ |
493| value  | boolean | Yes  | Whether to enable autofill.<br>**true**: enable<br>**false**: disable<br><br>Default value: **true**|
494
495### passwordRules<sup>11+</sup>
496
497passwordRules(value: string)
498
499Rules for generating passwords. When autofill is used, these rules are transparently transmitted to Password Vault for generating a new password.
500
501**Atomic service API**: This API can be used in atomic services since API version 12.
502
503**System capability**: SystemCapability.ArkUI.ArkUI.Full
504
505**Parameters**
506
507| Name| Type  | Mandatory| Description                |
508| ------ | ------ | ---- | -------------------- |
509| value  | string | Yes  | Rules for generating passwords.|
510
511### cancelButton<sup>11+</sup>
512
513cancelButton(value: { style?: CancelButtonStyle, icon?: IconOptions })
514
515Sets the style of the Cancel button on the right. This attribute is not available for the inline input style.
516
517**Atomic service API**: This API can be used in atomic services since API version 12.
518
519**System capability**: SystemCapability.ArkUI.ArkUI.Full
520
521**Parameters**
522
523| Name| Type                                                        | Mandatory| Description                                                        |
524| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
525| value  | {<br>style? : [CancelButtonStyle](ts-basic-components-search.md#cancelbuttonstyle10)<br>icon?: [IconOptions](ts-basic-components-search.md#iconoptions10) <br>} | Yes  | Style of the Cancel button on the right.<br>Default value:<br>{<br>style: CancelButtonStyle.INPUT<br>} |
526
527### selectAll<sup>11+</sup>
528
529selectAll(value: boolean)
530
531Sets whether to select all text in the initial state. This attribute is not available for the inline input style.
532
533**Atomic service API**: This API can be used in atomic services since API version 12.
534
535**System capability**: SystemCapability.ArkUI.ArkUI.Full
536
537**Parameters**
538
539| Name| Type   | Mandatory| Description                             |
540| ------ | ------- | ---- | --------------------------------- |
541| value  | boolean | Yes  | Whether to select all text in the initial state.<br>Default value: **false**|
542
543### showCounter<sup>11+</sup>
544
545showCounter(value: boolean, options?: InputCounterOptions)
546
547Sets the character counter displayed when the number of characters entered exceeds the threshold.
548
549**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.
550
551It 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**.
552
553The character counter is not displayed for text boxes in inline or password input style.
554
555**Atomic service API**: This API can be used in atomic services since API version 11.
556
557**System capability**: SystemCapability.ArkUI.ArkUI.Full
558
559**Parameters**
560
561| Name               | Type                                                 | Mandatory| Description            |
562| --------------------- | ----------------------------------------------------- | ---- | ---------------- |
563| value                 | boolean                                               | Yes  | Whether to display the character counter.|
564| options<sup>11+</sup> | [InputCounterOptions](ts-types.md#inputcounteroptions11) | No  | Threshold percentage of the character counter.|
565
566### lineHeight<sup>12+</sup>
567
568lineHeight(value: number | string | Resource)
569
570Sets 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.
571
572**Atomic service API**: This API can be used in atomic services since API version 12.
573
574**System capability**: SystemCapability.ArkUI.ArkUI.Full
575
576**Parameters**
577
578| Name| Type                                                        | Mandatory| Description            |
579| ------ | ------------------------------------------------------------ | ---- | ---------------- |
580| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Text line height.|
581
582### decoration<sup>12+</sup>
583
584decoration(value: TextDecorationOptions)
585
586Sets the color, type, and style of the text decorative line. This attribute does not take effect for the password input mode.
587
588**Atomic service API**: This API can be used in atomic services since API version 12.
589
590**System capability**: SystemCapability.ArkUI.ArkUI.Full
591
592**Parameters**
593
594| Name| Type                                                        | Mandatory| Description                                                        |
595| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
596| 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>} |
597
598### letterSpacing<sup>12+</sup>
599
600letterSpacing(value: number | string | Resource)
601
602Sets the letter spacing for a text style. If the value specified is a percentage or 0, the default value is used.
603
604If 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.
605
606**Atomic service API**: This API can be used in atomic services since API version 12.
607
608**System capability**: SystemCapability.ArkUI.ArkUI.Full
609
610**Parameters**
611
612| Name| Type                      | Mandatory| Description          |
613| ------ | -------------------------- | ---- | -------------- |
614| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Letter spacing.|
615
616### fontFeature<sup>12+</sup>
617
618fontFeature(value: string)
619
620Sets the font feature, for example, monospaced digits.
621
622Format: normal \| \<feature-tag-value\>
623
624Format of **\<feature-tag-value\>**: \<string\> \[ \<integer\> \| on \| off ]
625
626There can be multiple **\<feature-tag-value\>** values, which are separated by commas (,).
627
628For example, the input format for monospaced clock fonts is "ss01" on.
629
630**Atomic service API**: This API can be used in atomic services since API version 12.
631
632**System capability**: SystemCapability.ArkUI.ArkUI.Full
633
634**Parameters**
635
636| Name| Type  | Mandatory| Description          |
637| ------ | ------ | ---- | -------------- |
638| value  | string | Yes  | Font feature.|
639
640For details about the supported font features, see [Font Feature List](ts-basic-components-text.md#fontfeature12).
641Font 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.
642For 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/).
643
644>  **NOTE**
645>  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**.
646
647### wordBreak<sup>12+</sup>
648
649wordBreak(value: WordBreak)
650
651Sets the word break rule. This attribute is effective for the inline input style, but does not apply to the placeholder text.
652
653**Atomic service API**: This API can be used in atomic services since API version 12.
654
655**System capability**: SystemCapability.ArkUI.ArkUI.Full
656
657**Parameters**
658
659| Name| Type                                         | Mandatory| Description                                         |
660| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
661| value  | [WordBreak](ts-appendix-enums.md#wordbreak11) | Yes  | Word break rule in the inline input style.<br>Default value: **WordBreak.BREAK_WORD**|
662
663>  **NOTE**
664>
665>  The component does not support the **clip** attribute. Therefore, setting this attribute does not affect text clipping.
666
667### textOverflow<sup>12+</sup>
668
669textOverflow(value: TextOverflow)
670
671Sets the display mode when the text is too long. This attribute is only available for the inline input style.
672
673Text is clipped at the transition between words. To clip text in the middle of a word, set **wordBreak** to **WordBreak.BREAK_ALL**.
674
675**TextOverflow.None** produces the same effect as **TextOverflow.Clip**.
676
677**Atomic service API**: This API can be used in atomic services since API version 12.
678
679**System capability**: SystemCapability.ArkUI.ArkUI.Full
680
681**Parameters**
682
683| Name| Type                                                         | Mandatory| Description                                                                                               |
684| ------ | ------------------------------------------------------------ | ---- | -------------------------------------------------------------------------------------------------- |
685| 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**                    |
686
687>  **NOTE** 
688>   The **TextInput** component does not support the **TextOverflow.MARQUEE** mode. If this attribute is set to **TextOverflow.MARQUEE**, **TextOverflow.Ellipsis** is used instead 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.
689
690### textIndent<sup>12+</sup>
691
692textIndent(value: Dimension)
693
694Sets the indent of the first line text.
695
696**Atomic service API**: This API can be used in atomic services since API version 12.
697
698**System capability**: SystemCapability.ArkUI.ArkUI.Full
699
700**Parameters**
701
702| Name| Type                                 | Mandatory| Description                        |
703| ------ | ------------------------------------ | ---- | ---------------------------- |
704| value  | [Dimension](ts-types.md#dimension10) | Yes  | Indent of the first line text.<br>Default value: **0**|
705
706### minFontSize<sup>12+</sup>
707
708minFontSize(value: number | string | Resource)
709
710Sets the minimum font size.
711
712For 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.
713
714When the adaptive font size is used, the **fontSize** settings do not take effect.
715
716**Atomic service API**: This API can be used in atomic services since API version 12.
717
718**System capability**: SystemCapability.ArkUI.ArkUI.Full
719
720**Parameters**
721
722| Name| Type                                                        | Mandatory| Description              |
723| ------ | ------------------------------------------------------------ | ---- | ------------------ |
724| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Minimum font size.|
725
726### maxFontSize<sup>12+</sup>
727
728maxFontSize(value: number | string | Resource)
729
730Sets the maximum font size.
731
732For 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.
733
734When the adaptive font size is used, the **fontSize** settings do not take effect.
735
736**Atomic service API**: This API can be used in atomic services since API version 12.
737
738**System capability**: SystemCapability.ArkUI.ArkUI.Full
739
740**Parameters**
741
742| Name| Type                                                        | Mandatory| Description              |
743| ------ | ------------------------------------------------------------ | ---- | ------------------ |
744| value  | number \| string \| [Resource](ts-types.md#resource) | Yes  | Maximum font size.|
745
746### heightAdaptivePolicy<sup>12+</sup>
747
748heightAdaptivePolicy(value: TextHeightAdaptivePolicy)
749
750Sets how the adaptive height is determined for the text in the inline input style.
751
752When 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.
753
754If 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**.
755
756**TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST** produces the same effect as **TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST**.
757
758When 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.
759
760>  **NOTE**
761>
762>  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.
763
764**Atomic service API**: This API can be used in atomic services since API version 12.
765
766**System capability**: SystemCapability.ArkUI.ArkUI.Full
767
768**Parameters**
769
770| Name| Type                                                        | Mandatory| Description                                                        |
771| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
772| value  | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | Yes  | How the adaptive height is determined for the text.<br>Default value: **TextHeightAdaptivePolicy.MAX_LINES_FIRST**|
773
774### showPassword<sup>12+</sup>
775
776showPassword(visible: boolean)
777
778Sets whether to show the password.
779
780This attribute takes effect only in password input mode.
781
782As the password icon has a built-in state for updating the password mode, you are advised to add state synchronization to [onSecurityStateChange](#onsecuritystatechange12).
783
784**Atomic service API**: This API can be used in atomic services since API version 12.
785
786**System capability**: SystemCapability.ArkUI.ArkUI.Full
787
788**Parameters**
789
790| Name| Type                                                        | Mandatory| Description                                                        |
791| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
792| visible  | boolean | Yes | Whether to show the password.<br>Default value: **false**|
793
794### lineBreakStrategy<sup>12+</sup>
795
796lineBreakStrategy(strategy: LineBreakStrategy)
797
798Sets the line break rule. This attribute takes effect when **wordBreak** is not set to **breakAll**. Hyphens are not supported.
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| 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.|
809
810### editMenuOptions<sup>12+</sup>
811
812editMenuOptions(editMenu: EditMenuOptions)
813
814Sets the extended options of the custom context menu on selection, including the text content, icon, and callback.
815
816**Atomic service API**: This API can be used in atomic services since API version 12.
817
818**System capability**: SystemCapability.ArkUI.ArkUI.Full
819
820**Parameters**
821
822| Name| Type                                         | Mandatory| Description                                         |
823| ------ | --------------------------------------------- | ---- | --------------------------------------------- |
824| editMenu  | [EditMenuOptions](ts-text-common.md#editmenuoptions) | Yes  | Extended options of the custom context menu on selection.|
825
826### enablePreviewText<sup>12+</sup>
827
828enablePreviewText(enable: boolean)
829
830Sets whether to enable preview text.
831
832**Atomic service API**: This API can be used in atomic services since API version 12.
833
834**System capability**: SystemCapability.ArkUI.ArkUI.Full
835
836**Parameters**
837
838| Name| Type   | Mandatory| Description                              |
839| ------ | ------- | ---- | ---------------------------------- |
840| enable | boolean | Yes  | Whether to enable preview text.<br>Default value: **true**|
841
842## InputType
843
844**System capability**: SystemCapability.ArkUI.ArkUI.Full
845
846| Name                         | Description                                                        |
847| ----------------------------- | ------------------------------------------------------------ |
848| 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.|
849| Password                      | Password input mode.<br>The value can contain digits, letters, underscores (_), spaces, and special characters. 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.|
850| 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.|
851| Number                        | Digit input mode.<br>**Atomic service API**: This API can be used in atomic services since API version 11.|
852| 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.|
853| 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.|
854| 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.|
855| 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 11.|
856| 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.|
857| URL<sup>12+</sup>  | URL input mode.<br>**Atomic service API**: This API can be used in atomic services since API version 12.|
858
859## ContentType<sup>12+</sup>
860
861Content type for autofill.
862
863**Atomic service API**: This API can be used in atomic services since API version 12.
864
865**System capability**: SystemCapability.ArkUI.ArkUI.Full
866
867| Name                      | Value  | Description                                                        |
868| -------------------------- | ---- | ------------------------------------------------------------ |
869| USER_NAME                  | 0    | Username. Password Vault, when enabled, can automatically save and fill in usernames.|
870| PASSWORD                   | 1    | Password. Password Vault, when enabled, can automatically save and fill in passwords.|
871| NEW_PASSWORD               | 2    | New password. Password Vault, when enabled, can automatically generate a new password.  |
872| FULL_STREET_ADDRESS        | 3    | Full street address. The scenario-based autofill feature, when enabled, can automatically save and fill in full street addresses.|
873| HOUSE_NUMBER               | 4    | House number. The scenario-based autofill feature, when enabled, can automatically save and fill in house numbers.|
874| DISTRICT_ADDRESS           | 5    | District and county. The scenario-based autofill feature, when enabled, can automatically save and fill in districts and counties.|
875| CITY_ADDRESS               | 6    | City. The scenario-based autofill feature, when enabled, can automatically save and fill in cities.|
876| PROVINCE_ADDRESS           | 7    | Province. The scenario-based autofill feature, when enabled, can automatically save and fill in provinces.|
877| COUNTRY_ADDRESS            | 8    | Country. The scenario-based autofill feature, when enabled, can automatically save and fill in countries.|
878| PERSON_FULL_NAME           | 9    | Full name. The scenario-based autofill feature, when enabled, can automatically save and fill in full names.|
879| PERSON_LAST_NAME           | 10   | Last name. The scenario-based autofill feature, when enabled, can automatically save and fill in last names.|
880| PERSON_FIRST_NAME          | 11   | First name. The scenario-based autofill feature, when enabled, can automatically save and fill in first names.|
881| PHONE_NUMBER               | 12   | Phone number. The scenario-based autofill feature, when enabled, can automatically save and fill in phone numbers.|
882| PHONE_COUNTRY_CODE         | 13   | Country code. The scenario-based autofill feature, when enabled, can automatically save and fill in country codes.|
883| 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.|
884| EMAIL_ADDRESS              | 15   | Email address. The scenario-based autofill feature, when enabled, can automatically save and fill in email addresses.|
885| BANK_CARD_NUMBER           | 16   | Bank card number. The scenario-based autofill feature, when enabled, can automatically save and fill in bank card numbers.|
886| ID_CARD_NUMBER             | 17   | ID card number. The scenario-based autofill feature, when enabled, can automatically save and fill in ID card numbers.|
887| NICKNAME                   | 23   | Nickname. The scenario-based autofill feature, when enabled, can automatically save and fill in nicknames.|
888| 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.|
889| FORMAT_ADDRESS             | 25   | Standard address. The scenario-based autofill feature, when enabled, can automatically save and fill in standard addresses.|
890
891## TextInputStyle<sup>9+</sup>
892
893**Atomic service API**: This API can be used in atomic services since API version 11.
894
895**System capability**: SystemCapability.ArkUI.ArkUI.Full
896
897| Name     | Description                                      |
898| ------- | ---------------------------------------- |
899| 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.     |
900| 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.|
901
902## PasswordIcon<sup>10+</sup>
903
904**Atomic service API**: This API can be used in atomic services since API version 11.
905
906**System capability**: SystemCapability.ArkUI.ArkUI.Full
907
908| Name| Type | Mandatory  | Description|
909| ---- | ----- | ---- | ---- |
910| onIconSrc  | string \| [Resource](ts-types.md#resource) | No   | Icon that can be used to hide the password in password input mode.|
911| offIconSrc | string \| [Resource](ts-types.md#resource) | No   | Icon that can be used to show the password in password input mode.|
912
913## Events
914
915In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
916
917### onChange
918
919onChange(callback: EditableTextOnChangeCallback)
920
921Called when the input in the text box changes.
922
923This event is triggered when any of the following conditions is met:
924
9251. Keyboard input is received.
926
9272. Paste and cut is performed.
928
9293. Ctrl+V is pressed.
930
931**Atomic service API**: This API can be used in atomic services since API version 11.
932
933**System capability**: SystemCapability.ArkUI.ArkUI.Full
934
935**Parameters**
936
937| Name| Type  | Mandatory| Description                |
938| ------ | ------ | ---- | -------------------- |
939| callback  | [EditableTextOnChangeCallback](ts-text-common.md#editabletextonchangecallback12) | Yes  | Callback invoked when the input in the text box changes.|
940
941### onSubmit
942
943onSubmit(callback: (enterKey: EnterKeyType, event: SubmitEvent) =&gt; void)
944
945Called when the Enter key on the keyboard is pressed.
946
947**Atomic service API**: This API can be used in atomic services since API version 11.
948
949**System capability**: SystemCapability.ArkUI.ArkUI.Full
950
951**Parameters**
952
953| Name             | Type                                            | Mandatory| Description                                                        |
954| ------------------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
955| enterKey            | [EnterKeyType](ts-types.md#enterkeytype) | Yes  | Type of the Enter key. If it is **EnterKeyType.NEW_LINE** and the text box is in inline input style, **onSubmit** is not triggered.|
956| event<sup>11+</sup> | [SubmitEvent](#submitevent11)         | Yes  | Submit event.                                                  |
957
958### onEditChanged<sup>(deprecated)</sup>
959
960onEditChanged(callback: (isEditing: boolean) =&gt; void)
961
962Called when the input status changes.
963
964This API is deprecated since API version 8. You are advised to use **onEditChange** instead.
965
966**System capability**: SystemCapability.ArkUI.ArkUI.Full
967
968**Parameters**
969
970| Name   | Type   | Mandatory| Description                |
971| --------- | ------- | ---- | -------------------- |
972| 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.|
973
974### onEditChange<sup>8+</sup>
975
976onEditChange(callback: (isEditing: boolean) =&gt; void)
977
978Called 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. If the value of **isEditing** is **true**, the text box is in the editing state.
979
980**Atomic service API**: This API can be used in atomic services since API version 11.
981
982**System capability**: SystemCapability.ArkUI.ArkUI.Full
983
984**Parameters**
985
986| Name   | Type   | Mandatory| Description                |
987| --------- | ------- | ---- | -------------------- |
988| 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.|
989
990### onCopy<sup>8+</sup>
991
992onCopy(callback: (value: string) =&gt; void)
993
994Called when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.
995
996**Atomic service API**: This API can be used in atomic services since API version 11.
997
998**System capability**: SystemCapability.ArkUI.ArkUI.Full
999
1000**Parameters**
1001
1002| Name   | Type   | Mandatory| Description            |
1003| --------- | ------- | ---- | ---------------- |
1004| value | string | Yes  | Text that is copied.|
1005
1006### onCut<sup>8+</sup>
1007
1008onCut(callback: (value: string) =&gt; void)
1009
1010Called when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.
1011
1012**Atomic service API**: This API can be used in atomic services since API version 11.
1013
1014**System capability**: SystemCapability.ArkUI.ArkUI.Full
1015
1016**Parameters**
1017
1018| Name   | Type   | Mandatory| Description            |
1019| --------- | ------- | ---- | ---------------- |
1020| value | string | Yes  | Text that is cut.|
1021
1022### onPaste<sup>8+</sup>
1023
1024onPaste(callback: (value: string, event: PasteEvent) =&gt; void)
1025
1026Called when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.
1027
1028**Atomic service API**: This API can be used in atomic services since API version 11.
1029
1030**System capability**: SystemCapability.ArkUI.ArkUI.Full
1031
1032**Parameters**
1033
1034| Name             | Type                                                        | Mandatory| Description                  |
1035| ------------------- | ------------------------------------------------------------ | ---- | ---------------------- |
1036| value               | string                                                       | Yes  | Text to be pasted.      |
1037| event<sup>11+</sup> | [PasteEvent](ts-basic-components-richeditor.md#pasteevent11) | No  | Custom paste event.|
1038
1039### onTextSelectionChange<sup>10+</sup>
1040
1041onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)
1042
1043Called when the position of the text selection changes or when the cursor position changes during the editing state.
1044
1045**Atomic service API**: This API can be used in atomic services since API version 11.
1046
1047**System capability**: SystemCapability.ArkUI.ArkUI.Full
1048
1049**Parameters**
1050
1051| Name        | Type  | Mandatory| Description                                   |
1052| -------------- | ------ | ---- | --------------------------------------- |
1053| selectionStart | number | Yes  | Start position of the selected text. The start position of text is **0**.|
1054| selectionEnd   | number | Yes  | End position of the selected text.                   |
1055
1056### onContentScroll<sup>10+</sup>
1057
1058onContentScroll(callback: (totalOffsetX: number, totalOffsetY: number) => void)
1059
1060Called when the text content is scrolled.
1061
1062**Atomic service API**: This API can be used in atomic services since API version 11.
1063
1064**System capability**: SystemCapability.ArkUI.ArkUI.Full
1065
1066**Parameters**
1067
1068| Name      | Type  | Mandatory| Description                              |
1069| ------------ | ------ | ---- | ---------------------------------- |
1070| totalOffsetX | number | Yes  | Offset in the X coordinate of the text in the content area, in px.|
1071| totalOffsetY | number | Yes  | Offset in the Y coordinate of the text in the content area, in px.|
1072
1073### onSecurityStateChange<sup>12+</sup>
1074
1075onSecurityStateChange(callback: Callback\<boolean>)
1076
1077Called when the password visibility changes.
1078
1079**Atomic service API**: This API can be used in atomic services since API version 12.
1080
1081**System capability**: SystemCapability.ArkUI.ArkUI.Full
1082
1083**Parameters**
1084
1085| Name      | Type  | Mandatory| Description                              |
1086| ------------ | ------ | ---- | ---------------------------------- |
1087| callback | Callback\<boolean> | Yes  | Callback used to return the result.|
1088
1089### onWillInsert<sup>12+</sup>
1090
1091onWillInsert(callback: Callback\<InsertValue, boolean>)
1092
1093Called when text is about to be inserted.
1094
1095**Atomic service API**: This API can be used in atomic services since API version 12.
1096
1097**System capability**: SystemCapability.ArkUI.ArkUI.Full
1098
1099**Parameters**
1100
1101| Name| Type                                                        | Mandatory| Description              |
1102| ------ | ------------------------------------------------------------ | ---- | ------------------ |
1103| 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 called for text preview.<br>It is available only for system input methods.|
1104
1105### onDidInsert<sup>12+</sup>
1106
1107onDidInsert(callback: Callback\<InsertValue>)
1108
1109Called when text is inserted.
1110
1111**Atomic service API**: This API can be used in atomic services since API version 12.
1112
1113**System capability**: SystemCapability.ArkUI.ArkUI.Full
1114
1115**Parameters**
1116
1117| Name| Type                                                        | Mandatory| Description              |
1118| ------ | ------------------------------------------------------------ | ---- | ------------------ |
1119| callback  | Callback\<[InsertValue](ts-text-common.md#insertvalue12)> | Yes  | Callback triggered when text is inserted.<br>It is available only for system input methods.|
1120
1121### onWillDelete<sup>12+</sup>
1122
1123onWillDelete(callback: Callback\<DeleteValue, boolean>)
1124
1125Called when text is about to be deleted.
1126
1127**Atomic service API**: This API can be used in atomic services since API version 12.
1128
1129**System capability**: SystemCapability.ArkUI.ArkUI.Full
1130
1131**Parameters**
1132
1133| Name| Type                                                        | Mandatory| Description              |
1134| ------ | ------------------------------------------------------------ | ---- | ------------------ |
1135| 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.|
1136
1137### onDidDelete<sup>12+</sup>
1138
1139onDidDelete(callback: Callback\<DeleteValue>)
1140
1141Called when text is deleted.
1142
1143**Atomic service API**: This API can be used in atomic services since API version 12.
1144
1145**System capability**: SystemCapability.ArkUI.ArkUI.Full
1146
1147**Parameters**
1148
1149| Name| Type                                                        | Mandatory| Description              |
1150| ------ | ------------------------------------------------------------ | ---- | ------------------ |
1151| callback  | Callback\<[DeleteValue](ts-text-common.md#deletevalue12)> | Yes  | Callback triggered when text is deleted.<br>It is available only for system input methods.|
1152
1153## TextInputController<sup>8+</sup>
1154
1155Inherits from [TextContentControllerBase](ts-types.md#textcontentcontrollerbase10).
1156
1157**Atomic service API**: This API can be used in atomic services since API version 11.
1158
1159**System capability**: SystemCapability.ArkUI.ArkUI.Full
1160
1161### Objects to Import
1162```
1163controller: TextInputController = new TextInputController()
1164```
1165
1166### constructor<sup>8+</sup>
1167
1168constructor()
1169
1170A constructor used to create a **TextInputController** object.
1171
1172**Atomic service API**: This API can be used in atomic services since API version 11.
1173
1174**System capability**: SystemCapability.ArkUI.ArkUI.Full
1175
1176### caretPosition<sup>8+</sup>
1177
1178caretPosition(value: number): void
1179
1180Sets the position of the caret.
1181
1182**Atomic service API**: This API can be used in atomic services since API version 11.
1183
1184**System capability**: SystemCapability.ArkUI.ArkUI.Full
1185
1186**Parameters**
1187
1188| Name  | Type  | Mandatory  | Description |
1189| ----- | ------ | ---- | ------ |
1190| value | number | Yes   | Length from the start of the string to the position where the caret is located.|
1191### setTextSelection<sup>10+</sup>
1192
1193setTextSelection(selectionStart: number, selectionEnd: number, options?: SelectionOptions): void
1194
1195Sets the text selection area, which will be highlighted.
1196
1197**Atomic service API**: This API can be used in atomic services since API version 11.
1198
1199**System capability**: SystemCapability.ArkUI.ArkUI.Full
1200
1201**Parameters**
1202
1203| Name | Type  | Mandatory  | Description |
1204| ------- | ------ | ---- | ----- |
1205| selectionStart | number | Yes   | Start position of the text selection range. The start position of text in the text box is 0.|
1206| selectionEnd   | number | Yes   | End position of the text selection range.|
1207| 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.|
1208
1209>  **NOTE**
1210>
1211>  If **selectionStart** or **selectionEnd** is set to **undefined**, the value **0** will be used.
1212>
1213>  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**.
1214>
1215>  If the selected text contains an emoji, the emoji is selected when its start position is within the text selection range.
1216
1217### stopEditing<sup>10+</sup>
1218
1219stopEditing(): void
1220
1221Exits the editing state.
1222
1223**Atomic service API**: This API can be used in atomic services since API version 11.
1224
1225**System capability**: SystemCapability.ArkUI.ArkUI.Full
1226
1227## UnderlineColor<sup>12+</sup>
1228
1229**Atomic service API**: This API can be used in atomic services since API version 12.
1230
1231**System capability**: SystemCapability.ArkUI.ArkUI.Full
1232
1233| Name| Type | Mandatory  | Description|
1234| ---- | ----- | ---- | ---- |
1235| 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.|
1236| 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.|
1237| 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.|
1238| 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.|
1239
1240## SubmitEvent<sup>11+</sup>
1241
1242Defines the user submission event.
1243
1244**Atomic service API**: This API can be used in atomic services since API version 11.
1245
1246**System capability**: SystemCapability.ArkUI.ArkUI.Full
1247
1248| Name| Type | Mandatory  | Description|
1249| ---- | ----- | ---- | ---- |
1250| keepEditableState | () => void | Yes  | Editing status of the text box.<br> When this API is called, the text box remains in editing state.|
1251| text              | string     | Yes  | Text in the text box.                                  |
1252
1253## Example
1254
1255### Example 1
1256This example demonstrates the basic usage of **TextInput**.
1257```ts
1258// xxx.ets
1259@Entry
1260@Component
1261struct TextInputExample {
1262  @State text: string = ''
1263  @State positionInfo: CaretOffset = { index: 0, x: 0, y: 0 }
1264  @State passwordState: boolean = false
1265  controller: TextInputController = new TextInputController()
1266
1267  build() {
1268    Column() {
1269      TextInput({ text: this.text, placeholder: 'input your word...', controller: this.controller })
1270        .placeholderColor(Color.Grey)
1271        .placeholderFont({ size: 14, weight: 400 })
1272        .caretColor(Color.Blue)
1273        .width('95%')
1274        .height(40)
1275        .margin(20)
1276        .fontSize(14)
1277        .fontColor(Color.Black)
1278        .inputFilter('[a-z]', (e) => {
1279          console.log(JSON.stringify(e))
1280        })
1281        .onChange((value: string) => {
1282          this.text = value
1283        })
1284      Text(this.text)
1285      Button('Set caretPosition 1')
1286        .margin(15)
1287        .onClick(() => {
1288          // Move the caret to after the first entered character.
1289          this.controller.caretPosition(1)
1290        })
1291      Button('Get CaretOffset')
1292        .margin(15)
1293        .onClick(() => {
1294          this.positionInfo = this.controller.getCaretOffset()
1295        })
1296      // Password text box.
1297      TextInput({ placeholder: 'input your password...' })
1298        .width('95%')
1299        .height(40)
1300        .margin(20)
1301        .type(InputType.Password)
1302        .maxLength(9)
1303        .showPasswordIcon(true)
1304        .showPassword(this.passwordState)
1305        .onSecurityStateChange(((isShowPassword: boolean) => {
1306          // Update the password visibility.
1307          console.info('isShowPassword',isShowPassword)
1308          this.passwordState = isShowPassword
1309        }))
1310      // Email address autofill.
1311      TextInput({ placeholder: 'input your email...' })
1312        .width('95%')
1313        .height(40)
1314        .margin(20)
1315        .contentType(ContentType.EMAIL_ADDRESS)
1316        .maxLength(9)
1317      // Inline-style text box.
1318      TextInput({ text: 'inline style' })
1319        .width('95%')
1320        .height(50)
1321        .margin(20)
1322        .borderRadius(0)
1323        .style(TextInputStyle.Inline)
1324    }.width('100%')
1325  }
1326}
1327```
1328
1329![TextInput](figures/TextInput.png)
1330
1331### Example 2
1332This example showcases the use of the **passwordIcon**, **showUnderline**, **showUnit**, and **showError** attributes.
1333```ts
1334@Entry
1335@Component
1336struct TextInputExample {
1337  @State PassWordSrc1: Resource = $r('app.media.onIcon')
1338  @State PassWordSrc2: Resource = $r('app.media.offIcon')
1339  @State TextError: string = ''
1340  @State Text: string = ''
1341  @State NameText: string = 'test'
1342
1343  @Builder itemEnd() {
1344    Select([{ value: 'KB' },
1345      { value: 'MB' },
1346      { value: 'GB' },
1347      { value: 'TB', }])
1348      .height("48vp")
1349      .borderRadius(0)
1350      .selected(2)
1351      .align(Alignment.Center)
1352      .value('MB')
1353      .font({ size: 20, weight: 500 })
1354      .fontColor('#182431')
1355      .selectedOptionFont({ size: 20, weight: 400 })
1356      .optionFont({ size: 20, weight: 400 })
1357      .backgroundColor(Color.Transparent)
1358      .responseRegion({ height: "40vp", width: "80%", x: '10%', y: '6vp' })
1359      .onSelect((index: number) => {
1360        console.info('Select:' + index)
1361      })
1362  }
1363
1364  build() {
1365    Column({ space: 20 }) {
1366      // Customize the password icon.
1367      TextInput({ placeholder: 'Custom password icon' })
1368        .type(InputType.Password)
1369        .width(380)
1370        .height(60)
1371        .passwordIcon({ onIconSrc: this.PassWordSrc1, offIconSrc: this.PassWordSrc2 })
1372      // Show an underline.
1373      TextInput({ placeholder: 'Underline style' })
1374        .showUnderline(true)
1375        .width(380)
1376        .height(60)
1377        .showError('Error')
1378        .showUnit(this.itemEnd)
1379
1380      Text (`User name: ${this.Text}`)
1381        .width('95%')
1382      TextInput({ placeholder: 'Enter user name', text: this.Text })
1383        .showUnderline(true)
1384        .width(380)
1385        .showError(this.TextError)
1386        .onChange((value: string) => {
1387          this.Text = value
1388        })
1389        .onSubmit(() => {// If the entered user name is incorrect, the text box will be cleared and the error message will be displayed.
1390          if (this.Text == this.NameText) {
1391            this.TextError = ''
1392          } else {
1393            this.TextError ='Incorrect user name.'
1394            this.Text = ''
1395          }
1396        })
1397
1398    }.width('100%')
1399  }
1400}
1401```
1402
1403![TextInputError](figures/TextInputError.png)
1404
1405### Example 3
1406This example illustrates how to bind a custom keyboard to the **TextInput** component.
1407```ts
1408// xxx.ets
1409@Entry
1410@Component
1411struct TextInputExample {
1412  controller: TextInputController = new TextInputController()
1413  @State inputValue: string = ""
1414
1415  // Create a custom keyboard component.
1416  @Builder CustomKeyboardBuilder() {
1417    Column() {
1418      Button('x').onClick(() => {
1419        // Disable the custom keyboard.
1420        this.controller.stopEditing()
1421      })
1422      Grid() {
1423        ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item:number|string) => {
1424          GridItem() {
1425            Button(item + "")
1426              .width(110).onClick(() => {
1427              this.inputValue += item
1428            })
1429          }
1430        })
1431      }.maxCount(3).columnsGap(10).rowsGap(10).padding(5)
1432    }.backgroundColor(Color.Gray)
1433  }
1434
1435  build() {
1436    Column() {
1437      TextInput({ controller: this.controller, text: this.inputValue })
1438        // Bind the custom keyboard.
1439        .customKeyboard(this.CustomKeyboardBuilder()).margin(10).border({ width: 1 }).height('48vp')
1440    }
1441  }
1442}
1443```
1444
1445![customKeyboard](figures/textInputCustomKeyboard.png)
1446
1447
1448### Example 4
1449This example demonstrates the use of the **cancelButton** API.
1450```ts
1451// xxx.ets
1452@Entry
1453@Component
1454struct ClearNodeExample {
1455  @State text: string = ''
1456  controller: TextInputController = new TextInputController()
1457
1458  build() {
1459    Column() {
1460      TextInput({ placeholder: 'input ...', controller: this.controller })
1461        .width(380)
1462        .height(60)
1463        .cancelButton({
1464          style: CancelButtonStyle.CONSTANT,
1465          icon: {
1466            size: 45,
1467            src: $r('app.media.icon'),
1468            color: Color.Blue
1469          }
1470        })
1471        .onChange((value: string) => {
1472          this.text = value
1473        })
1474    }
1475  }
1476}
1477```
1478
1479![cancelButton](figures/TextInputCancelButton.png)
1480
1481### Example 5
1482This example illustrates the use of a character counter with the **TextInput** component.
1483```ts
1484// xxx.ets
1485@Entry
1486@Component
1487struct TextInputExample {
1488  @State text: string = ''
1489  controller: TextInputController = new TextInputController()
1490
1491  build() {
1492    Column() {
1493      TextInput({ text: this.text, controller: this.controller })
1494        .placeholderFont({ size: 16, weight: 400 })
1495        .width(336)
1496        .height(56)
1497        .maxLength(6)
1498        .showUnderline(true)
1499		.showCounter(true, { thresholdPercentage: 50, highlightBorder: true })
1500		// The character counter is in this format: Number of characters that have been entered/Maximum number of characters allowed, which is specified by maxLength().
1501        // 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).
1502        // 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.
1503        .onChange((value: string) => {
1504          this.text = value
1505        })
1506    }.width('100%').height('100%').backgroundColor('#F1F3F5')
1507  }
1508}
1509```
1510
1511![TextInputCounter](figures/TextInputShowCounter.jpg)
1512
1513
1514### Example 6
1515This example presents how to format a telephone number as XXX XXXX XXXX using the **TextInput** component.
1516
1517```ts
1518@Entry
1519@Component
1520struct phone_example {
1521  @State submitValue: string = ''
1522  @State text: string = ''
1523  public readonly NUM_TEXT_MAXSIZE_LENGTH = 13
1524  @State teleNumberNoSpace: string = ""
1525  @State nextCaret: number = -1 // Used to record the position for the next caret setting
1526  @State actualCh: number = -1 // Used to record the insertion or deletion position relative to the i-th digit of the caret
1527  @State lastCaretPosition: number = 0
1528  @State lastCaretPositionEnd: number = 0
1529  controller: TextInputController = new TextInputController()
1530
1531  isEmpty(str?: string): boolean {
1532    return str == 'undefined' || !str || !new RegExp("[^\\s]").test(str)
1533  }
1534
1535  checkNeedNumberSpace(numText: string) {
1536    let isSpace: RegExp = new RegExp('[\\+;,#\\*]', 'g')
1537    let isRule: RegExp = new RegExp('^\\+.*')
1538
1539    if (isSpace.test(numText)) {
1540      // If the phone number contains special characters, no space is added.
1541      if (isRule.test(numText)) {
1542        return true
1543      } else {
1544        return false
1545      }
1546    }
1547    return true;
1548  }
1549
1550  removeSpace(str: string): string {
1551    if (this.isEmpty(str)) {
1552      return ''
1553    }
1554    return str.replace(new RegExp("[\\s]", "g"), '')
1555  }
1556
1557  setCaret() {
1558    if (this.nextCaret != -1) {
1559      console.log("to keep caret position right, change caret to", this.nextCaret)
1560      this.controller.caretPosition(this.nextCaret)
1561      this.nextCaret = -1
1562    }
1563  }
1564
1565  calcCaretPosition(nextText: string) {
1566    let befNumberNoSpace: string = this.removeSpace(this.text)
1567    this.actualCh = 0
1568    if (befNumberNoSpace.length < this.teleNumberNoSpace.length) { // Insertion scenario
1569      for (let i = 0; i < this.lastCaretPosition; i++) {
1570        if (this.text[i] != ' ') {
1571          this.actualCh += 1
1572        }
1573      }
1574      this.actualCh += this.teleNumberNoSpace.length - befNumberNoSpace.length
1575      console.log("actualCh: " + this.actualCh)
1576      for (let i = 0; i < nextText.length; i++) {
1577        if (nextText[i] != ' ') {
1578          this.actualCh -= 1
1579          if (this.actualCh <= 0) {
1580            this.nextCaret = i + 1
1581            break;
1582          }
1583        }
1584      }
1585    } else if (befNumberNoSpace.length > this.teleNumberNoSpace.length) { // Deletion scenario
1586      if (this.lastCaretPosition === this.text.length) {
1587        console.log("Caret at last, no need to change")
1588      } else if (this.lastCaretPosition === this.lastCaretPositionEnd) {
1589        // Scenario where the backspace key on the keyboard is used to delete characters one by one
1590        for (let i = this.lastCaretPosition; i < this.text.length; i++) {
1591          if (this.text[i] != ' ') {
1592            this.actualCh += 1
1593          }
1594        }
1595        for (let i = nextText.length - 1; i >= 0; i--) {
1596          if (nextText[i] != ' ') {
1597            this.actualCh -= 1
1598            if (this.actualCh <= 0) {
1599              this.nextCaret = i
1600              break;
1601            }
1602          }
1603        }
1604      } else {
1605        // When cutting or selecting text with a handle to delete multiple characters at once
1606        this.nextCaret = this.lastCaretPosition // Maintain the caret position.
1607      }
1608    }
1609  }
1610
1611  build() {
1612    Column() {
1613      Row() {
1614        TextInput({ text: `${this.text}`, controller: this.controller }).type(InputType.PhoneNumber).height('48vp')
1615          .onChange((number: string) => {
1616            this.teleNumberNoSpace = this.removeSpace(number);
1617            let nextText: string = ""
1618            if (this.teleNumberNoSpace.length > this.NUM_TEXT_MAXSIZE_LENGTH - 2) {
1619              nextText = this.teleNumberNoSpace
1620            } else if (this.checkNeedNumberSpace(number)) {
1621              if (this.teleNumberNoSpace.length <= 3) {
1622                nextText = this.teleNumberNoSpace
1623              } else {
1624                let split1: string = this.teleNumberNoSpace.substring(0, 3)
1625                let split2: string = this.teleNumberNoSpace.substring(3)
1626                nextText = split1 + ' ' + split2
1627                if (this.teleNumberNoSpace.length > 7) {
1628                  split2 = this.teleNumberNoSpace.substring(3, 7)
1629                  let split3: string = this.teleNumberNoSpace.substring(7)
1630                  nextText = split1 + ' ' + split2 + ' ' + split3
1631                }
1632              }
1633            } else {
1634              nextText = number
1635            }
1636            console.log("onChange Triggered:" + this.text + "|" + nextText + "|" + number)
1637            if (this.text === nextText && nextText === number) {
1638              // The number has been formatted. Changing the caret position at this time will not reset the number.
1639              this.setCaret()
1640            } else {
1641              this.calcCaretPosition(nextText)
1642            }
1643            this.text = nextText
1644          })
1645          .onTextSelectionChange((selectionStart, selectionEnd) => {
1646            // Record the caret position.
1647            console.log("selection change: ", selectionStart, selectionEnd)
1648            this.lastCaretPosition = selectionStart
1649            this.lastCaretPositionEnd = selectionEnd
1650          })
1651      }
1652    }
1653    .width('100%')
1654    .height("100%")
1655  }
1656}
1657```
1658![phone_example](figures/phone_number.PNG)
1659
1660### Example 7
1661
1662This example shows how to set the color of the underline when it is shown.
1663
1664```ts
1665@Entry
1666@Component
1667struct Index {
1668
1669  build() {
1670    Row() {
1671      Column() {
1672        TextInput({placeholder:'Placeholder text'})
1673          .showUnderline(true)
1674          .underlineColor({normal:Color.Orange,typing:Color.Green,error:Color.Red,disable:Color.Gray});
1675        TextInput({placeholder:'Placeholder text'})
1676          .showUnderline(true)
1677          .underlineColor(Color.Gray);
1678      }
1679      .width('100%')
1680    }
1681    .height('100%')
1682  }
1683}
1684```
1685
1686![UnderlineColor](figures/UnderlineColor.png)
1687
1688
1689### Example 8
1690This example shows how to set the **wordBreak** attribute for the **TextInput** component.
1691
1692```ts
1693// xxx.ets
1694@Entry
1695@Component
1696struct TextInputExample {
1697  build() {
1698    Column() {
1699      Text("WordBreakType as NORMAL in the inline input style:").fontSize(16).fontColor(0xFF0000)
1700      TextInput({
1701        text: 'This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.'
1702      })
1703        .fontSize(16)
1704        .style(TextInputStyle.Inline) // Inline input style
1705        .wordBreak(WordBreak.NORMAL) // This attribute does not take effect for the non-inline input style.
1706
1707      Text("WordBreakType as BREAK_ALL in the inline input style:").fontSize(16).fontColor(0xFF0000)
1708      TextInput({
1709        text: 'This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.'
1710      })
1711        .fontSize(16)
1712        .style(TextInputStyle.Inline)
1713        .wordBreak(WordBreak.BREAK_ALL)
1714
1715      Text("WordBreakType as BREAK_ALL in the inline input style:").fontSize(16).fontColor(0xFF0000)
1716      TextInput({
1717        text: 'In a multi-line text input component, when the text content entered exceeds the width of the component, it will automatically wrap to display.\nIf the height is not set, the component has no default height and will adapt to the height of the content. If the width is not set, it auto-fills the maximum width available.'
1718      })
1719        .fontSize(16)
1720        .style(TextInputStyle.Inline)
1721        .wordBreak(WordBreak.BREAK_ALL)
1722
1723      Text("WordBreakType as BREAK_WORD in the inline input style:").fontSize(16).fontColor(0xFF0000)
1724      TextInput({
1725        text: 'This is set wordBreak to WordBreak text Taumatawhakatangihangakoauauotamateaturipukakapikimaungahoronukupokaiwhenuakitanatahu.'
1726      })
1727        .fontSize(16)
1728        .style(TextInputStyle.Inline)
1729        .wordBreak(WordBreak.BREAK_WORD)
1730    }
1731  }
1732}
1733```
1734![TextInputWordBreak](figures/TextInputWordBreak.jpeg)
1735
1736### Example 9
1737
1738This example shows how to use the **lineHeight**, **letterSpacing**, and **decoration** attributes.
1739
1740```ts
1741@Entry
1742@Component
1743struct TextInputExample {
1744  build() {
1745    Row() {
1746      Column() {
1747        Text('lineHeight').fontSize(9).fontColor(0xCCCCCC)
1748        TextInput({text: 'lineHeight unset'})
1749          .border({ width: 1 }).padding(10).margin(5)
1750        TextInput({text: 'lineHeight 15'})
1751          .border({ width: 1 }).padding(10).margin(5).lineHeight(15)
1752        TextInput({text: 'lineHeight 30'})
1753          .border({ width: 1 }).padding(10).margin(5).lineHeight(30)
1754
1755        Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC)
1756        TextInput({text: 'letterSpacing 0'})
1757          .border({ width: 1 }).padding(5).margin(5).letterSpacing(0)
1758        TextInput({text: 'letterSpacing 3'})
1759          .border({ width: 1 }).padding(5).margin(5).letterSpacing(3)
1760        TextInput({text: 'letterSpacing -1'})
1761          .border({ width: 1 }).padding(5).margin(5).letterSpacing(-1)
1762
1763        Text('decoration').fontSize(9).fontColor(0xCCCCCC)
1764        TextInput({text: 'LineThrough, Red'})
1765          .border({ width: 1 }).padding(5).margin(5)
1766          .decoration({type: TextDecorationType.LineThrough, color: Color.Red})
1767        TextInput({text: 'Overline, Red, DASHED'})
1768          .border({ width: 1 }).padding(5).margin(5)
1769          .decoration({type: TextDecorationType.Overline, color: Color.Red, style: TextDecorationStyle.DASHED})
1770        TextInput({text: 'Underline, Red, WAVY'})
1771          .border({ width: 1 }).padding(5).margin(5)
1772          .decoration({type: TextDecorationType.Underline, color: Color.Red, style: TextDecorationStyle.WAVY})
1773      }.height('90%')
1774    }
1775    .width('90%')
1776    .margin(10)
1777  }
1778}
1779```
1780
1781![TextInputDecoration](figures/textinput_decoration.png)
1782
1783### Example 10
1784
1785This example shows how to set the **fontFeature** attribute, with a comparison between the ss01-enabled and ss01-disabled effects.
1786
1787```ts
1788@Entry
1789@Component
1790struct textInput {
1791  @State text1: string = 'This is ss01 on : 0123456789'
1792  @State text2: string = 'This is ss01 off: 0123456789'
1793
1794
1795  build() {
1796    Column(){
1797      TextInput({text: this.text1})
1798        .fontSize(20)
1799        .margin({top:200})
1800        .fontFeature("\"ss01\" on")
1801      TextInput({text : this.text2})
1802        .margin({top:10})
1803        .fontSize(20)
1804        .fontFeature("\"ss01\" off")
1805    }
1806    .width("90%")
1807    .margin("5%")
1808  }
1809}
1810```
1811
1812![fontFeature](figures/textInputFontFeature.png)
1813
1814### Example 11
1815
1816This example shows how to support custom keyboard avoidance.
1817
1818```ts
1819@Entry
1820@Component
1821struct Input {
1822  controller: TextInputController = new TextInputController()
1823  @State inputValue: string = ""
1824  @State height1:string|number = '80%'
1825  @State supportAvoidance:boolean = true;
1826  // Create a custom keyboard component.
1827  @Builder CustomKeyboardBuilder() {
1828    Column() {
1829      Row(){
1830        Button('x').onClick(() => {
1831          // Disable the custom keyboard.
1832          this.controller.stopEditing()
1833        }).margin(10)
1834      }
1835      Grid() {
1836        ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item:number|string) => {
1837          GridItem() {
1838            Button(item + "")
1839              .width(110).onClick(() => {
1840              this.inputValue += item
1841            })
1842          }
1843        })
1844      }.maxCount(3).columnsGap(10).rowsGap(10).padding(5)
1845    }.backgroundColor(Color.Gray)
1846  }
1847  build() {
1848    Column() {
1849      Row(){
1850        Button("20%")
1851          .fontSize(24)
1852          .onClick(()=>{
1853            this.height1 = "20%"
1854          })
1855        Button("80%")
1856          .fontSize(24)
1857          .margin({left:20})
1858          .onClick(()=>{
1859            this.height1 = "80%"
1860          })
1861      }
1862      .justifyContent(FlexAlign.Center)
1863      .alignItems(VerticalAlign.Bottom)
1864      .height(this.height1)
1865      .width("100%")
1866      .padding({bottom:50})
1867      TextInput({ controller: this.controller, text: this.inputValue })
1868        // Bind the custom keyboard.
1869        .customKeyboard(this.CustomKeyboardBuilder(),{ supportAvoidance: this.supportAvoidance }).margin(10).border({ width: 1 })
1870
1871    }
1872  }
1873}
1874```
1875
1876![CustomTextInputType](figures/textInputCustomKeyboard.gif)
1877
1878### Example 12
1879
1880This example shows how to set **minFontSize**, **maxFontSize**, and **heightAdaptivePolicy**.
1881
1882```ts
1883@Entry
1884@Component
1885struct TextInputExample {
1886  build() {
1887    Row() {
1888      Column() {
1889        Text('heightAdaptivePolicy').fontSize(9).fontColor(0xCCCCCC)
1890        TextInput({text: 'This is the text without the height adaptive policy set'})
1891          .width('80%').height(50).borderWidth(1).margin(1)
1892        TextInput({text: 'This is the text with the height adaptive policy set'})
1893          .width('80%').height(50).borderWidth(1).margin(1)
1894          .minFontSize(4)
1895          .maxFontSize(40)
1896          .maxLines(3)
1897          .heightAdaptivePolicy(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
1898        TextInput({text: 'This is the text with the height adaptive policy set'})
1899          .width('80%').height(50).borderWidth(1).margin(1)
1900          .minFontSize(4)
1901          .maxFontSize(40)
1902          .maxLines(3)
1903          .heightAdaptivePolicy(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST)
1904        TextInput({text: 'This is the text with the height adaptive policy set'})
1905          .width('80%').height(50).borderWidth(1).margin(1)
1906          .minFontSize(4)
1907          .maxFontSize(40)
1908          .maxLines(3)
1909          .heightAdaptivePolicy(TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST)
1910      }.height('90%')
1911    }
1912    .width('90%')
1913    .margin(10)
1914  }
1915}
1916```
1917
1918![TextInputAdaptFont](figures/textinput_adapt_font.png)
1919
1920### Example 13
1921This example shows how to set the **lineBreakStrategy** attribute, with a comparison of line break rules.
1922
1923```ts
1924@Entry
1925@Component
1926struct TextExample1 {
1927  @State message1: string = "They can be classified as built-in components–those directly provided by the ArkUI framework and custom components – those defined by developers" +
1928    "The built-in components include buttons radio buttonsprogress indicators and text You can set the rendering effectof thesecomponents in method chaining mode," +
1929    "page components are divided into independent UI units to implementindependent creation development and reuse of different units on pages making pages more engineering-oriented.";
1930
1931  build() {
1932    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start }) {
1933      Text('LineBreakStrategy.GREEDY').fontSize(9).fontColor(0xCCCCCC).width('90%').padding(10)
1934      TextInput({text: this.message1})
1935        .fontSize(12)
1936        .border({ width: 1 })
1937        .padding(10)
1938        .width('100%')
1939        .maxLines(5)
1940        .style(TextInputStyle.Inline)
1941        .lineBreakStrategy(LineBreakStrategy.GREEDY)
1942      Text('LineBreakStrategy.HIGH_QUALITY').fontSize(9).fontColor(0xCCCCCC).width('90%').padding(10)
1943      TextInput({text: this.message1})
1944        .fontSize(12)
1945        .border({ width: 1 })
1946        .padding(10)
1947        .width('100%')
1948        .maxLines(5)
1949        .style(TextInputStyle.Inline)
1950        .lineBreakStrategy(LineBreakStrategy.HIGH_QUALITY)
1951      Text('LineBreakStrategy.BALANCED').fontSize(9).fontColor(0xCCCCCC).width('90%').padding(10)
1952      TextInput({text: this.message1})
1953        .fontSize(12)
1954        .border({ width: 1 })
1955        .padding(10)
1956        .width('100%')
1957        .maxLines(5)
1958        .style(TextInputStyle.Inline)
1959        .lineBreakStrategy(LineBreakStrategy.BALANCED)
1960    }.height(700).width(370).padding({ left: 35, right: 35, top: 35 })
1961  }
1962}
1963```
1964
1965![textInputLineBreakStrategy](figures/textInputLineBreakStrategy.PNG)
1966
1967### Example 14
1968
1969This example shows how to use the insert and delete callbacks.
1970
1971```ts
1972// xxx.ets
1973@Entry
1974@Component
1975struct TextInputExample {
1976  @State insertValue: string = ""
1977  @State deleteValue: string = ""
1978  @State insertOffset: number = 0
1979  @State deleteOffset: number = 0
1980  @State deleteDirection: number = 0
1981
1982  build() {
1983    Row() {
1984      Column() {
1985        TextInput({ text: "Insert callbacks" })
1986          .height(60)
1987          .onWillInsert((info: InsertValue) => {
1988            this.insertValue = info.insertValue
1989            return true;
1990          })
1991          .onDidInsert((info: InsertValue) => {
1992            this.insertOffset = info.insertOffset
1993          })
1994
1995        Text("insertValue:" + this.insertValue + "  insertOffset:" + this.insertOffset).height(30)
1996
1997        TextInput({ text: "Delete callbacks" })
1998          .height(60)
1999          .onWillDelete((info: DeleteValue) => {
2000            this.deleteValue = info.deleteValue
2001            info.direction
2002            return true;
2003          })
2004          .onDidDelete((info: DeleteValue) => {
2005            this.deleteOffset = info.deleteOffset
2006            this.deleteDirection = info.direction
2007          })
2008
2009        Text("deleteValue:" + this.deleteValue + "  deleteOffset:" + this.deleteOffset).height(30)
2010        Text("deleteDirection:" + (this.deleteDirection == 0 ? "BACKWARD" : "FORWARD")).height(30)
2011
2012      }.width('100%')
2013    }
2014    .height('100%')
2015  }
2016}
2017```
2018
2019![TextInputInsertAndDelete](figures/TextInputInsertAndDelete.PNG)
2020
2021### Example 15
2022
2023This example shows how to set **editMenuOptions**.
2024
2025```ts
2026// xxx.ets
2027@Entry
2028@Component
2029struct TextInputExample {
2030  @State text: string = 'TextInput editMenuOptions'
2031
2032  onCreateMenu(menuItems: Array<TextMenuItem>) {
2033    menuItems.forEach((value, index) => {
2034      value.icon = $r('app.media.startIcon')
2035      if (value.id.equals(TextMenuItemId.COPY)) {
2036        value.content = "Copy_custom"
2037      }
2038      if (value.id.equals(TextMenuItemId.SELECT_ALL)) {
2039        value.content = "Select all_custom"
2040      }
2041    })
2042    let item1: TextMenuItem = {
2043      content: 'Custom 1',
2044      icon: $r('app.media.startIcon'),
2045      id: TextMenuItemId.of('Custom 1'),
2046    }
2047    let item2: TextMenuItem = {
2048      content: 'Custom 2',
2049      id: TextMenuItemId.of('Custom 2'),
2050      icon: $r('app.media.startIcon'),
2051    }
2052    menuItems.push(item1)
2053    menuItems.unshift(item2)
2054    return menuItems
2055  }
2056
2057  build() {
2058    Column() {
2059      TextInput({ text: this.text })
2060        .width('95%')
2061        .height(50)
2062        .editMenuOptions({
2063          onCreateMenu: this.onCreateMenu, onMenuItemClick: (menuItem: TextMenuItem, textRange: TextRange) => {
2064            if (menuItem.id.equals(TextMenuItemId.of("custom2"))) {
2065              console.log("Intercept id: custom2 start:" + textRange.start + "; end:" + textRange.end)
2066              return true;
2067            }
2068            if (menuItem.id.equals(TextMenuItemId.COPY)) {
2069              console.log("Intercept COPY start:" + textRange.start + "; end:" + textRange.end)
2070              return true;
2071            }
2072            if (menuItem.id.equals(TextMenuItemId.SELECT_ALL)) {
2073              console.log("Do not intercept SELECT_ALL start:" + textRange.start + "; end:" + textRange.end)
2074              return false;
2075            }
2076            return false;
2077          }
2078        })
2079        .margin({ top: 100 })
2080    }
2081    .width("90%")
2082    .margin("5%")
2083  }
2084}
2085```
2086
2087![textInputEditMenuOptions](figures/textInputEditMenuOptions.gif)
2088