提交 96820d0f 编写于 作者: E ester.zhou

update docs

Signed-off-by: Nester.zhou <ester.zhou@huawei.com>
上级 5278e32a
# Input Method Framework # Input Method Framework
> **NOTE** The **inputMethod** module provides an input method framework, which can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more.
> **NOTE**
> >
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -8,14 +10,14 @@ ...@@ -8,14 +10,14 @@
## Modules to Import ## Modules to Import
``` ```
import inputMethod from '@ohos.inputMethod'; import inputMethod from '@ohos.inputmethod';
``` ```
## inputMethod<sup>8+</sup> ## inputMethod<sup>8+</sup>
Provides the constants. Provides the constants.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
...@@ -26,7 +28,7 @@ Provides the constants. ...@@ -26,7 +28,7 @@ Provides the constants.
Describes the input method application attributes. Describes the input method application attributes.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
...@@ -37,15 +39,15 @@ Describes the input method application attributes. ...@@ -37,15 +39,15 @@ Describes the input method application attributes.
getInputMethodController(): InputMethodController getInputMethodController(): InputMethodController
Obtains an [InputMethodController](#InputMethodController) instance. Obtains an **[InputMethodController](#inputmethodcontroller)** instance.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value** **Return value**
| Type| Description| | Type | Description |
| -------- | -------- | | ----------------------------------------- | ---------------------------- |
| [InputMethodController](#InputMethodController) | Returns the current **InputMethodController** instance.| | [InputMethodController](#inputmethodcontroller) | Returns the current **InputMethodController** instance.|
**Example** **Example**
...@@ -57,25 +59,74 @@ Obtains an [InputMethodController](#InputMethodController) instance. ...@@ -57,25 +59,74 @@ Obtains an [InputMethodController](#InputMethodController) instance.
getInputMethodSetting(): InputMethodSetting getInputMethodSetting(): InputMethodSetting
Obtains an [InputMethodSetting](#InputMethodSetting) instance. Obtains an **[InputMethodSetting](#inputmethodsetting8)** instance.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------------------- | ---------------------------- | | ----------------------------------------- | ---------------------------- |
| [InputMethodSetting](#InputMethodSetting) | Returns the current **InputMethodSetting** instance.| | [InputMethodSetting](#inputmethodsetting8) | Returns the current **InputMethodSetting** instance.|
**Example** **Example**
```js ```js
var InputMethodSetting = inputMethod.getInputMethodSetting(); var InputMethodSetting = inputMethod.getInputMethodSetting();
``` ```
## inputMethod.switchInputMethod<sup>9+</sup>
switchInputMethod(target: InputmethodProperty, callback: AsyncCallback&lt;boolean&gt;): void;
Switches to another input method. This API uses an asynchronous callback to return the result. This API can be used only in the stage model.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
|target | [InputmethodProperty](#inputmethodproperty8) | Yes| Input method to switch to.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the execution result. |
**Example**
```js
inputMethod.switchInputMethod({packageName:"com.ohos.inputApp", methodId:"InputDemoService"}).then(res => {
prompt.showToast({message:"Input method switched." + this.imeList[this.flag].packageName, duration: 200});
});
```
## inputMethod.switchInputMethod<sup>9+</sup>
switchInputMethod(target: InputmethodProperty): Promise&lt;boolean&gt;
Switches to another input method. This API uses a promise to return the result. This API can be used only in the stage model.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
|target | [InputmethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.|
**Return value**
| Type | Description |
| ----------------------------------------- | ---------------------------- |
| Promise\<boolean> | Promise used to return the execution result. |
**Example**
```js
inputMethod.switchInputMethod({packageName:"com.ohos.inputApp", methodId:"InputDemoService"}).then(res => {
prompt.showToast({message:"Input method switched." + this.imeList[this.flag].packageName, duration: 200});
});
```
## InputMethodController ## InputMethodController
In the following API examples, you must first use [getInputMethodController](#getInputMethodController) to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance. In the following API examples, you must first use **[getInputMethodController](#inputmethodgetinputmethodcontroller)** to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance.
### stopInput ### stopInput
...@@ -83,7 +134,7 @@ stopInput(callback: AsyncCallback&lt;boolean&gt;): void ...@@ -83,7 +134,7 @@ stopInput(callback: AsyncCallback&lt;boolean&gt;): void
Hides the keyboard. This API uses an asynchronous callback to return the result. Hides the keyboard. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
...@@ -105,13 +156,13 @@ stopInput(): Promise&lt;boolean&gt; ...@@ -105,13 +156,13 @@ stopInput(): Promise&lt;boolean&gt;
Hides the keyboard. This API uses an asynchronous callback to return the result. Hides the keyboard. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return whether the keyboard is successfully hidden.| | Promise&lt;boolean&gt; | Promise used to return whether the keyboard is successfully hidden. |
**Example** **Example**
...@@ -123,7 +174,7 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. ...@@ -123,7 +174,7 @@ Hides the keyboard. This API uses an asynchronous callback to return the result.
## InputMethodSetting<sup>8+</sup> ## InputMethodSetting<sup>8+</sup>
In the following API examples, you must first use [getInputMethodSetting](#getInputMethodSetting) to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. In the following API examples, you must first use **[getInputMethodSetting](#inputmethodgetinputmethodsetting8)** to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance.
### listInputMethod ### listInputMethod
...@@ -131,13 +182,12 @@ listInputMethod(callback: AsyncCallback&lt;Array&lt;InputMethodProperty&gt;&gt;) ...@@ -131,13 +182,12 @@ listInputMethod(callback: AsyncCallback&lt;Array&lt;InputMethodProperty&gt;&gt;)
Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. Obtains the list of installed input methods. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------------------------- | ---- | ---------------------- | | -------- | -------------------------------------------------- | ---- | ---------------------- |
| callback | Array<[InputMethodProperty](#InputMethodProperty)> | Yes | Callback used to return the list of installed input methods.| | callback | Array<[InputMethodProperty](#inputmethodproperty8)> | Yes | Callback used to return the list of installed input methods.|
**Example** **Example**
...@@ -156,13 +206,12 @@ listInputMethod(): Array&lt;InputMethodProperty&gt; ...@@ -156,13 +206,12 @@ listInputMethod(): Array&lt;InputMethodProperty&gt;
Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. Obtains the list of installed input methods. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------------------------------------- | ---------------------- | | ----------------------------------------------------------- | ---------------------- |
| Promise<Array<[InputMethodProperty](#InputMethodProperty)>> | Promise used to return the list of installed input methods.| | Promise<Array<[InputMethodProperty](#inputmethodproperty8)>> | Promise used to return the list of installed input methods. |
**Example** **Example**
...@@ -180,15 +229,16 @@ displayOptionalInputMethod(callback: AsyncCallback&lt;void&gt;): void ...@@ -180,15 +229,16 @@ displayOptionalInputMethod(callback: AsyncCallback&lt;void&gt;): void
Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
- Parameters **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the execution result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the execution result.|
**Example** **Example**
```js ```js
InputMethodSetting.displayOptionalInputMethod(()=>{ InputMethodSetting.displayOptionalInputMethod(()=>{
console.info('displayOptionalInputMethod is called'); console.info('displayOptionalInputMethod is called');
...@@ -197,20 +247,20 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono ...@@ -197,20 +247,20 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono
### displayOptionalInputMethod ### displayOptionalInputMethod
displayOptionalInputMethod(): Promise&lt;void&gt; displayOptionalInputMethod(): Promise&lt;void&gt;
Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the execution result.| | Promise&lt;void&gt; | Promise used to return the execution result. |
**Example** **Example**
```js ```js
InputMethodSetting.displayOptionalInputMethod(); InputMethodSetting.displayOptionalInputMethod();
``` ```
\ No newline at end of file
# Input Method Engine # Input Method Engine
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. The **inputMethodEngine** module streamlines the interaction between applications and input methods. By calling APIs of this module, applications can accept text input through the input methods, be bound to input method services, request the keyboard to display or hide, listen for the input method status, and much more.
> **NOTE**
> >
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
``` ```
import inputMethodEngine from '@ohos.inputMethodEngine'; import inputMethodEngine from '@ohos.inputmethodengine';
``` ```
## inputMethodEngine ## inputMethodEngine
Defines constant values. Provides the constants.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
| Name| Type| Readable| Writable| Description| | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
...@@ -50,7 +53,7 @@ getInputMethodEngine(): InputMethodEngine ...@@ -50,7 +53,7 @@ getInputMethodEngine(): InputMethodEngine
Obtains an **InputMethodEngine** instance. Obtains an **InputMethodEngine** instance.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value** **Return value**
...@@ -60,9 +63,9 @@ Obtains an **InputMethodEngine** instance. ...@@ -60,9 +63,9 @@ Obtains an **InputMethodEngine** instance.
**Example** **Example**
```js ```js
var InputMethodEngine = inputMethodEngine.getInputMethodEngine(); var InputMethodEngine = inputMethodEngine.getInputMethodEngine();
``` ```
## inputMethodEngine.createKeyboardDelegate<a name="createKeyboardDelegate"></a> ## inputMethodEngine.createKeyboardDelegate<a name="createKeyboardDelegate"></a>
...@@ -70,7 +73,7 @@ createKeyboardDelegate(): KeyboardDelegate ...@@ -70,7 +73,7 @@ createKeyboardDelegate(): KeyboardDelegate
Obtains a **KeyboardDelegate** instance. Obtains a **KeyboardDelegate** instance.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value** **Return value**
...@@ -80,9 +83,9 @@ Obtains a **KeyboardDelegate** instance. ...@@ -80,9 +83,9 @@ Obtains a **KeyboardDelegate** instance.
**Example** **Example**
```js ```js
var KeyboardDelegate = inputMethodEngine.createKeyboardDelegate(); var KeyboardDelegate = inputMethodEngine.createKeyboardDelegate();
``` ```
## InputMethodEngine<a name="InputMethodEngine"></a> ## InputMethodEngine<a name="InputMethodEngine"></a>
...@@ -94,7 +97,7 @@ on(type: 'inputStart', callback: (kbController: KeyboardController, textInputCli ...@@ -94,7 +97,7 @@ on(type: 'inputStart', callback: (kbController: KeyboardController, textInputCli
Listens for the input method binding event. This API uses a callback to return the result. Listens for the input method binding event. This API uses a callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
...@@ -105,12 +108,12 @@ Listens for the input method binding event. This API uses a callback to return t ...@@ -105,12 +108,12 @@ Listens for the input method binding event. This API uses a callback to return t
**Example** **Example**
```js ```js
InputMethodEngine.on('inputStart', (kbController, textInputClient) => { InputMethodEngine.on('inputStart', (kbController, textInputClient) => {
KeyboardController = kbController; KeyboardController = kbController;
TextInputClient = textInputClient; TextInputClient = textInputClient;
}); });
``` ```
### off('inputStart') ### off('inputStart')
...@@ -118,7 +121,7 @@ off(type: 'inputStart', callback?: (kbController: KeyboardController, textInputC ...@@ -118,7 +121,7 @@ off(type: 'inputStart', callback?: (kbController: KeyboardController, textInputC
Cancels listening for the input method binding event. Cancels listening for the input method binding event.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
...@@ -127,11 +130,13 @@ Cancels listening for the input method binding event. ...@@ -127,11 +130,13 @@ Cancels listening for the input method binding event.
| type | string | Yes | Listening type.<br>Set it to **'inputStart'**, which indicates listening for the input method binding event.| | type | string | Yes | Listening type.<br>Set it to **'inputStart'**, which indicates listening for the input method binding event.|
| callback | [KeyboardController](#KeyboardController), [TextInputClient](#TextInputClient) | No| Callback used to return the result.| | callback | [KeyboardController](#KeyboardController), [TextInputClient](#TextInputClient) | No| Callback used to return the result.|
**Example** **Example**
```js ```js
InputMethodEngine.off('inputStart'); InputMethodEngine.off('inputStart');
``` ```
### on('keyboardShow'|'keyboardHide') ### on('keyboardShow'|'keyboardHide')
...@@ -139,22 +144,22 @@ on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void ...@@ -139,22 +144,22 @@ on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void
Listens for an input method event. Listens for an input method event.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ | | -------- | ------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>- The value **'keyboardShow'** means to listen for displaying of the input method.<br>- The value **'keyboardHide'** means to listen for hiding of the input method.| | type | string | Yes | Listening type.<br>-&nbsp;The value **'keyboardShow'** means to listen for displaying of the input method.<br>-&nbsp;The value **'keyboardHide'** means to listen for hiding of the input method.|
| callback | void | No | Callback used to return the result. | | callback | void | No | Callback used to return the result. |
**Example** **Example**
```js ```js
InputMethodEngine.on('keyboardShow', (err) => { InputMethodEngine.on('keyboardShow', (err) => {
console.info('keyboardShow'); console.info('keyboardShow');
}); });
``` ```
### off('keyboardShow'|'keyboardHide') ### off('keyboardShow'|'keyboardHide')
...@@ -162,20 +167,21 @@ off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void ...@@ -162,20 +167,21 @@ off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void
Cancels listening for an input method event. Cancels listening for an input method event.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ | | -------- | ------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>- The value **'keyboardShow'** means to listen for displaying of the input method.<br>- The value **'keyboardHide'** means to listen for hiding of the input method.| | type | string | Yes | Listening type.<br>-&nbsp;The value **'keyboardShow'** means to listen for displaying of the input method.<br>-&nbsp;The value **'keyboardHide'** means to listen for hiding of the input method.|
| callback | void | No | Callback used to return the result. | | callback | void | No | Callback used to return the result. |
**Example** **Example**
```js ```js
InputMethodEngine.off('keyboardShow'); InputMethodEngine.off('keyboardShow');
``` ```
## KeyboardDelegate<a name="KeyboardDelegate"></a> ## KeyboardDelegate<a name="KeyboardDelegate"></a>
...@@ -187,22 +193,24 @@ on(type: 'keyDown'|'keyUp', callback: (event: KeyEvent) => boolean): void ...@@ -187,22 +193,24 @@ on(type: 'keyDown'|'keyUp', callback: (event: KeyEvent) => boolean): void
Listens for a hard keyboard even. This API uses a callback to return the key information. Listens for a hard keyboard even. This API uses a callback to return the key information.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>- The value **'keyDown'** means to listen for pressing of a key.<br>- The value **'keyUp'** means to listen for releasing of a key.| | type | string | Yes | Listening type.<br>-&nbsp;The value **'keyDown'** means to listen for pressing of a key.<br>-&nbsp;The value **'keyUp'** means to listen for releasing of a key.|
| callback | [KeyEvent](#KeyEvent) | Yes| Callback used to return the key information.| | callback | [KeyEvent](#KeyEvent) | Yes| Callback used to return the key information.|
**Example** **Example**
```js ```js
KeyboardDelegate.on('keyDown', (event) => { KeyboardDelegate.on('keyDown', (event) => {
console.info('keyDown'); console.info('keyDown');
}); });
``` ```
### off('keyDown'|'keyUp') ### off('keyDown'|'keyUp')
...@@ -210,20 +218,20 @@ off(type: 'keyDown'|'keyUp', callback?: (event: KeyEvent) => boolean): void ...@@ -210,20 +218,20 @@ off(type: 'keyDown'|'keyUp', callback?: (event: KeyEvent) => boolean): void
Cancels listening for a hard keyboard even. Cancels listening for a hard keyboard even.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------------------------------------------------ | | -------- | --------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>- The value **'keyDown'** means to listen for pressing of a key.<br>- The value **'keyUp'** means to listen for releasing of a key.| | type | string | Yes | Listening type.<br>-&nbsp;The value **'keyDown'** means to listen for pressing of a key.<br>-&nbsp;The value **'keyUp'** means to listen for releasing of a key.|
| callback | [KeyEvent](#KeyEvent) | No | Callback used to return the key information. | | callback | [KeyEvent](#KeyEvent) | No | Callback used to return the key information. |
**Example** **Example**
```js ```js
KeyboardDelegate.off('keyDown'); KeyboardDelegate.off('keyDown');
``` ```
### on('cursorContextChange') ### on('cursorContextChange')
...@@ -231,21 +239,25 @@ on(type: 'cursorContextChange', callback: (x: number, y:number, height:number) = ...@@ -231,21 +239,25 @@ on(type: 'cursorContextChange', callback: (x: number, y:number, height:number) =
Listens for cursor context changes. This API uses a callback to return the cursor information. Listens for cursor context changes. This API uses a callback to return the cursor information.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ | | -------- | ------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>Set it to **'cursorContextChange'**, which indicates listening for cursor context changes.| | type | string | Yes | Listening type.<br>Set it to **'cursorContextChange'**, which indicates listening for cursor context changes.|
| callback | number | Yes | Callback used to return the cursor information. | | callback | number | Yes | Callback used to return the cursor information. |
**Example**
**Example**
```js ```js
KeyboardDelegate.on('cursorContextChange', (x, y, height) => { KeyboardDelegate.on('cursorContextChange', (x, y, height) => {
console.info('cursorContextChange'); console.info('cursorContextChange');
}); });
``` ```
### off('cursorContextChange') ### off('cursorContextChange')
...@@ -254,42 +266,46 @@ off(type: 'cursorContextChange', callback?: (x: number, y:number, height:number) ...@@ -254,42 +266,46 @@ off(type: 'cursorContextChange', callback?: (x: number, y:number, height:number)
Cancels listening for cursor context changes. Cancels listening for cursor context changes.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------ | | -------- | ------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>Set it to **'cursorContextChange'**, which indicates listening for cursor context changes.| | type | string | Yes | Listening type.<br>Set it to **'cursorContextChange'**, which indicates listening for cursor context changes.|
| callback | number | No| Callback used to return the cursor information.| | callback | number | No | Callback used to return the cursor information. |
**Example**
**Example**
```js ```js
KeyboardDelegate.off('cursorContextChange'); KeyboardDelegate.off('cursorContextChange');
```
```
### on('selectionChange') ### on('selectionChange')
on(type: 'selectionChange', callback: (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void): void on(type: 'selectionChange', callback: (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void): void
Listens for text selection changes. This API uses a callback to return the text selection information. Listens for text selection changes. This API uses a callback to return the text selection information.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ | | -------- | ------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>Set it to **'selectionChange'**, which indicates listening for text selection changes.| | type | string | Yes | Listening type.<br>Set it to **'selectionChange'**, which indicates listening for text selection changes.|
| callback | number | Yes | Callback used to return the text selection information. | | callback | number | Yes | Callback used to return the text selection information. |
**Example** **Example**
```js ```js
KeyboardDelegate.on('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { KeyboardDelegate.on('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => {
console.info('selectionChange'); console.info('selectionChange');
}); });
``` ```
### off('selectionChange') ### off('selectionChange')
...@@ -298,19 +314,21 @@ off(type: 'selectionChange', callback?: (oldBegin: number, oldEnd: number, newBe ...@@ -298,19 +314,21 @@ off(type: 'selectionChange', callback?: (oldBegin: number, oldEnd: number, newBe
Cancels listening for text selection changes. Cancels listening for text selection changes.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------ | | -------- | ------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>Set it to **'selectionChange'**, which indicates listening for text selection changes.| | type | string | Yes | Listening type.<br>Set it to **'selectionChange'**, which indicates listening for text selection changes.|
| callback | number | No| Callback used to return the text selection information.| | callback | number | No | Callback used to return the text selection information. |
**Example** **Example**
```js ```js
KeyboardDelegate.off('selectionChange'); KeyboardDelegate.off('selectionChange');
``` ```
...@@ -320,21 +338,23 @@ on(type: 'textChange', callback: (text: string) => void): void ...@@ -320,21 +338,23 @@ on(type: 'textChange', callback: (text: string) => void): void
Listens for text changes. This API uses a callback to return the current text content. Listens for text changes. This API uses a callback to return the current text content.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>Set it to **'textChange'**, which indicates listening for text changes.| | type | string | Yes | Listening type.<br>Set it to **'textChange'**, which indicates listening for text changes.|
| callback | string | Yes| Callback used to return the current text content.| | callback | string | Yes | Callback used to return the current text content. |
**Example** **Example**
```js ```js
KeyboardDelegate.on('textChange', (text) => { KeyboardDelegate.on('textChange', (text) => {
console.info('textChange'); console.info('textChange');
}); });
``` ```
### off('textChange') ### off('textChange')
...@@ -343,16 +363,16 @@ off(type: 'textChange', callback?: (text: string) => void): void ...@@ -343,16 +363,16 @@ off(type: 'textChange', callback?: (text: string) => void): void
Cancels listening for text changes. Cancels listening for text changes.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ------------------------ | | -------- | ------ | ---- | ------------------------------------------------------------ |
| type | string | Yes | Listening type.<br>Set it to **'textChange'**, which indicates listening for text changes.| | type | string | Yes | Listening type.<br>Set it to **'textChange'**, which indicates listening for text changes.|
| callback | string | No| Callback used to return the current text content.| | callback | string | No | Callback used to return the current text content. |
**Example** **Example**
```js ```js
KeyboardDelegate.off('textChange'); KeyboardDelegate.off('textChange');
...@@ -368,7 +388,7 @@ hideKeyboard(callback: AsyncCallback&lt;void&gt;): void ...@@ -368,7 +388,7 @@ hideKeyboard(callback: AsyncCallback&lt;void&gt;): void
Hides the keyboard. This API uses an asynchronous callback to return the result. Hides the keyboard. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
...@@ -388,19 +408,18 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. ...@@ -388,19 +408,18 @@ Hides the keyboard. This API uses an asynchronous callback to return the result.
hideKeyboard(): Promise&lt;void&gt; hideKeyboard(): Promise&lt;void&gt;
Hides the keyboard. This API uses a promise to return the result. Hides the keyboard. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value** **Return value**
| Type | Description: | | Type | Description |
| ---------------- | -------- | | ---------------- | -------- |
| Promise&lt;void> | Promise used to return the result.| | Promise&lt;void> | Promise used to return the result.|
**Example** **Example**
```js ```js
KeyboardController.hideKeyboard(); KeyboardController.hideKeyboard();
``` ```
...@@ -415,30 +434,30 @@ getForward(length:number, callback: AsyncCallback&lt;string&gt;): void ...@@ -415,30 +434,30 @@ getForward(length:number, callback: AsyncCallback&lt;string&gt;): void
Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result. Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| length | number | Yes| Text length.| | length | number | Yes| Text length.|
| callback | AsyncCallback&lt;string&gt; | Yes| Text returned.| | callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the text.|
**Example** **Example**
```js ```js
TextInputClient.getForward(5,(text) =>{ TextInputClient.getForward(5,(text) =>{
console.info("text = " + text); console.info("text = " + text);
}); });
``` ```
### getForward ### getForward
getForward(length:number): Promise&lt;string&gt; getForward(length:number): Promise&lt;string&gt;
Obtains the specific-length text before the cursor. This API uses a promise to return the result. Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
...@@ -450,14 +469,14 @@ Obtains the specific-length text before the cursor. This API uses a promise to r ...@@ -450,14 +469,14 @@ Obtains the specific-length text before the cursor. This API uses a promise to r
| Type | Description | | Type | Description |
| ------------------------------- | ------------------------------------------------------------ | | ------------------------------- | ------------------------------------------------------------ |
| Promise&lt;string&gt; | Text returned. | | Promise&lt;string&gt; | Promise used to return the text. |
**Example** **Example**
```js ```js
var text = TextInputClient.getForward(5); var text = TextInputClient.getForward(5);
console.info("text = " + text); console.info("text = " + text);
``` ```
### getBackward ### getBackward
...@@ -465,30 +484,30 @@ getBackward(length:number, callback: AsyncCallback&lt;string&gt;): void ...@@ -465,30 +484,30 @@ getBackward(length:number, callback: AsyncCallback&lt;string&gt;): void
Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result. Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| length | number | Yes| Text length.| | length | number | Yes| Text length.|
| callback | AsyncCallback&lt;string&gt; | Yes| Text returned.| | callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the text.|
**Example** **Example**
```js ```js
TextInputClient.getBackward(5,(text)=>{ TextInputClient.getBackward(5,(text)=>{
console.info("text = " + text); console.info("text = " + text);
}); });
``` ```
### getBackward ### getBackward
getBackward(length:number): Promise&lt;string&gt; getBackward(length:number): Promise&lt;string&gt;
Obtains the specific-length text after the cursor. This API uses a promise to return the result. Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
...@@ -500,14 +519,14 @@ Obtains the specific-length text after the cursor. This API uses a promise to re ...@@ -500,14 +519,14 @@ Obtains the specific-length text after the cursor. This API uses a promise to re
| Type | Description | | Type | Description |
| ------------------------------- | ------------------------------------------------------------ | | ------------------------------- | ------------------------------------------------------------ |
| Promise&lt;string&gt; | Text returned. | | Promise&lt;string&gt; | Promise used to return the text. |
**Example** **Example**
```js ```js
var text = TextInputClient.getBackward(5); var text = TextInputClient.getBackward(5);
console.info("text = " + text); console.info("text = " + text);
``` ```
### deleteForward ### deleteForward
...@@ -515,47 +534,46 @@ deleteForward(length:number, callback: AsyncCallback&lt;boolean&gt;): void ...@@ -515,47 +534,46 @@ deleteForward(length:number, callback: AsyncCallback&lt;boolean&gt;): void
Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result. Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| length | number | Yes| Text length.| | length | number | Yes| Text length.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Returns whether the operation is successful.| | callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
**Example** **Example**
```js ```js
TextInputClient.deleteForward(5,(isSuccess)=>{ TextInputClient.deleteForward(5,(isSuccess)=>{
console.info("isSuccess = " + isSuccess); console.info("isSuccess = " + isSuccess);
}); });
``` ```
### deleteForward ### deleteForward
deleteForward(length:number): Promise&lt;boolean&gt; deleteForward(length:number): Promise&lt;boolean&gt;
Deletes the fixed-length text before the cursor. This API uses a promise to return the result. Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type | Mandatory| Description |
| -------- | -------- | -------- | -------- | | ------ | ------ | ---- | ---------- |
| length | number | Yes| Text length.| | length | number | Yes | Text length.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------- | ------------------------------------------------------------ | | ---------------------- | -------------- |
| Promise&lt;boolean&gt; | Returns whether the operation is successful. | | Promise&lt;boolean&gt; | Promise used to return the result.|
**Example** **Example**
```js ```js
var isSuccess = TextInputClient.deleteForward(5); var isSuccess = TextInputClient.deleteForward(5);
console.info("isSuccess = " + isSuccess); console.info("isSuccess = " + isSuccess);
``` ```
...@@ -565,33 +583,34 @@ deleteBackward(length:number, callback: AsyncCallback&lt;boolean&gt;): void ...@@ -565,33 +583,34 @@ deleteBackward(length:number, callback: AsyncCallback&lt;boolean&gt;): void
Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name | Type | Mandatory| Description |
| -------- | -------- | -------- | -------- | | -------- | ---------------------------- | ---- | -------------- |
| length | number | Yes| Text length.| | length | number | Yes | Text length. |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Returns whether the operation is successful.| | callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result.|
**Example** **Example**
```js ```js
TextInputClient.deleteBackward(5, (isSuccess)=>{ TextInputClient.deleteBackward(5, (isSuccess)=>{
console.info("isSuccess = " + isSuccess); console.info("isSuccess = " + isSuccess);
}); });
``` ```
### deleteBackward ### deleteBackward
deleteBackward(length:number): Promise&lt;boolean&gt; deleteBackward(length:number): Promise&lt;boolean&gt;
Deletes the fixed-length text after the cursor. This API uses a promise to return the result. Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| length | number | Yes| Text length.| | length | number | Yes| Text length.|
...@@ -600,45 +619,48 @@ Deletes the fixed-length text after the cursor. This API uses a promise to retur ...@@ -600,45 +619,48 @@ Deletes the fixed-length text after the cursor. This API uses a promise to retur
| Type | Description | | Type | Description |
| ------------------------------- | ------------------------------------------------------------ | | ------------------------------- | ------------------------------------------------------------ |
| Promise&lt;boolean&gt; | Returns whether the operation is successful. | | Promise&lt;boolean&gt; | Promise used to return the result. |
**Example** **Example**
```js ```js
var isSuccess = TextInputClient.deleteBackward(5);
console.info("isSuccess = " + isSuccess);
```
var isSuccess = TextInputClient.deleteBackward(5);
console.info("isSuccess = " + isSuccess);
```
### sendKeyFunction ### sendKeyFunction
sendKeyFunction(action:number, callback: AsyncCallback&lt;boolean&gt;): void sendKeyFunction(action:number, callback: AsyncCallback&lt;boolean&gt;): void
Sets the Enter key to send the text to its target. This API uses an asynchronous callback to return the result. Sets the Enter key to send the text to its target. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| action | number | Yes| Edit box attribute.| | action | number | Yes| Edit box attribute.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Returns whether the operation is successful.| | callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
**Example** **Example**
```js ```js
TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT,(isSuccess)=>{ TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT,(isSuccess)=>{
console.info("isSuccess = " + isSuccess); console.info("isSuccess = " + isSuccess);
}); });
``` ```
### sendKeyFunction ### sendKeyFunction
sendKeyFunction(action:number): Promise&lt;boolean&gt; sendKeyFunction(action:number): Promise&lt;boolean&gt;
Sets the Enter key to send the text to its target. This API uses a promise to return the result. Sets the Enter key to send the text to its target. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
...@@ -650,14 +672,14 @@ Sets the Enter key to send the text to its target. This API uses a promise to re ...@@ -650,14 +672,14 @@ Sets the Enter key to send the text to its target. This API uses a promise to re
| Type | Description | | Type | Description |
| ------------------------------- | ------------------------------------------------------------ | | ------------------------------- | ------------------------------------------------------------ |
| Promise&lt;boolean&gt; | Returns whether the operation is successful. | | Promise&lt;boolean&gt; | Promise used to return the result. |
**Example** **Example**
```js ```js
var isSuccess = TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT); var isSuccess = TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT);
console.info("isSuccess = " + isSuccess); console.info("isSuccess = " + isSuccess);
``` ```
### insertText ### insertText
...@@ -665,30 +687,32 @@ insertText(text:string, callback: AsyncCallback&lt;boolean&gt;): void ...@@ -665,30 +687,32 @@ insertText(text:string, callback: AsyncCallback&lt;boolean&gt;): void
Inserts text. This API uses an asynchronous callback to return the result. Inserts text. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| text | string | Yes| Text to insert.| | text | string | Yes| Text to insert.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Returns whether the operation is successful.| | callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
**Example** **Example**
```js ```js
TextInputClient.insertText("test", (isSuccess)=>{ TextInputClient.insertText("test", (isSuccess)=>{
console.info("isSuccess = " + isSuccess); console.info("isSuccess = " + isSuccess);
}); });
``` ```
### insertText ### insertText
insertText(text:string): Promise&lt;boolean&gt; insertText(text:string): Promise&lt;boolean&gt;
Inserts text. This API uses a promise to return the result. Inserts text. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
...@@ -696,18 +720,18 @@ Inserts text. This API uses a promise to return the result. ...@@ -696,18 +720,18 @@ Inserts text. This API uses a promise to return the result.
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| text | string | Yes| Text to insert.| | text | string | Yes| Text to insert.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------- | ------------------------------------------------------------ | | ------------------------------- | ------------------------------------------------------------ |
| Promise&lt;boolean&gt; | Returns whether the operation is successful. | | Promise&lt;boolean&gt; | Promise used to return the result. |
**Example** **Example**
```js ```js
var isSuccess = TextInputClient.insertText("test"); var isSuccess = TextInputClient.insertText("test");
console.info("isSuccess = " + isSuccess); console.info("isSuccess = " + isSuccess);
``` ```
### getEditorAttribute ### getEditorAttribute
...@@ -715,7 +739,7 @@ getEditorAttribute(callback: AsyncCallback&lt;EditorAttribute&gt;): void ...@@ -715,7 +739,7 @@ getEditorAttribute(callback: AsyncCallback&lt;EditorAttribute&gt;): void
Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result. Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters** **Parameters**
...@@ -725,36 +749,36 @@ Obtains the attribute of the edit box. This API uses an asynchronous callback to ...@@ -725,36 +749,36 @@ Obtains the attribute of the edit box. This API uses an asynchronous callback to
**Example** **Example**
```js ```js
TextInputClient.getEditorAttribute((EditorAttribute)=>{ TextInputClient.getEditorAttribute((EditorAttribute)=>{
}); });
``` ```
### getEditorAttribute ### getEditorAttribute
getEditorAttribute(): EditorAttribute getEditorAttribute(): EditorAttribute
Obtains the attribute of the edit box. This API uses a promise to return the result. Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------- | ------------------------------------------------------------ | | ------------------------------- | ------------------------------------------------------------ |
| Promise&lt;[EditorAttribute](#EditorAttribute)&gt; | Returns the attribute of the edit box. | | Promise&lt;[EditorAttribute](#EditorAttribute)&gt; | Promise used to return the attribute of the edit box. |
**Example** **Example**
```js ```js
var EditorAttribute = TextInputClient.getEditorAttribute(); var EditorAttribute = TextInputClient.getEditorAttribute();
``` ```
## EditorAttribute<a name="EditorAttribute"></a> ## EditorAttribute<a name="EditorAttribute"></a>
Describes the attribute of the edit box. Describes the attribute of the edit box.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
| Name | Type| Readable| Writable| Description | | Name | Type| Readable| Writable| Description |
| ------------ | -------- | ---- | ---- | ------------------ | | ------------ | -------- | ---- | ---- | ------------------ |
...@@ -765,7 +789,7 @@ Describes the attribute of the edit box. ...@@ -765,7 +789,7 @@ Describes the attribute of the edit box.
Describes the attribute of a key. Describes the attribute of a key.
**System capability**: SystemCapability.Miscservices.InputMethodFramework **System capability**: SystemCapability.MiscServices.InputMethodFramework
| Name | Type| Readable| Writable| Description | | Name | Type| Readable| Writable| Description |
| --------- | -------- | ---- | ---- | ------------ | | --------- | -------- | ---- | ---- | ------------ |
......
...@@ -17,9 +17,9 @@ import request from '@ohos.request'; ...@@ -17,9 +17,9 @@ import request from '@ohos.request';
## Constraints ## Constraints
HTTPS is supported by default. To support HTTP, you need to add **network** to the **config.json** file and set the **cleartextTraffic** attribute to **true**. HTTPS is supported by default in the FA model. To support HTTP, add **network** to the **config.json** file and set the **cleartextTraffic** attribute to **true**.
``` ```js
var config = { var config = {
"deviceConfig": { "deviceConfig": {
"default": { "default": {
...@@ -32,6 +32,9 @@ var config = { ...@@ -32,6 +32,9 @@ var config = {
} }
``` ```
The **cleartextTraffic** attribute is not involved during the development of applications in the stage model.
## Constants ## Constants
...@@ -39,28 +42,28 @@ var config = { ...@@ -39,28 +42,28 @@ var config = {
**System capability**: SystemCapability.MiscServices.Download **System capability**: SystemCapability.MiscServices.Download
| Name | Type | Readable | Writable | Description | | Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| NETWORK_MOBILE | number | Yes | No | Whether download is allowed when the cellular network is used. | | NETWORK_MOBILE | number | Yes| No| Whether download is allowed on a mobile network.|
| NETWORK_WIFI | number | Yes | No | Whether download is allowed on a WLAN. | | NETWORK_WIFI | number | Yes| No| Whether download is allowed on a WLAN.|
| ERROR_CANNOT_RESUME<sup>7+</sup> | number | Yes | No | Failure to resume the download due to an error. | | ERROR_CANNOT_RESUME<sup>7+</sup> | number | Yes| No| Failure to resume the download due to an error.|
| ERROR_DEVICE_NOT_FOUND<sup>7+</sup> | number | Yes | No | Failure to find a storage device such as a memory card. | | ERROR_DEVICE_NOT_FOUND<sup>7+</sup> | number | Yes| No| Failure to find a storage device such as a memory card.|
| ERROR_FILE_ALREADY_EXISTS<sup>7+</sup> | number | Yes | No | Failure to download the file because it already exists. | | ERROR_FILE_ALREADY_EXISTS<sup>7+</sup> | number | Yes| No| Failure to download the file because it already exists.|
| ERROR_FILE_ERROR<sup>7+</sup> | number | Yes | No | File operation failure. | | ERROR_FILE_ERROR<sup>7+</sup> | number | Yes| No| File operation failure.|
| ERROR_HTTP_DATA_ERROR<sup>7+</sup> | number | Yes | No | HTTP transmission failure. | | ERROR_HTTP_DATA_ERROR<sup>7+</sup> | number | Yes| No| HTTP transmission failure.|
| ERROR_INSUFFICIENT_SPACE<sup>7+</sup> | number | Yes | No | Insufficient storage space. | | ERROR_INSUFFICIENT_SPACE<sup>7+</sup> | number | Yes| No| Insufficient storage space.|
| ERROR_TOO_MANY_REDIRECTS<sup>7+</sup> | number | Yes | No | Error caused by too many network redirections. | | ERROR_TOO_MANY_REDIRECTS<sup>7+</sup> | number | Yes| No| Error caused by too many network redirections.|
| ERROR_UNHANDLED_HTTP_CODE<sup>7+</sup> | number | Yes | No | Unidentified HTTP code. | | ERROR_UNHANDLED_HTTP_CODE<sup>7+</sup> | number | Yes| No| Unidentified HTTP code.|
| ERROR_UNKNOWN<sup>7+</sup> | number | Yes | No | Unknown error. | | ERROR_UNKNOWN<sup>7+</sup> | number | Yes| No| Unknown error.|
| PAUSED_QUEUED_FOR_WIFI<sup>7+</sup> | number | Yes | No | Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed by a cellular network session. | | PAUSED_QUEUED_FOR_WIFI<sup>7+</sup> | number | Yes| No| Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed by a mobile network session.|
| PAUSED_UNKNOWN<sup>7+</sup> | number | Yes | No | Download paused due to unknown reasons. | | PAUSED_UNKNOWN<sup>7+</sup> | number | Yes| No| Download paused due to unknown reasons.|
| PAUSED_WAITING_FOR_NETWORK<sup>7+</sup> | number | Yes | No | Download paused due to a network connection problem, for example, network disconnection. | | PAUSED_WAITING_FOR_NETWORK<sup>7+</sup> | number | Yes| No| Download paused due to a network connection problem, for example, network disconnection.|
| PAUSED_WAITING_TO_RETRY<sup>7+</sup> | number | Yes | No | Download paused and then retried. | | PAUSED_WAITING_TO_RETRY<sup>7+</sup> | number | Yes| No| Download paused and then retried.|
| SESSION_FAILED<sup>7+</sup> | number | Yes | No | Download failure without retry. | | SESSION_FAILED<sup>7+</sup> | number | Yes| No| Download failure without retry.|
| SESSION_PAUSED<sup>7+</sup> | number | Yes | No | Download paused. | | SESSION_PAUSED<sup>7+</sup> | number | Yes| No| Download paused.|
| SESSION_PENDING<sup>7+</sup> | number | Yes | No | Download pending. | | SESSION_PENDING<sup>7+</sup> | number | Yes| No| Download pending.|
| SESSION_RUNNING<sup>7+</sup> | number | Yes | No | Download in progress. | | SESSION_RUNNING<sup>7+</sup> | number | Yes| No| Download in progress.|
| SESSION_SUCCESSFUL<sup>7+</sup> | number | Yes | No | Successful download. | | SESSION_SUCCESSFUL<sup>7+</sup> | number | Yes| No| Successful download.|
## request.upload ## request.upload
...@@ -69,30 +72,36 @@ upload(config: UploadConfig): Promise&lt;UploadTask&gt; ...@@ -69,30 +72,36 @@ upload(config: UploadConfig): Promise&lt;UploadTask&gt;
Uploads files. This API uses a promise to return the result. Uploads files. This API uses a promise to return the result.
This API can be used only in the FA model.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Upload **System capability**: SystemCapability.MiscServices.Upload
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [UploadConfig](#uploadconfig) | Yes | Configurations of the upload. | | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
**Return value** **Return value**
| Type | Description | | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[UploadTask](#uploadtask)&gt; | Promise used to return the **UploadTask** object. | | Promise&lt;[UploadTask](#uploadtask)&gt; | Promise used to return the **UploadTask** object.|
**Example** **Example**
```js ```js
let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" };
let data = { name: "name123", value: "123" };
let header = { key1: "value1", key2: "value2" };
let uploadTask; let uploadTask;
request.upload({ url: 'https://patch', header: header, method: "POST", files: [file1], data: [data] }).then((data) => { let uploadConfig = {
url: 'https://patch',
header: { key1: "value1", key2: "value2" },
method: "POST",
files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }],
data: [{ name: "name123", value: "123" }],
};
request.upload(uploadConfig).then((data) => {
uploadTask = data; uploadTask = data;
}).catch((err) => { }).catch((err) => {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
...@@ -106,25 +115,31 @@ upload(config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void ...@@ -106,25 +115,31 @@ upload(config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void
Uploads files. This API uses an asynchronous callback to return the result. Uploads files. This API uses an asynchronous callback to return the result.
This API can be used only in the FA model.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Upload **System capability**: SystemCapability.MiscServices.Upload
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [UploadConfig](#uploadconfig) | Yes | Configurations of the upload. | | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | No | Callback used to return the **UploadTask** object. | | callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | No| Callback used to return the **UploadTask** object.|
**Example** **Example**
```js ```js
let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" };
let data = { name: "name123", value: "123" };
let header = { key1: "value1", key2: "value2" };
let uploadTask; let uploadTask;
request.upload({ url: 'https://patch', header: header, method: "POST", files: [file1], data: [data] }, (err, data) => { let uploadConfig = {
url: 'https://patch',
header: { key1: "value1", key2: "value2" },
method: "POST",
files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }],
data: [{ name: "name123", value: "123" }],
};
request.upload(uploadConfig, (err, data) => {
if (err) { if (err) {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
return; return;
...@@ -132,7 +147,86 @@ Uploads files. This API uses an asynchronous callback to return the result. ...@@ -132,7 +147,86 @@ Uploads files. This API uses an asynchronous callback to return the result.
uploadTask = data; uploadTask = data;
}); });
``` ```
## request.upload<sup>9+</sup>
upload(context: BaseContext, config: UploadConfig): Promise&lt;UploadTask&gt;
Uploads files. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Upload
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | BaseContext | Yes| Application-based context.|
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[UploadTask](#uploadtask)&gt; | Promise used to return the **UploadTask** object.|
**Example**
```js
let uploadTask;
let uploadConfig = {
url: 'https://patch',
header: { key1: "value1", key2: "value2" },
method: "POST",
files: { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" },
data: { name: "name123", value: "123" },
};
request.upload(globalThis.abilityContext, uploadConfig).then((data) => {
uploadTask = data;
}).catch((err) => {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
});
```
## request.upload<sup>9+</sup>
upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void
Uploads files. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Upload
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | BaseContext | Yes| Application-based context.|
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | No| Callback used to return the **UploadTask** object.|
**Example**
```js
let uploadTask;
let uploadConfig = {
url: 'https://patch',
header: { key1: "value1", key2: "value2" },
method: "POST",
files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }],
data: [{ name: "name123", value: "123" }],
};
request.upload(globalThis.abilityContext, uploadConfig, (err, data) => {
if (err) {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
return;
}
uploadTask = data;
});
```
## UploadTask ## UploadTask
...@@ -143,7 +237,7 @@ Implements file uploads. Before using any APIs of this class, you must obtain an ...@@ -143,7 +237,7 @@ Implements file uploads. Before using any APIs of this class, you must obtain an
on(type: 'progress', callback:(uploadedSize: number, totalSize: number) =&gt; void): void on(type: 'progress', callback:(uploadedSize: number, totalSize: number) =&gt; void): void
Subscribes to the upload progress event. This API uses an asynchronous callback to return the result. Subscribes to an upload event. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -151,17 +245,17 @@ Subscribes to the upload progress event. This API uses an asynchronous callback ...@@ -151,17 +245,17 @@ Subscribes to the upload progress event. This API uses an asynchronous callback
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes | Type of the event to subscribe to. The value is **progress** (upload progress). | | type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).|
| callback | function | Yes | Callback for the upload progress event. | | callback | function | Yes| Callback for the upload progress event.|
**callback** parameters Parameters of the callback function
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| uploadedSize | number | Yes | Size of the uploaded files, in KB. | | uploadedSize | number | Yes| Size of the uploaded files, in KB.|
| totalSize | number | Yes | Total size of the files to upload, in KB. | | totalSize | number | Yes| Total size of the files to upload, in KB.|
**Example** **Example**
...@@ -177,7 +271,7 @@ Subscribes to the upload progress event. This API uses an asynchronous callback ...@@ -177,7 +271,7 @@ Subscribes to the upload progress event. This API uses an asynchronous callback
on(type: 'headerReceive', callback: (header: object) =&gt; void): void on(type: 'headerReceive', callback: (header: object) =&gt; void): void
Subscribes to the **headerReceive** event, which is triggered when an HTTP response header is received. This API uses an asynchronous callback to return the result. Subscribes to an upload event. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -185,16 +279,16 @@ Subscribes to the **headerReceive** event, which is triggered when an HTTP respo ...@@ -185,16 +279,16 @@ Subscribes to the **headerReceive** event, which is triggered when an HTTP respo
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes | Type of the event to subscribe to. The value is **'headerReceive'** (response header). | | type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response header).|
| callback | function | Yes | Callback for the HTTP Response Header event. | | callback | function | Yes| Callback for the HTTP Response Header event.|
**callback** parameters Parameters of the callback function
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| header | object | Yes | HTTP Response Header. | | header | object | Yes| HTTP Response Header.|
**Example** **Example**
...@@ -210,7 +304,7 @@ Subscribes to the **headerReceive** event, which is triggered when an HTTP respo ...@@ -210,7 +304,7 @@ Subscribes to the **headerReceive** event, which is triggered when an HTTP respo
off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) =&gt; void): void off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) =&gt; void): void
Unsubscribes from the upload progress event. This API uses an asynchronous callback to return the result. Unsubscribes from an upload event. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -218,17 +312,17 @@ Unsubscribes from the upload progress event. This API uses an asynchronous callb ...@@ -218,17 +312,17 @@ Unsubscribes from the upload progress event. This API uses an asynchronous callb
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes | Type of the event to unsubscribe from. The value is **'progress'** (upload progress). | | type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).|
| callback | function | No | Callback for the upload progress event. | | callback | function | No| Callback for the upload progress event.|
**callback** parameters Parameters of the callback function
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| uploadedSize | number | Yes | Size of the uploaded files, in KB. | | uploadedSize | number | Yes| Size of the uploaded files, in KB.|
| totalSize | number | Yes | Total size of the files to upload, in KB. | | totalSize | number | Yes| Total size of the files to upload, in KB.|
**Example** **Example**
...@@ -244,7 +338,7 @@ Unsubscribes from the upload progress event. This API uses an asynchronous callb ...@@ -244,7 +338,7 @@ Unsubscribes from the upload progress event. This API uses an asynchronous callb
off(type: 'headerReceive', callback?: (header: object) =&gt; void): void off(type: 'headerReceive', callback?: (header: object) =&gt; void): void
Unsubscribes from the **headerReceive** event. This API uses an asynchronous callback to return the result. Unsubscribes from an upload event. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -252,16 +346,16 @@ Unsubscribes from the **headerReceive** event. This API uses an asynchronous cal ...@@ -252,16 +346,16 @@ Unsubscribes from the **headerReceive** event. This API uses an asynchronous cal
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes | Type of the event to unsubscribe from. The value is **'headerReceive'** (response header). | | type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).|
| callback | function | No | Callback for the HTTP Response Header event. | | callback | function | No| Callback for the HTTP Response Header event.|
**callback** parameters Parameters of the callback function
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| header | object | Yes | HTTP Response Header. | | header | object | Yes| HTTP Response Header.|
**Example** **Example**
...@@ -277,7 +371,7 @@ Unsubscribes from the **headerReceive** event. This API uses an asynchronous cal ...@@ -277,7 +371,7 @@ Unsubscribes from the **headerReceive** event. This API uses an asynchronous cal
remove(): Promise&lt;boolean&gt; remove(): Promise&lt;boolean&gt;
Removes this upload task. This API uses a promise to return the result. Removes this upload task. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -285,9 +379,9 @@ Removes this upload task. This API uses a promise to return the result. ...@@ -285,9 +379,9 @@ Removes this upload task. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result. If **true** is returned, the task is removed. If **false** is returned, the task fails to be removed. | | Promise&lt;boolean&gt; | Promise used to return the task removal result. If **true** is returned, the task is removed. If **false** is returned, the task fails to be removed.|
**Example** **Example**
...@@ -308,7 +402,7 @@ Removes this upload task. This API uses a promise to return the result. ...@@ -308,7 +402,7 @@ Removes this upload task. This API uses a promise to return the result.
remove(callback: AsyncCallback&lt;boolean&gt;): void remove(callback: AsyncCallback&lt;boolean&gt;): void
Removes this upload task. This API uses an asynchronous callback to return the result. Removes this upload task. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -316,9 +410,9 @@ Removes this upload task. This API uses an asynchronous callback to return the r ...@@ -316,9 +410,9 @@ Removes this upload task. This API uses an asynchronous callback to return the r
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
**Example** **Example**
...@@ -339,37 +433,42 @@ Removes this upload task. This API uses an asynchronous callback to return the r ...@@ -339,37 +433,42 @@ Removes this upload task. This API uses an asynchronous callback to return the r
## UploadConfig ## UploadConfig
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Upload **System capability**: SystemCapability.MiscServices.Upload
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| url | string | Yes | Resource URL. | | url | string | Yes| Resource URL.|
| header | object | Yes | HTTP or HTTPS header added to an upload request. | | header | object | Yes| HTTP or HTTPS header added to an upload request.|
| method | string | Yes | Request method, which can be **POST** or **PUT**. The default value is **POST**. | | method | string | Yes| Request method, which can be **'POST'** or **'PUT'**. The default value is **'POST'**.|
| files | Array&lt;[File](#file)&gt; | Yes | List of files to upload, which is submitted through **multipart/form-data**. | | files | Array&lt;[File](#file)&gt; | Yes| List of files to upload, which is submitted through **multipart/form-data**.|
| data | Array&lt;[RequestData](#requestdata)&gt; | Yes | Form data in the request body. | | data | Array&lt;[RequestData](#requestdata)&gt; | Yes| Form data in the request body.|
## File ## File
**System capability**: SystemCapability.MiscServices.Upload **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| filename | string | No | File name in the header when **multipart** is used. | | filename | string | No| File name in the header when **multipart** is used.|
| name | string | No | Name of a form item when **multipart** is used. The default value is **file**. | | name | string | No| Name of a form item when **multipart** is used. The default value is **file**.|
| uri | string | Yes | Local path for storing files.<br/>The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:<br>dataability:///com.domainname.dataability.persondata/person/10/file.txt<br>internal://cache/path/to/file.txt | | uri | string | Yes| Local path for storing files.<br>The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:<br>dataability:///com.domainname.dataability.persondata/person/10/file.txt<br><br>internal://cache/path/to/file.txt |
| type | string | No | Type of the file content. By default, the type is obtained based on the extension of the file name or URI. | | type | string | No| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.|
## RequestData ## RequestData
**System capability**: SystemCapability.MiscServices.Upload **Required permissions**: ohos.permission.INTERNET
| Name | Type | Mandatory | Description | **System capability**: SystemCapability.MiscServices.Download
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes | Name of a form element. | | name | string | Yes| Name of a form element.|
| value | string | Yes | Value of a form element. | | value | string | Yes| Value of a form element.|
## request.download ## request.download
...@@ -378,21 +477,23 @@ download(config: DownloadConfig): Promise&lt;DownloadTask&gt; ...@@ -378,21 +477,23 @@ download(config: DownloadConfig): Promise&lt;DownloadTask&gt;
Downloads files. This API uses a promise to return the result. Downloads files. This API uses a promise to return the result.
This API can be used only in the FA model.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download **System capability**: SystemCapability.MiscServices.Download
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [DownloadConfig](#downloadconfig) | Yes | Configurations of the download. | | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
**Return value** **Return value**
| Type | Description | | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;[DownloadTask](#downloadtask)&gt; | Promise used to return the result. | | Promise&lt;[DownloadTask](#downloadtask)&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -412,16 +513,18 @@ download(config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): v ...@@ -412,16 +513,18 @@ download(config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): v
Downloads files. This API uses an asynchronous callback to return the result. Downloads files. This API uses an asynchronous callback to return the result.
This API can be used only in the FA model.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download **System capability**: SystemCapability.MiscServices.Download
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [DownloadConfig](#downloadconfig) | Yes | Configurations of the download. | | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | No | Callback used to return the result. | | callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | No| Callback used to return the result.|
**Example** **Example**
...@@ -437,7 +540,72 @@ Downloads files. This API uses an asynchronous callback to return the result. ...@@ -437,7 +540,72 @@ Downloads files. This API uses an asynchronous callback to return the result.
}); });
``` ```
## request.download<sup>9+</sup>
download(context: BaseContext, config: DownloadConfig): Promise&lt;DownloadTask&gt;
Downloads files. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | BaseContext | Yes| Application-based context.|
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[DownloadTask](#downloadtask)&gt; | Promise used to return the result.|
**Example**
```js
let downloadTask;
request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => {
downloadTask = data;
}).catch((err) => {
console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
})
```
## request.download<sup>9+</sup>
download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void;
Downloads files. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | BaseContext | Yes| Application-based context.|
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | No| Callback used to return the result.|
**Example**
```js
let downloadTask;
request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap',
filePath: 'xxx/xxxxx.hap'}, (err, data) => {
if (err) {
console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
return;
}
downloadTask = data;
});
```
## DownloadTask ## DownloadTask
Implements file downloads. Implements file downloads.
...@@ -447,7 +615,7 @@ Implements file downloads. ...@@ -447,7 +615,7 @@ Implements file downloads.
on(type: 'progress', callback:(receivedSize: number, totalSize: number) =&gt; void): void on(type: 'progress', callback:(receivedSize: number, totalSize: number) =&gt; void): void
Subscribes to the download progress event. This API uses an asynchronous callback to return the result. Subscribes to a download event. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -455,17 +623,17 @@ Subscribes to the download progress event. This API uses an asynchronous callbac ...@@ -455,17 +623,17 @@ Subscribes to the download progress event. This API uses an asynchronous callbac
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes | Type of the event to subscribe to. The value is **'progress'** (download progress). | | type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).|
| callback | function | Yes | Callback for the download progress event. | | callback | function | Yes| Callback for the download progress event.|
**callback** parameters Parameters of the callback function
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| receivedSize | number | Yes | Size of the downloaded files, in KB. | | receivedSize | number | Yes| Size of the downloaded files, in KB.|
| totalSize | number | Yes | Total size of the files to download, in KB. | | totalSize | number | Yes| Total size of the files to download, in KB.|
**Example** **Example**
...@@ -481,7 +649,7 @@ Subscribes to the download progress event. This API uses an asynchronous callbac ...@@ -481,7 +649,7 @@ Subscribes to the download progress event. This API uses an asynchronous callbac
off(type: 'progress', callback?: (receivedSize: number, totalSize: number) =&gt; void): void off(type: 'progress', callback?: (receivedSize: number, totalSize: number) =&gt; void): void
Unsubscribes from the download progress event. This API uses an asynchronous callback to return the result. Unsubscribes from a download event. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -489,17 +657,17 @@ Unsubscribes from the download progress event. This API uses an asynchronous cal ...@@ -489,17 +657,17 @@ Unsubscribes from the download progress event. This API uses an asynchronous cal
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes | Type of the event to unsubscribe from. The value is **'progress'** (download progress). | | type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).|
| callback | function | No | Callback for the download progress event. | | callback | function | No| Callback for the download progress event.|
**callback** parameters Parameters of the callback function
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| receivedSize | number | Yes | Size of the downloaded files, in KB. | | receivedSize | number | Yes| Size of the downloaded files.|
| totalSize | number | Yes | Total size of the files to download, in KB. | | totalSize | number | Yes| Total size of the files to download.|
**Example** **Example**
...@@ -523,10 +691,10 @@ Subscribes to a download event. This API uses an asynchronous callback to return ...@@ -523,10 +691,10 @@ Subscribes to a download event. This API uses an asynchronous callback to return
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes | Event type.<br/>- **'complete'**: download task completion event.<br/>- **'pause'**: download task pause event.<br/>- **'remove'**: download task removal event. | | type | string | Yes| Type of the event to subscribe to.<br>- **'complete'**: download task completion event.<br>- **'pause'**: download task pause event.<br>- **'remove'**: download task removal event.|
| callback | function | Yes | Callback used to return the result. | | callback | function | Yes| Callback used to return the result.|
**Example** **Example**
...@@ -542,7 +710,7 @@ Subscribes to a download event. This API uses an asynchronous callback to return ...@@ -542,7 +710,7 @@ Subscribes to a download event. This API uses an asynchronous callback to return
off(type: 'complete'|'pause'|'remove', callback?:() =&gt; void): void off(type: 'complete'|'pause'|'remove', callback?:() =&gt; void): void
Unsubscribes from the download event. This API uses an asynchronous callback to return the result. Unsubscribes from a download event. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -550,10 +718,10 @@ Unsubscribes from the download event. This API uses an asynchronous callback to ...@@ -550,10 +718,10 @@ Unsubscribes from the download event. This API uses an asynchronous callback to
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes | Event type.<br/>- **'complete'**: download task completion event.<br/>- **'pause'**: download task pause event.<br/>- **'remove'**: download task removal event. | | type | string | Yes| Type of the event to unsubscribe from.<br>- **'complete'**: download task completion event.<br>- **'pause'**: download task pause event.<br>- **'remove'**: download task removal event.|
| callback | function | No | Callback used to return the result. | | callback | function | No| Callback used to return the result.|
**Example** **Example**
...@@ -577,16 +745,16 @@ Subscribes to the download task failure event. This API uses an asynchronous cal ...@@ -577,16 +745,16 @@ Subscribes to the download task failure event. This API uses an asynchronous cal
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes | Type of the subscribed event. The value is **'fail'** (download failure). | | type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).|
| callback | function | Yes | Callback for the download task failure event. | | callback | function | Yes| Callback for the download task failure event.|
**callback** parameters Parameters of the callback function
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| err | number | Yes | Error code of the download failure. For details about the error cause, see [ERROR_*](#constants). | | err | number | Yes| Error code of the download failure. For details about the error codes, see [ERROR_*](#constants).|
**Example** **Example**
...@@ -602,7 +770,7 @@ Subscribes to the download task failure event. This API uses an asynchronous cal ...@@ -602,7 +770,7 @@ Subscribes to the download task failure event. This API uses an asynchronous cal
off(type: 'fail', callback?: (err: number) =&gt; void): void off(type: 'fail', callback?: (err: number) =&gt; void): void
Unsubscribes from the download task failure event. This API uses an asynchronous callback to return the result. Unsubscribes from the download task failure event. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -610,16 +778,16 @@ Unsubscribes from the download task failure event. This API uses an asynchronous ...@@ -610,16 +778,16 @@ Unsubscribes from the download task failure event. This API uses an asynchronous
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| type | string | Yes | Type of the event to unsubscribe from. The value is **'fail'** (download failure). | | type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).|
| callback | function | No | Callback for the download task failure event. | | callback | function | No| Callback for the download task failure event.|
**callback** parameters Parameters of the callback function
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| err | number | Yes | Error code of the download failure. For details about the error cause, see [ERROR_*](#constants). | | err | number | Yes| Error code of the download failure. For details about the error codes, see [ERROR_*](#constants).|
**Example** **Example**
...@@ -643,9 +811,9 @@ Removes this download task. This API uses a promise to return the result. ...@@ -643,9 +811,9 @@ Removes this download task. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result. | | Promise&lt;boolean&gt; | Promise used to return the task removal result.|
**Example** **Example**
...@@ -674,9 +842,9 @@ Removes this download task. This API uses an asynchronous callback to return the ...@@ -674,9 +842,9 @@ Removes this download task. This API uses an asynchronous callback to return the
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the task removal result. | | callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the task removal result.|
**Example** **Example**
...@@ -706,10 +874,9 @@ Queries this download task. This API uses a promise to return the result. ...@@ -706,10 +874,9 @@ Queries this download task. This API uses a promise to return the result.
**System capability**: SystemCapability.MiscServices.Download **System capability**: SystemCapability.MiscServices.Download
**Parameters** **Parameters**
| Type| Description|
| Type | Description |
| -------- | -------- | | -------- | -------- |
| Promise&lt;[DownloadInfo](#downloadinfo7)&gt; | Promise used to return the download task information. | | Promise&lt;[DownloadInfo](#downloadinfo7)&gt; | Promise used to return the download task information.|
**Example** **Example**
...@@ -734,9 +901,9 @@ Queries this download task. This API uses an asynchronous callback to return the ...@@ -734,9 +901,9 @@ Queries this download task. This API uses an asynchronous callback to return the
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[DownloadInfo](#downloadinfo7)&gt; | Yes | Callback used to return the download task information. | | callback | AsyncCallback&lt;[DownloadInfo](#downloadinfo7)&gt; | Yes| Callback used to return the download task information.|
**Example** **Example**
...@@ -755,7 +922,7 @@ Queries this download task. This API uses an asynchronous callback to return the ...@@ -755,7 +922,7 @@ Queries this download task. This API uses an asynchronous callback to return the
queryMimeType(): Promise&lt;string&gt; queryMimeType(): Promise&lt;string&gt;
Queries **MimeType** of this download task. This API uses a promise to return the result. Queries the **MimeType** of this download task. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -763,9 +930,9 @@ Queries **MimeType** of this download task. This API uses a promise to return th ...@@ -763,9 +930,9 @@ Queries **MimeType** of this download task. This API uses a promise to return th
**Return value** **Return value**
| Type | Description | | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;string&gt; | Promise used to return **MimeType** of the download task. | | Promise&lt;string&gt; | Promise used to return the **MimeType** of the download task.|
**Example** **Example**
...@@ -782,7 +949,7 @@ Queries **MimeType** of this download task. This API uses a promise to return th ...@@ -782,7 +949,7 @@ Queries **MimeType** of this download task. This API uses a promise to return th
queryMimeType(callback: AsyncCallback&lt;string&gt;): void; queryMimeType(callback: AsyncCallback&lt;string&gt;): void;
Queries **MimeType** of this download task. This API uses an asynchronous callback to return the result. Queries the **MimeType** of this download task. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET **Required permissions**: ohos.permission.INTERNET
...@@ -790,9 +957,9 @@ Queries **MimeType** of this download task. This API uses an asynchronous callba ...@@ -790,9 +957,9 @@ Queries **MimeType** of this download task. This API uses an asynchronous callba
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return **MimeType** of the download task. | | callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the **MimeType** of the download task.|
**Example** **Example**
...@@ -819,9 +986,9 @@ Pauses this download task. This API uses a promise to return the result. ...@@ -819,9 +986,9 @@ Pauses this download task. This API uses a promise to return the result.
**Return value** **Return value**
| Type | Description | | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the download task pause result. | | Promise&lt;void&gt; | Promise used to return the download task pause result.|
**Example** **Example**
...@@ -850,9 +1017,9 @@ Pauses this download task. This API uses an asynchronous callback to return the ...@@ -850,9 +1017,9 @@ Pauses this download task. This API uses an asynchronous callback to return the
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example** **Example**
...@@ -883,9 +1050,9 @@ Resumes this download task. This API uses a promise to return the result. ...@@ -883,9 +1050,9 @@ Resumes this download task. This API uses a promise to return the result.
**Parameters** **Parameters**
| Type | Description | | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
...@@ -915,9 +1082,9 @@ Resumes this download task. This API uses an asynchronous callback to return the ...@@ -915,9 +1082,9 @@ Resumes this download task. This API uses an asynchronous callback to return the
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example** **Example**
...@@ -938,34 +1105,38 @@ Resumes this download task. This API uses an asynchronous callback to return the ...@@ -938,34 +1105,38 @@ Resumes this download task. This API uses an asynchronous callback to return the
## DownloadConfig ## DownloadConfig
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download **System capability**: SystemCapability.MiscServices.Download
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| url | string | Yes | Resource URL. | | url | string | Yes| Resource URL.|
| header | object | No | HTTP or HTTPS header added to a download request. | | header | object | No| HTTP or HTTPS header added to a download request.|
| enableMetered | boolean | No | Download allowed in metered connections. | | enableMetered | boolean | No| Download allowed in metered connections.|
| enableRoaming | boolean | No | Download allowed on a roaming network. | | enableRoaming | boolean | No| Download allowed on a roaming network.|
| description | string | No | Description of the download session. | | description | string | No| Description of the download session.|
| filePath<sup>7+</sup> | string | No | Download path. (The default path is **'internal://cache/'**.<br/>- filePath:'workspace/test.txt': The **workspace** directory is created in the default path to store files.<br/>- filePath:'test.txt': Files are stored in the default path.<br/>- filePath:'workspace/': The **workspace** directory is created in the default path to store files. | | filePath<sup>7+</sup> | string | No| Download path. (The default path is **'internal://cache/'**.)<br>- filePath:'workspace/test.txt': The **workspace** directory is created in the default path to store files.<br>- filePath:'test.txt': Files are stored in the default path.<br>- filePath:'workspace/': The **workspace** directory is created in the default path to store files.|
| networkType | number | No | Network type allowed for download. | | networkType | number | No| Network type allowed for download.|
| title | string | No | Title of the download session. | | title | string | No| Title of the download session.|
## DownloadInfo<sup>7+</sup> ## DownloadInfo<sup>7+</sup>
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download **System capability**: SystemCapability.MiscServices.Download
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| downloadId | number | Yes | ID of the downloaded file. | | downloadId | number | Yes| ID of the downloaded file.|
| failedReason | number | No | Download failure cause, which can be any constant of [ERROR_*](#constants). | | failedReason | number | No| Download failure cause, which can be any constant of [ERROR_*](#constants).|
| fileName | string | Yes | Name of the downloaded file. | | fileName | string | Yes| Name of the downloaded file.|
| filePath | string | Yes | URI of the saved file. | | filePath | string | Yes| URI of the saved file.|
| pausedReason | number | No | Reason for session pause, which can be any constant of [PAUSED_*](#constants). | | pausedReason | number | No| Reason for session pause, which can be any constant of [PAUSED_*](#constants).|
| status | number | Yes | Download status code, which can be any constant of [SESSION_*](#constants). | | status | number | Yes| Download status code, which can be any constant of [SESSION_*](#constants).|
| targetURI | string | Yes | URI of the downloaded file. | | targetURI | string | Yes| URI of the downloaded file.|
| downloadTitle | string | Yes | Title of the downloaded file. | | downloadTitle | string | Yes| Title of the downloaded file.|
| downloadTotalBytes | number | Yes | Total size of the downloaded file (int bytes). | | downloadTotalBytes | number | Yes| Total size of the files to download (int bytes).|
| description | string | Yes | Description of the file to download. | | description | string | Yes| Description of the file to download.|
| downloadedBytes | number | Yes | Size of the files downloaded (int bytes). | | downloadedBytes | number | Yes| Size of the files downloaded (int bytes).|
...@@ -91,7 +91,11 @@ struct ProgressExample { ...@@ -91,7 +91,11 @@ struct ProgressExample {
Text('Capsule Progress').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('Capsule Progress').fontSize(9).fontColor(0xCCCCCC).width('90%')
Row({ space: 40 }) { Row({ space: 40 }) {
Progress({ value: 10, type: ProgressType.Capsule }).width(100).height(50) Progress({ value: 10, type: ProgressType.Capsule }).width(100).height(50)
Progress({ value: 20, total: 150, type: ProgressType.Capsule }).color(Color.Grey).value(50).width(100).height(50) Progress({ value: 20, total: 150, type: ProgressType.Capsule })
.color(Color.Grey)
.value(50)
.width(100)
.height(50)
} }
}.width('100%').margin({ top: 30 }) }.width('100%').margin({ top: 30 })
} }
......
# Slider # Slider
> **NOTE**<br> > **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Slider&gt;** component is used to quickly adjust settings, such as the volume and brightness. The *\<Slider>** component is used to quickly adjust settings, such as the volume and brightness.
## Required Permissions ## Required Permissions
...@@ -15,7 +16,7 @@ None ...@@ -15,7 +16,7 @@ None
## Child Components ## Child Components
None Not supported
## APIs ## APIs
...@@ -44,12 +45,12 @@ Slider(value:{value?: number, min?: number, max?: number, step?: number, style?: ...@@ -44,12 +45,12 @@ Slider(value:{value?: number, min?: number, max?: number, step?: number, style?:
Touch target configuration is not supported. Touch target configuration is not supported.
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| ------------- | ------- | ------------- | -------------------------------------------------------------------- | | ------------- | ------- | ------------- | ---------------------------------------- |
| blockColor | Color | - | Color of the slider. | | blockColor | Color | - | Color of the slider. |
| trackColor | Color | - | Background color of the slider. | | trackColor | Color | - | Background color of the slider. |
| selectedColor | Color | - | Color of the slider rail that has been slid. | | selectedColor | Color | - | Color of the slider rail that has been slid. |
| showSteps | boolean | false | Whether to display the current step. | | showSteps | boolean | false | Whether to display the current step. |
| showTips | boolean | false | Whether to display a bubble to indicate the percentage when sliding. | | showTips | boolean | false | Whether to display a bubble to indicate the percentage when sliding. |
...@@ -62,17 +63,18 @@ Among all the universal events, only **OnAppear** and **OnDisAppear** are suppor ...@@ -62,17 +63,18 @@ Among all the universal events, only **OnAppear** and **OnDisAppear** are suppor
| onChange(callback: (value: number, mode: SliderChangeMode) =&gt; void) | Callback invoked when the slider slides.<br/>**value**: current progress.<br/>**mode**: dragging state. | | onChange(callback: (value: number, mode: SliderChangeMode) =&gt; void) | Callback invoked when the slider slides.<br/>**value**: current progress.<br/>**mode**: dragging state. |
- SliderChangeMode enums - SliderChangeMode enums
| Name | Description | | Name | Value | Description |
| ------ | ----------------------------------- | | ------ | ----- | ----------------------------------- |
| Begin | The user starts to drag the slider. | | Begin | 0 | The user starts to drag the slider. |
| Moving | The user is dragging the slider. | | Moving | 1 | The user is dragging the slider. |
| End | The user stops dragging the slider. | | End | 2 | The user stops dragging the slider. |
## Example ## Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct SliderExample { struct SliderExample {
......
# CanvasGradient # CanvasGradient
> **NOTE**<br> > **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -17,18 +18,18 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse ...@@ -17,18 +18,18 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| offset | number | Yes | 0 | Proportion of the distance between the color stop and the start point to the total length. The value ranges from 0 to 1. | | offset | number | Yes | 0 | Proportion of the distance between the color stop and the start point to the total length. The value ranges from 0 to 1. |
| color | string | Yes | 'ffffff' | Gradient color to set. | | color | string | Yes | '#ffffff'| Gradient color to set. |
- Example - Example
```ts
``` // xxx.ets
@Entry @Entry
@Component @Component
struct Page45 { struct Page45 {
private settings: RenderingContextSettings = new RenderingContextSettings(true) private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context) Canvas(this.context)
...@@ -37,9 +38,9 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse ...@@ -37,9 +38,9 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse
.backgroundColor('#ffff00') .backgroundColor('#ffff00')
.onReady(() =>{ .onReady(() =>{
var grad = this.context.createLinearGradient(50,0, 300,100) var grad = this.context.createLinearGradient(50,0, 300,100)
this.grad.addColorStop(0.0, 'red') grad.addColorStop(0.0, 'red')
this.grad.addColorStop(0.5, 'white') grad.addColorStop(0.5, 'white')
this.grad.addColorStop(1.0, 'green') grad.addColorStop(1.0, 'green')
this.context.fillStyle = grad this.context.fillStyle = grad
this.context.fillRect(0, 0, 500, 500) this.context.fillRect(0, 0, 500, 500)
}) })
......
# Scroll # Scroll
> **NOTE**
> - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> - When a **\<List>** is nested in this component, you are advised to specify the width and height of the **\<List>** under scenarios where consistently high performance is required. If the width and height are not specified, this component will load all content of the **\<List>**.
> **NOTE**<br>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Scroll>** component scrolls the content when the layout size of a component exceeds the viewport of its parent component.
The **<Scroll\>** component scrolls the content when the layout size of a component exceeds the viewport of its parent component.
## Required Permissions ## Required Permissions
None None.
## Child Components ## Child Components
...@@ -25,35 +25,45 @@ Scroll(scroller?: Scroller) ...@@ -25,35 +25,45 @@ Scroll(scroller?: Scroller)
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------------- | ---------------------------------------- | ------------------------ | --------- |
| scrollable | ScrollDirection | ScrollDirection.Vertical | Scroll method. | | scrollable | ScrollDirection | ScrollDirection.Vertical | Scroll method. |
| scrollBar | [BarState](ts-appendix-enums.md#barstate-enums) | Auto | Scroll bar status. | | scrollBar | [BarState](ts-appendix-enums.md#barstate-enums)| ScrollDirection.Auto | Scrollbar status. |
| scrollBarColor | Color | - | Color of the scroll bar. | | scrollBarColor | Color | - | Color of the scrollbar.|
| scrollBarWidth | Length | - | Width of the scrollbar. | | scrollBarWidth | Length | - | Width of the scrollbar.|
- ScrollDirection enums
| Name | Description |
| ---------- | ---------- |
| Horizontal | Only horizontal scrolling is supported.|
| Vertical | Only vertical scrolling is supported.|
| None | Scrolling is disabled. |
## Events
- ScrollDirection | Name | Description |
| Name | Description | | ---------------------------------------- | ----------------------------- |
| -------- | -------- | | onScrollBegin<sup>9+</sup>(dx: number, dy: number)&nbsp;=&gt;&nbsp;{ dxRemain: number, dyRemain: number } | Invoked when scrolling starts.<br>Parameters:<br>- **dx**: amount to scroll by in the horizontal direction.<br>- **dy**: amount to scroll by in the vertical direction.<br>Return value:<br>- **dxRemain**: remaining amount to scroll by in the horizontal direction.<br>- **dyRemain**: remaining amount to scroll by in the vertical direction.|
| Horizontal | Only horizontal scrolling is supported. | | onScroll(xOffset:&nbsp;number,&nbsp;yOffset:&nbsp;number)&nbsp;=&gt;&nbsp;void | Invoked to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs.|
| Vertical | Only vertical scrolling is supported. | | onScrollEdge(side:&nbsp;Edge)&nbsp;=&gt;&nbsp;void | Invoked when scrolling reaches the edge. |
| None | Scrolling is disabled. | | onScrollEnd()&nbsp;=&gt;&nbsp;void | Invoked when scrolling stops. |
> **NOTE**
> If the **onScrollBegin** event and **scrollBy** API are used to implement nested scrolling, you must set **edgeEffect** of the scrolling child node to **None**. For example, if a **\<List>** is nested in the **\<Scroll>** component, the **edgeEffect** attribute of the **\<List>** must be set to **EdgeEffect.None**.
## Scroller ## Scroller
Controller of the scrollable container component. You can bind this component to the container component and use it to control the scrolling of the container component. Currently, this component can be bound to the **<List\>** and **<Scroll\>** components. Controller of the scrollable container component. You can bind this component to a container component and use it to control the scrolling of that component. Currently, this component can be bound to the **\<List>** and **\<Scroll>** components.
### Objects to Import ### Objects to Import
``` ```
scroller: Scroller = new Scroller() scroller: Scroller = new Scroller()
``` ```
### scroller.scrollTo ### scrollTo
scrollTo(value: { xOffset: number | string, yOffset: number | string, animation?: { duration: number, curve: Curve } }): void scrollTo(value: { xOffset: number | string, yOffset: number | string, animation?: { duration: number, curve: Curve } }): void
...@@ -62,14 +72,14 @@ Scrolls to the specified position. ...@@ -62,14 +72,14 @@ Scrolls to the specified position.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | --------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| xOffset | Length | Yes | - | Horizontal scrolling offset. | | xOffset | Length | Yes | - | Horizontal scrolling offset. |
| yOffset | Length | Yes | - | Vertical scrolling offset. | | yOffset | Length | Yes | - | Vertical scrolling offset. |
| animation | {<br/>duration: number,<br/>curve: Curve \|<br/>CubicBezier \|<br/>SpringCurve<br/>} | No | | Animation configuration, which includes the following:<br/>- **duration**: scrolling duration.<br/>- **curve**: scrolling curve. | | animation | {<br>duration:&nbsp;number,<br>curve:&nbsp;[Curve](ts-animatorproperty.md)&nbsp;\|<br>CubicBezier&nbsp;\|<br>SpringCurve<br>} | No | | Animation configuration, which includes the following:<br>- **duration**: scrolling duration.<br>- **curve**: scrolling curve.|
### scroller.scrollEdge ### scrollEdge
scrollEdge(value: Edge): void scrollEdge(value: Edge): void
...@@ -78,68 +88,80 @@ Scrolls to the edge of the container. ...@@ -78,68 +88,80 @@ Scrolls to the edge of the container.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type| Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | ----- | ---- | ---- | ---- | --------- |
| value | Edge | Yes | - | Edge position to scroll to. | | value | Edge | Yes | - | Edge position to scroll to.|
### scroller.scrollPage ### scrollPage
scrollPage(value: { next: boolean, direction?: Axis }): void scrollPage(value: { next: boolean, direction?: Axis }): void
Scrolls to the next or previous page. Scrolls to the next or previous page.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | --------- | ------- | ---- | ---- | ------------------------------ |
| next | boolean | Yes | - | Whether to turn to the next page. The value **true** means to scroll to the next page, and the value **false** means to scroll to the previous page. | | next | boolean | Yes | - | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.|
| direction | Axis | No | - | Scrolling direction: horizontal or vertical. |
### scroller.currentOffset ### currentOffset
scroller.currentOffset(): Object currentOffset(): Object
Obtains the scrolling offset. Obtains the scrolling offset.
- Return value - Return value
| Type | Description | | Type | Description |
| -------- | -------- | | ------------------------------------------------------- | ------------------------------------------------------------ |
| {<br/>xOffset: number,<br/>yOffset: number<br/>} | - **xOffset**: horizontal scrolling offset.<br/>- **yOffset**: vertical scrolling offset. | | {<br>xOffset:&nbsp;number,<br>yOffset:&nbsp;number<br>} | **xOffset**: horizontal scrolling offset.<br>**yOffset**: vertical scrolling offset. |
### scroller.scrollToIndex ### scrollToIndex
scroller.scrollToIndex(value: number): void scrollToIndex(value: number): void
Scrolls to the specified index. Scrolls to the item with the specified index.
> **NOTE**<br> > **NOTE**
> Only the **<List\>** component is supported. > Only the **\<List>** component is supported.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- | | ----- | ------ | ---- | ---- | ----------------- |
| value | number | Yes | - | Index of the item to be scrolled to in the list. | | value | number | Yes | - | Index of the item to be scrolled to in the list.|
## Events ### scrollBy
| Name | Description | scrollBy(dx: Length, dy: Length): void
| -------- | -------- |
| onScroll(xOffset: number, yOffset: number) =&gt; void | Invoked to return the horizontal and vertical scrolling offsets when the specified scroll event occurs. |
| onScrollEdge(side: Edge) =&gt; void | Invoked when an item is scrolled to the edge. |
| onScrollEnd() =&gt; void | Invoked when scrolling stops. |
## Example Scrolls by the specified amount.
``` > **NOTE**
> Only the **\<Scroll>** component is supported.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| dx | Length | Yes | - | Amount to scroll by in the horizontal direction.|
| dy | Length | Yes | - | Amount to scroll by in the vertical direction.|
## Example
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ScrollExample { struct ScrollExample {
...@@ -152,14 +174,20 @@ struct ScrollExample { ...@@ -152,14 +174,20 @@ struct ScrollExample {
Column() { Column() {
ForEach(this.arr, (item) => { ForEach(this.arr, (item) => {
Text(item.toString()) Text(item.toString())
.width('90%').height(150).backgroundColor(0xFFFFFF) .width('90%')
.borderRadius(15).fontSize(16).textAlign(TextAlign.Center) .height(150)
.backgroundColor(0xFFFFFF)
.borderRadius(15)
.fontSize(16)
.textAlign(TextAlign.Center)
.margin({ top: 10 }) .margin({ top: 10 })
}, item => item) }, item => item)
}.width('100%') }.width('100%')
} }
.scrollable(ScrollDirection.Vertical).scrollBar(BarState.On) .scrollable(ScrollDirection.Vertical)
.scrollBarColor(Color.Gray).scrollBarWidth(30) .scrollBar(BarState.On)
.scrollBarColor(Color.Gray)
.scrollBarWidth(30)
.onScroll((xOffset: number, yOffset: number) => { .onScroll((xOffset: number, yOffset: number) => {
console.info(xOffset + ' ' + yOffset) console.info(xOffset + ' ' + yOffset)
}) })
...@@ -171,17 +199,17 @@ struct ScrollExample { ...@@ -171,17 +199,17 @@ struct ScrollExample {
}) })
Button('scroll 100') Button('scroll 100')
.onClick(() => {// Click to scroll down 100.0. .onClick(() => { // Click to scroll down 100.0.
this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 }) this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 })
}) })
.margin({ top: 10, left: 20 }) .margin({ top: 10, left: 20 })
Button('back top') Button('back top')
.onClick(() => {// Click to go back to the top. .onClick(() => { // Click to go back to the top.
this.scroller.scrollEdge(Edge.Top) this.scroller.scrollEdge(Edge.Top)
}) })
.margin({ top: 60, left: 20 }) .margin({ top: 60, left: 20 })
Button('next page') Button('next page')
.onClick(() => {// Click to scroll down to the bottom. .onClick(() => { // Click to scroll down to the bottom.
this.scroller.scrollPage({ next: true }) this.scroller.scrollPage({ next: true })
}) })
.margin({ top: 110, left: 20 }) .margin({ top: 110, left: 20 })
...@@ -191,3 +219,58 @@ struct ScrollExample { ...@@ -191,3 +219,58 @@ struct ScrollExample {
``` ```
![en-us_image_0000001256978363](figures/en-us_image_0000001256978363.gif) ![en-us_image_0000001256978363](figures/en-us_image_0000001256978363.gif)
```ts
@Entry
@Component
struct NestedScroll {
@State listPosition: number = 0 // 0 indicates scrolling to the top of the list, 1 indicates scrolling to the center of the list, and 2 indicates scrolling to the bottom of the list.
private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
private scroller: Scroller = new Scroller()
build() {
Flex() {
Scroll(this.scroller) {
Column() {
Text("Scroll Area")
.width("100%").height("40%").backgroundColor(0X330000FF)
.fontSize(16).textAlign(TextAlign.Center)
List({ space: 20 }) {
ForEach(this.arr, (item) => {
ListItem() {
Text("ListItem" + item)
.width("100%").height("100%").borderRadius(15)
.fontSize(16).textAlign(TextAlign.Center).backgroundColor(Color.White)
}.width("100%").height(100)
}, item => item)
}
.width("100%").height("50%").edgeEffect(EdgeEffect.None)
.onReachStart(() => {
this.listPosition = 0
})
.onReachEnd(() => {
this.listPosition = 2
})
.onScrollBegin((dx: number, dy: number) => {
if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) {
this.scroller.scrollBy(0, -dy)
return { dxRemain: dx, dyRemain: 0 }
}
this.listPosition = 1;
return { dxRemain: dx, dyRemain: dy }
})
Text("Scroll Area")
.width("100%").height("40%").backgroundColor(0X330000FF)
.fontSize(16).textAlign(TextAlign.Center)
}
}
.width("100%").height("100%")
}.width('100%').height('100%').backgroundColor(0xDCDCDC).padding(20)
}
}
```
![NestedScroll](figures/NestedScroll.gif)
# Button
The **\<Button>** component can be used to create different types of buttons.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components
Supported
## APIs
- Button(options?: {type?: ButtonType, stateEffect?: boolean})
**Table 1** options parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| type | ButtonType | No | Capsule | Button type. |
| stateEffect | boolean | No | true | Whether to enable the state switchover effect when a button is pressed. When the state is set to **false**, the state switchover effect is disabled. |
- Button(label?: ResourceStr, options?: { type?: ButtonType, stateEffect?: boolean })
Creates a button component based on text content. In this case, the **\<Button>** component cannot contain child components.
**Table 2** Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| label | [ResourceStr](../../ui/ts-types.md) | No | - | Button text. |
| options | Object | No | - | For details, see the **options** parameters. |
## Attributes
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| type | ButtonType | Capsule | Button type. |
| stateEffect | boolean | true | Whether to enable the state switchover effect. When the state is set to **false**, the state switchover effect is disabled. |
**ButtonType** enums
| Name | Description |
| -------- | -------- |
| Capsule | Capsule-type button (the round corner is half of the height by default). |
| Circle | Circle button. |
| Normal | Normal button (without rounded corners by default). |
> **NOTE**
> - The rounded corner of a button is set by using [Border](ts-universal-attributes-border.md). (The rounded corner cannot be set by using a border API.)
> - When the button type is **Capsule**, the **borderRadius** settings do not take effect, and the rounded corner of the button is always half of the button height.
> - When the button type is **Circle**, the value of **borderRadius** is used as the button radius. If **borderRadius** is not set, the button radius is half of the width or height, whichever is smaller.
> - The button text is set using the [common text style](ts-universal-attributes-text-style.md).
## Example
```ts
// xxx.ets
@Entry
@Component
struct ButtonExample {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
Text('Common button').fontSize(9).fontColor(0xCCCCCC)
Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Button('Ok', { type: ButtonType.Normal, stateEffect: true }).borderRadius(8).backgroundColor(0x317aff).width(90)
Button({ type: ButtonType.Normal, stateEffect: true }) {
Row() {
// You are advised to reference an image by using $r to create a Resource object.
Image($r('app.media.loading')).width(20).height(20).margin({ left: 12 })
Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 })
}.alignItems(VerticalAlign.Center)
}.borderRadius(8).backgroundColor(0x317aff).width(90)
Button('Disable', { type: ButtonType.Normal, stateEffect: false }).opacity(0.5)
.borderRadius(8).backgroundColor(0x317aff).width(90)
}
Text('Capsule button').fontSize(9).fontColor(0xCCCCCC)
Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Button('Ok', { type: ButtonType.Capsule, stateEffect: true }).backgroundColor(0x317aff).width(90)
Button({ type: ButtonType.Capsule, stateEffect: true }) {
Row() {
Image($r('app.media.loading')).width(20).height(20).margin({ left: 12 })
Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 })
}.alignItems(VerticalAlign.Center).width(90)
}.backgroundColor(0x317aff)
.onClick((event: ClickEvent) => {
AlertDialog.show({ message: 'The login is successful' })
})
Button('Disable', { type: ButtonType.Capsule, stateEffect: false }).opacity(0.5)
.backgroundColor(0x317aff).width(90)
}
Text('Circle button').fontSize(9).fontColor(0xCCCCCC)
Flex({ alignItems: ItemAlign.Center, wrap: FlexWrap.Wrap }) {
Button({ type: ButtonType.Circle, stateEffect: true }) {
Image($r('app.media.ic_public_app_filled')).width(20).height(20)
}.width(55).height(55).backgroundColor(0x317aff)
Button({ type: ButtonType.Circle, stateEffect: true }) {
Image($r('app.media.ic_public_delete_filled')).width(30).height(30)
}.width(55).height(55).margin({ left: 20 }).backgroundColor(0xF55A42)
}
}.height(400).padding({ left: 35, right: 35, top: 35 })
}
}
```
![en-us_image_0000001257138341](figures/en-us_image_0000001257138341.gif)
# @Component # @Component
A struct decorated by **@Component** has the componentization capability and can serve as an independent component. This type of component is also called a custom component, and its UI structure is described in the **build** method. Custom components have the following features:
A struct decorated by @Component has the componentization capability and can serve as an independent component. This type of component is also called a custom component, and its UI structure is described in the build method. Custom components have the following features:
- Composability: Custom components can be used with preset or other components, as well as common attributes and methods. - Composability: Custom components can be used with preset or other components, as well as common attributes and methods.
- Chain call<sup>9+</sup>: Universal attributes can be invoked in chain call mode to change the component style.
- Reusable: Custom components can be reused by other components and used as different instances in different parent components or containers. - Reusable: Custom components can be reused by other components and used as different instances in different parent components or containers.
- Lifecycle: Custom components provide callbacks for service logic processing throughout the lifecycle. - Lifecycle: Custom components provide callbacks for service logic processing throughout the lifecycle.
- Data-driven update: The UI of custom components can be automatically updated based on the data of state variables. - Data-driven update: The UI of custom components can be automatically updated based on the data of state variables.
For details about componentization, see [About @Component](ts-function-build.md). For details about componentization, see [About @Component](ts-custom-component-initialization.md).
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**: > **NOTE**
> - The build method must be defined for a custom component. >
> > - The **build** method must be defined for a custom component.
> - Custom constructors are prohibited for custom components. >- Custom constructors are prohibited for custom components.
The following code illustrates how to create a custom component named MyComponent: The following code illustrates how to create a custom component named **MyComponent**:
```
```ts
@Component @Component
struct MyComponent { struct MyComponent {
build() { build() {
...@@ -37,12 +35,13 @@ struct MyComponent { ...@@ -37,12 +35,13 @@ struct MyComponent {
``` ```
The build method of MyComponent is executed during initial rendering. When the component status changes, the build method will be executed again. The **build** method of **MyComponent** is executed during initial rendering. When the component status changes, the **build** method will be executed again.
The following code illustrates how to use MyComponent: The following code illustrates how to use **MyComponent**:
```
```ts
@Component @Component
struct ParentComponent { struct ParentComponent {
build() { build() {
...@@ -56,9 +55,10 @@ struct ParentComponent { ...@@ -56,9 +55,10 @@ struct ParentComponent {
``` ```
MyComponent can be applied multiple times and reused in different components, as shown in the code below: **MyComponent** can be applied multiple times and reused in different components, as shown in the code below:
```
```ts
@Component @Component
struct ParentComponent { struct ParentComponent {
build() { build() {
...@@ -76,12 +76,47 @@ struct ParentComponent { ...@@ -76,12 +76,47 @@ struct ParentComponent {
} }
} }
private aboutToAppear() { aboutToAppear() {
console.log('ParentComponent: Just created, about to become rendered first time.') console.log('ParentComponent: Just created, about to become rendered first time.')
} }
private aboutToDisappear() { aboutToDisappear() {
console.log('ParentComponent: About to be removed from the UI.') console.log('ParentComponent: About to be removed from the UI.')
} }
} }
``` ```
Universal attributes can be invoked in chain call mode to diversify component styles.
> **NOTE**
>
> This feature is supported since API version 9.
>
> The chain call for custom components does not support trailing closures in the following scenario: When the custom component is initialized, the component name is followed by a pair of braces ({}) to form a trailing closure (as in `Index(){}`). You can consider a trailing closure as a container and add content to it, as in `{Column(){Text("content")}`.
```ts
@Entry
@Component
struct Index {
@State bannerValue: string = 'Hello,world';
build() {
Column() {
Chind({ ChindBannerValue:$bannerValue })
.height(60)
.width(250)
.border({ width:5, color:Color.Red, radius:10, style: BorderStyle.Dotted })
}
}
}
@Component
struct Chind {
@Link ChindBannerValue: string;
build() {
Column() {
Text(this.ChindBannerValue)
.fontSize(30)
}
}
}
```
...@@ -14,17 +14,17 @@ A component can access only one **LocalStorage** instance, and a **LocalStorage* ...@@ -14,17 +14,17 @@ A component can access only one **LocalStorage** instance, and a **LocalStorage*
## @LocalStorageLink Decorator ## @LocalStorageLink Decorator
Two-way data binding can be established between a component and the **LocalStorage** through the component's state variable decorated by **@LocalStorageLink(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. When a component that contains a **@LocalStorageLink** decorated state variable is created, the state variable is initialized with the initial value of the **LocalStorage**. If no initial value is assigned for the **LocalStorage**, the state variable will use the value defined by **@LocalStorageLink**. Changes made to this variable in the component will be first synchronized to the **LocalStorage**, and then to other components of the bound ability. Two-way data binding can be established between a component and the **LocalStorage** through the component's state variable decorated by **@LocalStorageLink(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. When a component that contains a **@LocalStorageLink** decorated state variable is created, the state variable is initialized with the value predefined in the **LocalStorage**. If no initial value is assigned in the **LocalStorage**, the state variable will use the value defined by **@LocalStorageLink**. Changes made to this variable in the component will be first synchronized to the **LocalStorage**, and then to other components of the bound ability.
## @LocalStorageProp Decorator ## @LocalStorageProp Decorator
One-way data binding can be established between a component and the **LocalStorage** through the component's state variable decorated by **@LocalStorageLink(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. When a component that contains a **@LocalStorageProp** decorated state variable is created, the state variable is initialized with the value predefined in the **LocalStorage**. Changes made to the value in the **LocalStorage** will cause all UI components of the bound ability to update the state. One-way data binding can be established between a component and the **LocalStorage** through the component's state variable decorated by **@LocalStorageProp(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. When a component that contains a **@LocalStorageProp** decorated state variable is created, the state variable is initialized with the value predefined in the **LocalStorage**. Changes made to the value in the **LocalStorage** will cause all UI components of the bound ability to update the state.
> **NOTE** > **NOTE**
> >
> If a **LocalStorage** instance has initial values assigned when being created, these values will be used for the **@LocalStorageLink** and **@LocalStorageProp** decorated state variables in the component. Otherwise, the initial values assigned for **@LocalStorageLink** and **@LocalStorageProp** will be used instead. > If a **LocalStorage** instance has initial values assigned when being created, these values will be used for the **@LocalStorageLink** and **@LocalStorageProp** decorated state variables in the component. Otherwise, the initial values assigned for **@LocalStorageLink** and **@LocalStorageProp** will be used instead.
## LocalStorage APIs ## LocalStorage
### constructor ### constructor
...@@ -34,9 +34,25 @@ Creates and initializes a **LocalStorage** instance. ...@@ -34,9 +34,25 @@ Creates and initializes a **LocalStorage** instance.
**Parameters** **Parameters**
| Name | Type | Mandatory| Default Value| Description | | Name | Type | Mandatory | Default Value | Description |
| ---------------------- | ------ | :--: | ------ | ------------------------------------------------------------ | | ---------------------- | ------ | :--: | ---- | ---------------------------------------- |
| initializingProperties | Object | No | - | Object attributes and their values returned by **object.keys(obj)**.| | initializingProperties | Object | No | - | Object attributes and their values returned by **object.keys(obj)**.|
### GetShared
static GetShared(): LocalStorage
Obtains the current shared **LocalStorage** object.
This API can be used only in the stage model.
**Return value**
| Type | Description |
| ----------------------------- | ----------------- |
| [LocalStorage](#localstorage) | **LocalStorage** object.|
...@@ -48,14 +64,14 @@ Checks whether the **LocalStorage** contains the specified attribute value. ...@@ -48,14 +64,14 @@ Checks whether the **LocalStorage** contains the specified attribute value.
**Parameters** **Parameters**
| Name | Type | Mandatory| Default Value| Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | :--: | ------ | -------------- | | -------- | ------ | :--: | ---- | ------- |
| propName | string | Yes | - | Attribute value.| | propName | string | Yes | - | Attribute value.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | -------------------------- | | ------- | ------------- |
| boolean | Whether the attribute value is contained.| | boolean | Whether the attribute value is contained.|
...@@ -68,14 +84,14 @@ Obtains the value corresponding to the given key. ...@@ -68,14 +84,14 @@ Obtains the value corresponding to the given key.
**Parameters** **Parameters**
| Name | Type | Mandatory| Default Value| Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | :--: | ------ | ------------------- | | -------- | ------ | :--: | ---- | ----------- |
| propName | string | Yes | - | Key of the value to obtain.| | propName | string | Yes | - | Key of the value to obtain.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| -------------- | ------------------------------------------------------- | | -------------- | ---------------------------------------- |
| T \| undefined | Returns the value if it is found; returns **undefined** otherwise.| | T \| undefined | Returns the value if it is found; returns **undefined** otherwise.|
...@@ -88,15 +104,15 @@ Sets the value for the given key. ...@@ -88,15 +104,15 @@ Sets the value for the given key.
**Parameters** **Parameters**
| Name | Type | Mandatory| Default Value| Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | :--: | ------ | ----------------- | | -------- | ------ | :--: | ---- | ----------- |
| propName | string | Yes | - | Key of the value to set. | | propName | string | Yes | - | Key of the value to set. |
| newValue | T | Yes | - | Value to set.| | newValue | T | Yes | - | Value to set.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ----------------------------------------------------- | | ------- | ----------------------------------- |
| boolean | Returns **true** if the value is successfully set for the key; returns **false** otherwise.| | boolean | Returns **true** if the value is successfully set for the key; returns **false** otherwise.|
...@@ -109,16 +125,16 @@ Creates or updates the value for the given key. ...@@ -109,16 +125,16 @@ Creates or updates the value for the given key.
**Parameters** **Parameters**
| Name | Type | Mandatory| Default Value| Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | :--: | ------ | ----------------------- | | -------- | ------ | :--: | ---- | -------------- |
| propName | string | Yes | - | Key of the value to create or update.| | propName | string | Yes | - | Key of the value to create or update. |
| newValue | T | Yes | - | Value to create or update.| | newValue | T | Yes | - | Value to create or update.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ------------------------------------------------------------ | | ------- | ---------------------------------------- |
| boolean | Updates the value of the attribute and returns **true** if an attribute that has the same name as the specified key exists; creates an attribute with the specified value as its default value and returns **false** otherwise. **true** cannot be returned for **undefined** or **null**.| | boolean | Updates the value of the attribute and returns **true** if an attribute that has the same name as the specified key exists; creates an attribute with the specified value of the T type as its default value and returns **false** otherwise. **true** cannot be returned for **undefined** or **null**.|
...@@ -130,14 +146,14 @@ Establishes two-way data binding between an attribute and this **LocalStorage** ...@@ -130,14 +146,14 @@ Establishes two-way data binding between an attribute and this **LocalStorage**
**Parameters** **Parameters**
| Name | Type | Mandatory| Default Value| Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | :--: | ------ | ---------------------- | | -------- | ------ | :--: | ---- | ----------- |
| propName | string | Yes | - | Key of the target attribute.| | propName | string | Yes | - | Key of the target attribute.|
**Return value** **Return value**
| Type| Description | | Type | Description |
| ---- | ------------------------------------------------------------ | | ---- | ---------------------------------------- |
| T | Returns the two-way data binding if an attribute that has the same name as the specified key exists; returns **undefined** otherwise.| | T | Returns the two-way data binding if an attribute that has the same name as the specified key exists; returns **undefined** otherwise.|
...@@ -146,20 +162,20 @@ Establishes two-way data binding between an attribute and this **LocalStorage** ...@@ -146,20 +162,20 @@ Establishes two-way data binding between an attribute and this **LocalStorage**
setAndLink\<T>(propName: string, defaultValue: T): T setAndLink\<T>(propName: string, defaultValue: T): T
Establishes two-way data binding between an attribute and this **LocalStorage** instance. Establishes two-way data binding between an attribute and this **LocalStorage** instance. This API works in a way similar to the **link** API.
**Parameters** **Parameters**
| Name | Type | Mandatory| Default Value| Description | | Name | Type | Mandatory | Default Value | Description |
| ------------ | ------ | :--: | ------ | -------------------- | | ------------ | ------ | :--: | ---- | ----------- |
| propName | string | Yes | - | Key of the target attribute. | | propName | string | Yes | - | Key of the target attribute.|
| defaultValue | T | Yes | - | Default value of the target attribute to set.| | defaultValue | T | Yes | - | Default value to set. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------------- | ------------------------------------------------------------ | | ------------------------------------- | ---------------------------------------- |
| [@Link](ts-component-states-link.md)| Returns the two-way data binding if an attribute that has the same name as the specified key exists; creates an attribute with the specified value as its default value and returns the attribute otherwise.| | [@Link](ts-component-states-link.md ) | Returns the value corresponding to the specified key if the key is stored in the **LocalStorage**; creates and returns a **Link** instance with the specified value as its default value otherwise|
...@@ -171,15 +187,15 @@ Establishes one-way data binding with an attribute to update its status. ...@@ -171,15 +187,15 @@ Establishes one-way data binding with an attribute to update its status.
**Parameters** **Parameters**
| Name | Type | Mandatory| Default Value| Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | :--: | ------ | ----------------------- | | -------- | ------ | :--: | ---- | ------------- |
| propName | string | Yes | - | Key of the target attribute.| | propName | string | Yes | - | Key of the target attribute.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------------ | ------------------------------------------------------------ | | ------------------------------------ | ---------------------------------------- |
| [@Prop](ts-component-states-prop.md) | Returns the one-way data binding if an attribute that has the same name as the specified key exists; returns **undefined** otherwise. Note that the variables returned are immutable variables, which are applicable to variable and immutable state variables.| | [@Prop](ts-component-states-prop.md) | Returns one-way binding to an attribute with a given key if the attribute exists; returns **undefined** otherwise. This means that attribute changes made through the **LocalStorage** will be synchronized to the variable or component, but attribute changes made by the variable or component will be synchronized to the **LocalStorage**. Note that the variables returned are immutable variables, which are applicable to mutable and immutable state variables. |
...@@ -187,20 +203,20 @@ Establishes one-way data binding with an attribute to update its status. ...@@ -187,20 +203,20 @@ Establishes one-way data binding with an attribute to update its status.
setAndProp\<T>(propName: string, defaultValue: T): T setAndProp\<T>(propName: string, defaultValue: T): T
Works in a way similar to the **Prop** API and sets up one-way data binding with the **localStorage**. Sets up one-way data binding with the **localStorage**. This API works in a way similar to the **Prop** API.
**Parameters** **Parameters**
| Name | Type | Mandatory| Default Value| Description | | Name | Type | Mandatory | Default Value | Description |
| ------------ | ------ | :--: | ------ | --------------------------- | | ------------ | ------ | :--: | ---- | --------------- |
| propName | string | Yes | - | Key value in the key-value pair to be saved.| | propName | string | Yes | - | Key value in the key-value pair to be saved.|
| defaultValue | T | Yes | - | Default value created. | | defaultValue | T | Yes | - | Default value to set. |
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------------------------ | ------------------------------------------------------------ | | ------------------------------------ | ---------------------------------------- |
| [@Prop](ts-component-states-prop.md) | Returns the value corresponding to the key if the current key is stored in the **LocalStorage**; creates and returns a **Prop** instance corresponding to the default value if the key has not been created.| | [@Prop](ts-component-states-prop.md) | Returns the value corresponding to the specified key if the key is stored in the **LocalStorage**; creates and returns a **Prop** instance with the specified value as its default value otherwise.|
...@@ -212,15 +228,15 @@ Deletes the key-value pair specified by key. ...@@ -212,15 +228,15 @@ Deletes the key-value pair specified by key.
**Parameters** **Parameters**
| Name | Type | Mandatory| Default Value| Description | | Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | :--: | ------ | --------------------- | | -------- | ------ | :--: | ---- | ------------ |
| propName | string | Yes | - | Key value of the attribute to be deleted.| | propName | string | Yes | - | Key value of the attribute to be deleted.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ------------------------------------------------------------ | | ------- | ---------------------------------------- |
| boolean | Deletes the key-value pair for the specified key. Returns **true** if the key-value pair exists and is successfully deleted; returns **false** otherwise.| | boolean | Returns **true** if the key-value pair exists and is successfully deleted; returns **false** otherwise.|
...@@ -232,8 +248,8 @@ Searches for all keys. ...@@ -232,8 +248,8 @@ Searches for all keys.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------- | ---------------------------- | | -------------- | -------------- |
| array\<string> | Returns an array of strings containing all keys.| | array\<string> | Returns an array of strings containing all keys.|
...@@ -246,8 +262,8 @@ Number of existing key-value pairs. ...@@ -246,8 +262,8 @@ Number of existing key-value pairs.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------ | ------------------ | | ------ | --------- |
| number | Number of key-value pairs.| | number | Number of key-value pairs.|
...@@ -260,14 +276,14 @@ Deletes all attributes. ...@@ -260,14 +276,14 @@ Deletes all attributes.
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------- | ------------------------------------------------------------ | | ------- | --------------------------------- |
| boolean | Deletes all attributes. If any of the attributes is being referenced by a state variable, **false** is returned.| | boolean | Returns **true** if all attributes are deleted; returns **false** if any of the attributes is being referenced by a state variable.|
### Example 1 (Creating a LocalStorage in an Ability) ### Example 1 (Creating a LocalStorage in an Ability)
```javascript ```ts
import Ability from '@ohos.appLication.Ability' import Ability from '@ohos.application.Ability'
export default class MainAbility extends Ability { export default class MainAbility extends Ability {
storage : LocalStorage storage : LocalStorage
onCreate(want) { onCreate(want) {
...@@ -296,7 +312,7 @@ export default class MainAbility extends Ability { ...@@ -296,7 +312,7 @@ export default class MainAbility extends Ability {
The @Component decorated component obtains data. The @Component decorated component obtains data.
``` ```ts
let storage = LocalStorage.GetShared() let storage = LocalStorage.GetShared()
@Entry(storage) @Entry(storage)
@Component @Component
...@@ -318,28 +334,28 @@ struct LocalStorageComponent { ...@@ -318,28 +334,28 @@ struct LocalStorageComponent {
### Example 2 (Defining LocalStorage on the Entry Page) ### Example 2 (Defining LocalStorage on the Entry Page)
``` ```ts
let storage = new LocalStorage({"PropA":47}); let storage = new LocalStorage({"PropA":47});
@Entry(storage) @Entry(storage)
@Component @Component
struct ComA { struct ComA {
@LocalStorageLink("PropA") storLink : number = 1; @LocalStorageLink("PropA") storLink: number = 1;
build() { build() {
Column() { Column() {
Text(`Parent from LocalStorage $(this.storLink)`) Text(`Parent from LocalStorage ${ this.storLink }`)
.onClick(()=>this.storLink+=1) .onClick(()=>this.storLink+=1)
Child() Child()
} }
} }
} }
@Component @Component
struct Child{ struct Child{
@LocalStorageLink("PropA") storLink : number = 1; @LocalStorageLink("PropA") storLink: number = 1;
build() { build() {
Text(`Parent from LocalStorage $(this.storLink)`) Text(`Parent from LocalStorage ${ this.storLink }`)
.onClick(()=>this.storLink1+=1) .onClick(()=>this.storLink+=1)
} }
} }
``` ```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册