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