ts-basic-components-textinput.md 15.7 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 43 44
| 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**|
| style<sup>9+</sup> | [TextInputStyle](#textinputstyle9) \| [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Text input style.<br>Default value: **TextInputStyle.Default**|
| 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 49 50 51 52
| showUnit<sup>10+</sup>                |  [CustomBuilder](ts-types.md#CustomBuilder8)         | Unit for content in the component.<br>By default, there is no unit.|
| showError<sup>10+</sup> | string \| undefined | Error text displayed when an error occurs.<br>By default, no error text is displayed.|
| 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

>  **NOTE**
>
E
ester.zhou 已提交
57
>  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 已提交
58 59 60 61 62 63 64 65 66 67 68

## 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 已提交
69
## InputType
E
ester.zhou 已提交
70 71 72 73

| Name                | Description           |
| ------------------ | ------------- |
| Normal   | Normal input mode.<br>The value can contain digits, letters, underscores (_), spaces, and special characters.|
E
ester.zhou 已提交
74 75
| 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.|
| Email    | Email address input mode. The value can contain digits, letters, underscores (_), and at signs (@). Only one at sign (@) is allowed.|
E
ester.zhou 已提交
76 77 78
| 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 已提交
79
## TextInputStyle<sup>9+</sup>
E
ester.zhou 已提交
80 81 82

| Name                | Description           |
| ------------------ | ------------- |
E
ester.zhou 已提交
83 84
| 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.  |
| Inline    | Inline input style. The background height of the selected text is the same as the height of the text box.     |
E
ester.zhou 已提交
85

E
ester.zhou 已提交
86 87 88 89 90 91 92
## 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 已提交
93
## Events
E
ester.zhou 已提交
94

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

E
ester.zhou 已提交
97
| Name                                                        | Description                                                    |
98
| ------------------------------------------------------------ | ------------------------------------------------------------ |
E
ester.zhou 已提交
99
| 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 已提交
100 101 102 103 104 105
| 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 已提交
106 107
| 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 已提交
108 109

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

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

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

caretPosition(value: number): void

E
ester.zhou 已提交
121
Sets the position of the caret.
Z
zengyawen 已提交
122

E
ester.zhou 已提交
123
**Parameters**
Z
zengyawen 已提交
124

E
ester.zhou 已提交
125 126 127
| 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 已提交
128 129 130 131 132 133 134
### setTextSelection<sup>10+</sup>

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

Sets the text selection area, which will be highlighted.

**Parameters**
Z
zengyawen 已提交
135

E
ester.zhou 已提交
136 137
| Name        | Type| Mandatory| Description              |
| -------------- | -------- | ---- | ---------------------- |
E
ester.zhou 已提交
138 139
| 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 已提交
140

E
ester.zhou 已提交
141 142 143 144 145 146
### stopEditing<sup>10+</sup>

stopEditing(): void

Exits the editing state.

E
ester.zhou 已提交
147 148 149 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
### 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 已提交
188 189
## Example

E
ester.zhou 已提交
190 191
### Example 1

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

  build() {
    Column() {
E
ester.zhou 已提交
202
      TextInput({ text: this.text, placeholder: 'input your word...', controller: this.controller })
E
ester.zhou 已提交
203 204
        .placeholderColor(Color.Grey)
        .placeholderFont({ size: 14, weight: 400 })
Z
zengyawen 已提交
205
        .caretColor(Color.Blue)
E
ester.zhou 已提交
206 207 208 209 210
        .width(400)
        .height(40)
        .margin(20)
        .fontSize(14)
        .fontColor(Color.Black)
E
ester.zhou 已提交
211 212 213
        .inputFilter('[a-z]', (e) => {
          console.log(JSON.stringify(e))
        })
Z
zengyawen 已提交
214 215 216
        .onChange((value: string) => {
          this.text = value
        })
E
ester.zhou 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
      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 已提交
240 241 242 243
  }
}
```

E
ester.zhou 已提交
244
![textInput](figures/textInput.gif)
E
ester.zhou 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296

### Example 2

```ts
// xxx.ets
@Entry
@Component
struct TextInputExample {
  @State PassWordSrc1:Resource=$r('app.media.icon')
  @State PassWordSrc2:Resource=$r('app.media.icon')
  @Builder itemEnd() {
    Select([{ value: 'KB' },
      { value: 'MB' },
      { value: 'GB'},
      { value: 'TB',}])
      .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)
      .responseRegion({height:"40vp",width:"80%",x:'10%',y:'6vp'})
      .onSelect((index: number) => {
        console.info('Select:' + index)
      })
  }

  build() {
    Column() {
      // Customize the password icon.
      TextInput({ placeholder: 'user define password icon' })
        .type(InputType.Password)
        .width(400)
        .height(60)
        .passwordIcon({onIconSrc:this.PassWordSrc1,offIconSrc : this.PassWordSrc2})
      // Show an underline.
      TextInput({ placeholder: 'underline style' })
        .showUnderline(true)
        .width(400)
        .height(60)
        .showError('Error')
        .showUnit(this.itemEnd.bind(this))
    }.width('100%')
  }
}
```

![showUnit](figures/showUnit.png)