ts-basic-components-textinput.md 19.0 KB
Newer Older
Z
zengyawen 已提交
1
# TextInput
Z
zengyawen 已提交
2

E
ester.zhou 已提交
3
The **\<TextInput>** component provides single-line text input.
4

E
ester.zhou 已提交
5
>  **NOTE**
E
ester.zhou 已提交
6
>
E
ester.zhou 已提交
7
>  This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
Z
zengyawen 已提交
8

Z
zengyawen 已提交
9 10

## Child Components
Z
zengyawen 已提交
11

E
ester.zhou 已提交
12
Not supported
Z
zengyawen 已提交
13

Z
zengyawen 已提交
14 15 16

## APIs

E
ester.zhou 已提交
17
TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: TextInputController})
Z
zengyawen 已提交
18

E
ester.zhou 已提交
19 20 21 22
**Parameters**

| Name                    | Type                                    | Mandatory  | Description           |
| ----------------------- | ---------------------------------------- | ---- | --------------- |
E
ester.zhou 已提交
23 24
| placeholder   | [ResourceStr](ts-types.md#resourcestr)       | No   | Text displayed when there is no input.     |
| text          | [ResourceStr](ts-types.md#resourcestr)       | No   | Current text input.<br>If the component has [stateStyles](ts-universal-attributes-polymorphic-style.md) or any other attribute that may trigger updating configured, you are advised to bind the state variable to the text in real time through the **onChange** event, 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).|
E
ester.zhou 已提交
25
| controller<sup>8+</sup> | [TextInputController](#textinputcontroller8) | No   | Text input controller.|
Z
zengyawen 已提交
26 27 28 29


## Attributes

E
ester.zhou 已提交
30
Among the [universal attributes](ts-universal-attributes-size.md) and [universal text attributes](ts-universal-attributes-text-style.md), **fontColor**, **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are supported. In addition, the following attributes are supported.
E
ester.zhou 已提交
31 32 33

| Name                      | Type                                    | Description                                      |
| ------------------------ | ---------------------------------------- | ---------------------------------------- |
34
| type                     | [InputType](#inputtype)     | Input box type.<br>Default value: **InputType.Normal**       |
E
ester.zhou 已提交
35
| placeholderColor         | [ResourceColor](ts-types.md#resourcecolor)     | Placeholder text color.<br>The default value follows the theme.  |
E
ester.zhou 已提交
36
| placeholderFont          | [Font](ts-types.md#font) | Placeholder text font.|
E
ester.zhou 已提交
37
| enterKeyType             | [EnterKeyType](#enterkeytype) | Type of the Enter key. Currently, only the default value is supported.<br>Default value: **EnterKeyType.Done**|
E
ester.zhou 已提交
38
| caretColor               | [ResourceColor](ts-types.md#resourcecolor)    | Color of the caret in the text box.<br>Default value: **'#007DFF'**                               |
E
ester.zhou 已提交
39
| maxLength                | number                                   | Maximum number of characters in the text input.                           |
E
ester.zhou 已提交
40
| inputFilter<sup>8+</sup> | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>error?: (value: string) =&gt; void<br>} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The regular expression can match single characters, but not strings.<br>- **value**: regular expression to set.<br>- **error**: filtered-out content to return when regular expression matching fails.|
E
ester.zhou 已提交
41 42
| copyOption<sup>9+</sup>  | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.<br>Default value: **CopyOptions.LocalDevice**<br>If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.|
| showPasswordIcon<sup>9+</sup> | boolean | Whether to display the password icon at the end of the password text box.<br>Default value: **true**|
E
ester.zhou 已提交
43
| style<sup>9+</sup> | [TextInputStyle](#textinputstyle9) \| [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Text input style.<br>Default value: **TextInputStyle.Default**|
E
ester.zhou 已提交
44
| textAlign<sup>9+</sup>   | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.<br>Default value: **TextAlign.Start**<br>**NOTE**<br>Available options are **TextAlign.Start**, **TextAlign.Center**, and **TextAlign.End**.<br>To 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. |
E
ester.zhou 已提交
45
| selectedBackgroundColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected text.<br>If the opacity is not set, the color is opaque. For example, **0x80000000** indicates black with 50% opacity.|
E
ester.zhou 已提交
46
| caretStyle<sup>10+</sup> | {<br>width: [Length](ts-types.md#length)<br>} | Caret style.                                       |
E
ester.zhou 已提交
47
| caretPosition<sup>10+</sup> | number | Caret position.|
E
ester.zhou 已提交
48
| showUnit<sup>10+</sup>                | [CustomBuilder](ts-types.md#CustomBuilder8)         | Unit for content in the component.<br>By default, there is no unit.|
E
ester.zhou 已提交
49
| showError<sup>10+</sup> | string \| undefined | Error message displayed when an error occurs.<br>By default, no error message is displayed.<br>**NOTE**<br>If the parameter type is string and the input content does not comply with specifications, the error message is displayed. If the parameter type is undefined, no error message is displayed. See [Example 2](#example-2).|
E
ester.zhou 已提交
50 51 52
| showUnderline<sup>10+</sup> | boolean | Whether to show an underline.<br>Default value: **false**|
| passwordIcon<sup>10+</sup> | [PasswordIcon](#passwordicon10) | Password icon to display at the end of the password text box.<br>By default, the system-provided icon is used.|
| enableKeyboardOnFocus<sup>10+</sup> | boolean | Whether to enable the input method when the component obtains focus.<br>Default value: **true**  |
E
ester.zhou 已提交
53
| selectionMenuHidden<sup>10+</sup> | boolean | Whether to display the text selection menu when the text box is long-pressed or right-clicked.<br>Default value: **false**|
E
ester.zhou 已提交
54 55 56
| barState<sup>10+</sup> | [BarState](ts-appendix-enums.md#BarState) | Scrollbar state when the inline input style is used.<br>Default value: **BarState.Auto**|
| maxLines<sup>10+</sup> | number | Maximum number of lines that can be displayed when the inline input style is used.<br>Default value: **3**|
| customKeyboard<sup>10+</sup> | [CustomBuilder](ts-types.md#custombuilder8) | Custom keyboard.<br>**NOTE**<br>When a custom keyboard is set, activating the text box opens the specified custom component, instead of the system input method, and the **enterKeyType** attribute setting for the system keyboard will not take effect.<br>The custom keyboard's height can be set through the **height** attribute of the custom component's root node, and its width is fixed at the default value.<br>The custom keyboard is displayed on top of the current page, without compressing or raising the page.<br>The custom keyboard cannot obtain the focus, but it blocks gesture events.<br>By 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.|
E
ester.zhou 已提交
57 58 59

>  **NOTE**
>
E
ester.zhou 已提交
60
>  The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows: <br>{<br> top: 8 vp,<br> right: 16 vp,<br> bottom: 8 vp,<br> left: 16 vp<br> }
E
ester.zhou 已提交
61 62 63 64 65 66 67 68 69 70 71

## EnterKeyType

| Name                 | Description       |
| ------------------- | --------- |
| Go     | The Enter key is labeled "Go."  |
| Search | The Enter key is labeled "Search." |
| Send   | The Enter key is labeled "Send." |
| Next   | The Enter key is labeled "Next."|
| Done   | The Enter key is labeled "Done."    |

E
ester.zhou 已提交
72
## InputType
E
ester.zhou 已提交
73 74 75 76

| Name                | Description           |
| ------------------ | ------------- |
| Normal   | Normal input mode.<br>The value can contain digits, letters, underscores (_), spaces, and special characters.|
E
ester.zhou 已提交
77
| Password | Password input mode. The value can contain digits, letters, underscores (_), spaces, and special characters. An eye icon is used to show or hide the password, and the password is hidden behind dots by default. The password input mode does not support underlines.|
E
ester.zhou 已提交
78
| Email    | Email address input mode. The value can contain digits, letters, underscores (_), and at signs (@). Only one at sign (@) is allowed.|
E
ester.zhou 已提交
79 80 81
| Number   | Digit input mode.     |
| PhoneNumber<sup>9+</sup> | Phone number input mode.<br>The value can contain digits, plus signs (+), hyphens (-), asterisks (*), and number signs (#). The length is not limited.|

E
ester.zhou 已提交
82
## TextInputStyle<sup>9+</sup>
E
ester.zhou 已提交
83 84 85

| Name                | Description           |
| ------------------ | ------------- |
E
ester.zhou 已提交
86
| 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.  |
E
ester.zhou 已提交
87
| 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.|
E
ester.zhou 已提交
88

E
ester.zhou 已提交
89 90 91 92 93 94 95
## PasswordIcon<sup>10+</sup>

| Name      | Type                                              | Mandatory| Description                                              |
| ---------- | -------------------------------------------------- | ---- | -------------------------------------------------- |
| onIconSrc  | string \|[Resource](ts-types.md#resource)| No  | Icon that can be used to hide the password in password input mode.|
| offIconSrc | string \|[Resource](ts-types.md#resource)| No  | Icon that can be used to show the password in password input mode.|

E
ester.zhou 已提交
96
## Events
E
ester.zhou 已提交
97

E
ester.zhou 已提交
98 99
In addition to the [universal events](ts-universal-events-click.md), the following events are supported.

E
ester.zhou 已提交
100
| Name                                                        | Description                                                    |
101
| ------------------------------------------------------------ | ------------------------------------------------------------ |
E
ester.zhou 已提交
102
| onChange(callback: (value: string) =&gt; void) | Triggered when the input in the text box changes.<br>**value**: text content.<br>This event is triggered when any of the following conditions is met:<br>1. Keyboard input is received.<br>2. Paste and cut is performed.<br>3. Ctrl+V is pressed.|
E
ester.zhou 已提交
103 104 105 106 107 108
| onSubmit(callback: (enterKey: EnterKeyType) =&gt; void) | Triggered when the Enter key on the keyboard is pressed. The return value is the current type of the Enter key.<br>**enterKeyType**: type of the Enter key. For details, see [EnterKeyType](#enterkeytype).|
| onEditChanged(callback: (isEditing: boolean) =&gt; void)<sup>(deprecated)</sup> | Triggered when the input status changes. Since API version 8, **onEditChange** is recommended.|
| onEditChange(callback: (isEditing: boolean) =&gt; void)<sup>8+</sup> | Triggered when the input status changes. When the cursor is placed in the text box, it is in the editing state. Otherwise, it is in the non-editing state. If the value of **isEditing** is **true**, text input is in progress.|
| onCopy(callback:(value: string) =&gt; void)<sup>8+</sup> | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be copied.|
| onCut(callback:(value: string) =&gt; void)<sup>8+</sup> | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be cut.|
| onPaste(callback:(value: string) =&gt; void)<sup>8+</sup> | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be pasted.|
E
ester.zhou 已提交
109 110
| onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)<sup>10+</sup> | Triggered when the text selection position changes.<br>**selectionStart**: start position of the text selection area. The start position of text in the text box is **0**.<br>**selectionEnd**: end position of the text selection area.|
| onContentScroll(callback: (totalOffsetX: number, totalOffsetY: number) => void)<sup>10+</sup> | Triggered when the text content is scrolled.<br>**totalOffsetX**: X coordinate offset of the text in the content area.<br>**totalOffsetY**: Y coordinate offset of the text in the content area.|
E
ester.zhou 已提交
111 112

## TextInputController<sup>8+</sup>
E
ester.zhou 已提交
113

E
ester.zhou 已提交
114
Implements the controller of the **\<TextInput>** component.
Z
zengyawen 已提交
115

E
ester.zhou 已提交
116
### Objects to Import
Z
zengyawen 已提交
117 118 119
```
controller: TextInputController = new TextInputController()
```
120
### caretPosition<sup>8+</sup>
Z
zengyawen 已提交
121 122 123

caretPosition(value: number): void

E
ester.zhou 已提交
124
Sets the position of the caret.
Z
zengyawen 已提交
125

E
ester.zhou 已提交
126
**Parameters**
Z
zengyawen 已提交
127

E
ester.zhou 已提交
128 129 130
| Name| Type| Mandatory| Description                              |
| ------ | -------- | ---- | -------------------------------------- |
| value  | number   | Yes  | Length from the start of the string to the position where the caret is located.|
E
ester.zhou 已提交
131 132 133 134 135 136 137
### setTextSelection<sup>10+</sup>

setTextSelection(selectionStart: number, selectionStart: number): void

Sets the text selection area, which will be highlighted.

**Parameters**
Z
zengyawen 已提交
138

E
ester.zhou 已提交
139 140
| Name        | Type| Mandatory| Description              |
| -------------- | -------- | ---- | ---------------------- |
E
ester.zhou 已提交
141 142
| selectionStart | number   | Yes  | Start position of the text selection range. The start position of text in the text box is 0.|
| selectionEnd   | number   | Yes  | End position of the text selection range.|
E
ester.zhou 已提交
143

E
ester.zhou 已提交
144 145 146 147 148 149
### stopEditing<sup>10+</sup>

stopEditing(): void

Exits the editing state.

E
ester.zhou 已提交
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
### getTextContentRect<sup>10+</sup>

getTextContentRect(): [RectResult](#rectresult10)

Obtains the position of the edited text area relative to the component and its size. The unit of the return value is pixel.

**Return value**

| Type      | Description      |
| -------------------  | -------- |
| [RectResult](#rectresult10) | Position of the edited text area relative to the component and its size.|

> **NOTE**
>
> - If no text is entered, the return value contains the position information, but the size is 0.
> - The position information is the offset of the first character relative to the editable area.

### RectResult<sup>10+</sup>

Describes the position and size.

| Parameter     | Type    | Description|
| ------- | ------ | ----------------------- |
| x     | number | X coordinate.|
| y     | number | Y coordinate.|
| width | number | Content width.|
| height | number | Content height.|


### getTextContentLineCount<sup>10+</sup>

getTextContentLineCount(): number

Obtains the number of lines of the edited text.

**Return value**

| Type | Description      |
| ----- | -------- |
| number| Number of lines of the edited text.|

Z
zengyawen 已提交
191 192
## Example

E
ester.zhou 已提交
193 194
### Example 1

E
ester.zhou 已提交
195 196
```ts
// xxx.ets
Z
zengyawen 已提交
197 198
@Entry
@Component
E
ester.zhou 已提交
199
struct TextInputExample {
Z
zengyawen 已提交
200
  @State text: string = ''
E
ester.zhou 已提交
201
  controller: TextInputController = new TextInputController()
Z
zengyawen 已提交
202 203 204

  build() {
    Column() {
E
ester.zhou 已提交
205
      TextInput({ text: this.text, placeholder: 'input your word...', controller: this.controller })
E
ester.zhou 已提交
206 207
        .placeholderColor(Color.Grey)
        .placeholderFont({ size: 14, weight: 400 })
Z
zengyawen 已提交
208
        .caretColor(Color.Blue)
E
ester.zhou 已提交
209 210 211 212 213
        .width(400)
        .height(40)
        .margin(20)
        .fontSize(14)
        .fontColor(Color.Black)
E
ester.zhou 已提交
214 215 216
        .inputFilter('[a-z]', (e) => {
          console.log(JSON.stringify(e))
        })
Z
zengyawen 已提交
217 218 219
        .onChange((value: string) => {
          this.text = value
        })
E
ester.zhou 已提交
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
      Text(this.text)
      Button('Set caretPosition 1')
        .margin(15)
        .onClick(() => {
          // Move the caret to after the first entered character.
          this.controller.caretPosition(1)
        })
      // Password text box.
      TextInput({ placeholder: 'input your password...' })
        .width(400)
        .height(40)
        .margin(20)
        .type(InputType.Password)
        .maxLength(9)
        .showPasswordIcon(true)
      // Inline-style text box.
      TextInput({ placeholder: 'inline style' })
        .width(400)
        .height(50)
        .margin(20)
        .borderRadius(0)
        .style(TextInputStyle.Inline)
    }.width('100%')
Z
zengyawen 已提交
243 244 245 246
  }
}
```

E
ester.zhou 已提交
247
![TextInput](figures/TextInput.png)
E
ester.zhou 已提交
248 249 250 251 252 253 254

### Example 2

```ts
@Entry
@Component
struct TextInputExample {
E
ester.zhou 已提交
255 256 257 258 259 260
  @State PassWordSrc1: Resource = $r('app.media.onIcon')
  @State PassWordSrc2: Resource = $r('app.media.offIcon')
  @State TextError: string = undefined
  @State Text: string = ''
  @State NameText: string = 'test'

E
ester.zhou 已提交
261 262 263
  @Builder itemEnd() {
    Select([{ value: 'KB' },
      { value: 'MB' },
E
ester.zhou 已提交
264 265
      { value: 'GB' },
      { value: 'TB', }])
E
ester.zhou 已提交
266 267 268 269 270 271 272 273 274 275
      .height("48vp")
      .borderRadius(0)
      .selected(2)
      .align(Alignment.Center)
      .value('MB')
      .font({ size: 20, weight: 500 })
      .fontColor('#182431')
      .selectedOptionFont({ size: 20, weight: 400 })
      .optionFont({ size: 20, weight: 400 })
      .backgroundColor(Color.Transparent)
E
ester.zhou 已提交
276
      .responseRegion({ height: "40vp", width: "80%", x: '10%', y: '6vp' })
E
ester.zhou 已提交
277 278 279 280 281 282
      .onSelect((index: number) => {
        console.info('Select:' + index)
      })
  }

  build() {
E
ester.zhou 已提交
283
    Column({ space: 20 }) {
E
ester.zhou 已提交
284
      // Customize the password icon.
E
ester.zhou 已提交
285
      TextInput({ placeholder: 'Custom password icon' })
E
ester.zhou 已提交
286
        .type(InputType.Password)
E
ester.zhou 已提交
287
        .width(380)
E
ester.zhou 已提交
288
        .height(60)
E
ester.zhou 已提交
289
        .passwordIcon({ onIconSrc: this.PassWordSrc1, offIconSrc: this.PassWordSrc2 })
E
ester.zhou 已提交
290
      // Show an underline.
E
ester.zhou 已提交
291
      TextInput({ placeholder: 'Underline style' })
E
ester.zhou 已提交
292
        .showUnderline(true)
E
ester.zhou 已提交
293
        .width(380)
E
ester.zhou 已提交
294 295 296
        .height(60)
        .showError('Error')
        .showUnit(this.itemEnd.bind(this))
E
ester.zhou 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315

      Text (`User name: ${this.Text}`)
        .width('95%')
      TextInput({ placeholder: 'Enter user name', text: this.Text })
        .showUnderline(true)
        .width(380)
        .showError(this.TextError)
        .onChange((value: string) => {
          this.Text = value
        })
        .onSubmit(() => {// If the entered user name is incorrect, the text box will be cleared and the error message will be displayed.
          if (this.Text == this.NameText) {
            this.TextError = undefined
          } else {
            this.TextError ='Incorrect user name.'
            this.Text = ''
          }
        })

E
ester.zhou 已提交
316 317 318 319 320
    }.width('100%')
  }
}
```

E
ester.zhou 已提交
321
![TextInputError](figures/TextInputError.png)
E
ester.zhou 已提交
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363

### Example 3

```ts
// xxx.ets
@Entry
@Component
struct TextInputExample {
  controller: TextInputController = new TextInputController()
  @State inputValue: string = ""

  // Create a custom keyboard component.
  @Builder CustomKeyboardBuilder() {
    Column() {
      Button('x').onClick(() => {
        // Disable the custom keyboard.
        this.controller.stopEditing()
      })
      Grid() {
        ForEach([1, 2, 3, 4, 5, 6, 7, 8, 9, '*', 0, '#'], (item) => {
          GridItem() {
            Button(item + "")
              .width(110).onClick(() => {
              this.inputValue += item
            })
          }
        })
      }.maxCount(3).columnsGap(10).rowsGap(10).padding(5)
    }.backgroundColor(Color.Gray)
  }

  build() {
    Column() {
      TextInput({ controller: this.controller, text: this.inputValue })
        // Bind the custom keyboard.
        .customKeyboard(this.CustomKeyboardBuilder()).margin(10).border({ width: 1 })
    }
  }
}
```

![customKeyboard](figures/textInputCustomKeyboard.png)