“bc2b95dadcd174295f2ed15ed87b02c61a3c83ad”上不存在“assets/js/gitalk.min.js”
提交 4715fb88 编写于 作者: zyjhandsome's avatar zyjhandsome

Merge branch 'master' of https://gitee.com/openharmony/docs

......@@ -14,6 +14,8 @@ The sample server provides a package search server for checking update packages
openssl req -newkey rsa:2048 -nodes -keyout serverKey.pem -x509 -days 365 -out serverCert.cer -subj "/C=CN/ST=GD/L=GZ/O=abc/OU=defg/CN=hijk/emailAddress=test.com"
```
2. Modify the **bundle.json** file.
Add **sub_component** to the **build** field.
......@@ -173,7 +175,7 @@ The sample server provides a package search server for checking update packages
"\"descriptPackageId\": \"abcdefg1234567ABCDEFG\","
"}],"
"\"descriptInfo\": [{"
"\"descriptPackageId\": \"abcdefg1234567ABCDEFG\","
"\"descriptionType\": 0,"
"\"content\": \"This package message is used for sampleContent\""
"}]"
"}";
......
......@@ -30,7 +30,7 @@ The following is an example of the JSON response returned by the server. Note th
"descriptPackageId": "abcdefg1234567ABCDEFG"
}],
"descriptInfo": [{
"descriptPackageId": "abcdefg1234567ABCDEFG",
"descriptionType": 0,
"content": "This package is used for update."
}]
}
......
# Upload and Download
# @ohos.request
The **request** module provides applications with basic upload, download, and background transmission agent capabilities.
> **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.
......@@ -34,8 +34,9 @@ var config = {
The **cleartextTraffic** attribute is not involved during application development in the stage model.
The download server must support the HTTP HEAD method so that the size of the data to download can be obtained through **content-length**. Otherwise, the download task fails. If this is the case, you can check the failure cause through [on('fail')<sup>7+</sup>)](#onfail7).
The download server must support the HTTP HEAD method so that the size of the data to download can be obtained through **Content-length**. Otherwise, the download task fails. If this is the case, you can check the failure cause through [on('fail')<sup>7+</sup>](#onfail7).
Only HTTP requests are supported. HTTPS requests are not supported.
## Constants
......@@ -69,86 +70,93 @@ The download server must support the HTTP HEAD method so that the size of the da
| SESSION_SUCCESSFUL<sup>7+</sup> | number | Yes| No| Successful download.|
## request.upload
## request.uploadFile<sup>9+</sup>
upload(config: UploadConfig): Promise&lt;UploadTask&gt;
uploadFile(context: BaseContext, config: UploadConfig): Promise&lt;UploadTask&gt;
Uploads files. This API uses a promise to return the result.
This API can be used only in the FA model.
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [request.uploadFile<sup>9+</sup>](#requestuploadfile9).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Upload
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | 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.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[UploadTask](#uploadtask)&gt; | Promise used to return the **UploadTask** object.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400002 | Bad file path. |
**Example**
```js
let uploadTask;
let uploadConfig = {
url: 'https://patch',
url: 'http://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) => {
request.uploadFile(globalThis.abilityContext, uploadConfig).then((data) => {
uploadTask = data;
}).catch((err) => {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
})
});
```
## request.upload
## request.uploadFile<sup>9+</sup>
upload(config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void
uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void
Uploads files. This API uses an asynchronous callback to return the result.
This API can be used only in the FA model.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.uploadFile<sup>9+</sup>](#requestuploadfile9-1).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Upload
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | Yes| Callback used to return the **UploadTask** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | Yes| Callback used to return the **UploadTask** object.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400002 | Bad file path. |
**Example**
```js
let uploadTask;
let uploadConfig = {
url: 'https://patch',
url: 'http://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) => {
request.uploadFile(globalThis.abilityContext, uploadConfig, (err, data) => {
if (err) {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
return;
......@@ -156,15 +164,18 @@ This API can be used only in the FA model.
uploadTask = data;
});
```
## request.upload<sup>9+</sup>
upload(context: BaseContext, config: UploadConfig): Promise&lt;UploadTask&gt;
## request.upload<sup>(deprecated)</sup>
upload(config: UploadConfig): Promise&lt;UploadTask&gt;
Uploads files. This API uses a promise to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.uploadFile<sup>9+</sup>](#requestuploadfile9).
**Model restriction**: This API can be used only in the FA model.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.uploadFile<sup>9+</sup>](#requestuploadfile9).
**Required permissions**: ohos.permission.INTERNET
......@@ -172,46 +183,46 @@ Uploads files. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | BaseContext | Yes| Application-based context.|
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[UploadTask](#uploadtask)&gt; | Promise used to return the **UploadTask** object.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[UploadTask](#uploadtask)&gt; | Promise used to return the **UploadTask** object.|
**Example**
```js
let uploadTask;
let uploadConfig = {
url: 'https://patch',
url: 'http://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) => {
request.upload(uploadConfig).then((data) => {
uploadTask = data;
}).catch((err) => {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
});
})
```
## request.upload<sup>9+</sup>
## request.upload<sup>(deprecated)</sup>
upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void
upload(config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void
Uploads files. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.uploadFile<sup>9+</sup>](#requestuploadfile9-1).
**Model restriction**: This API can be used only in the FA model.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.uploadFile<sup>9+</sup>](#requestuploadfile9-1).
**Required permissions**: ohos.permission.INTERNET
......@@ -219,24 +230,23 @@ Uploads files. This API uses an asynchronous callback to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | BaseContext | Yes| Application-based context.|
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | Yes| Callback used to return the **UploadTask** object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | Yes| Callback used to return the **UploadTask** object.|
**Example**
```js
let uploadTask;
let uploadConfig = {
url: 'https://patch',
url: 'http://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) => {
request.upload(uploadConfig, (err, data) => {
if (err) {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
return;
......@@ -245,13 +255,16 @@ Uploads files. This API uses an asynchronous callback to return the result.
});
```
## request.upload<sup>(deprecated)</sup>
## request.uploadFile<sup>9+</sup>
uploadFile(context: BaseContext, config: UploadConfig): Promise&lt;UploadTask&gt;
upload(context: BaseContext, config: UploadConfig): Promise&lt;UploadTask&gt;
Uploads files. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 9 and is deprecated since API version 9. You are advised to use [request.uploadFile<sup>9+</sup>](#requestuploadfile9).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Upload
......@@ -259,36 +272,29 @@ Uploads files. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | BaseContext | Yes| Application-based context.|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | 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.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400002 | Bad file path. |
| Promise&lt;[UploadTask](#uploadtask)&gt; | Promise used to return the **UploadTask** object.|
**Example**
```js
let uploadTask;
let uploadConfig = {
url: 'https://patch',
url: 'http://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.uploadFile(globalThis.abilityContext, uploadConfig).then((data) => {
request.upload(globalThis.abilityContext, uploadConfig).then((data) => {
uploadTask = data;
}).catch((err) => {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
......@@ -296,12 +302,16 @@ For details about the error codes, see [Upload and Download Error Codes](../erro
```
## request.uploadFile<sup>9+</sup>
## request.upload<sup>(deprecated)</sup>
uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void
upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void
Uploads files. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.uploadFile<sup>9+</sup>](#requestuploadfile9-1).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Upload
......@@ -309,30 +319,23 @@ Uploads files. This API uses an asynchronous callback to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | BaseContext | Yes| Application-based context.|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | Yes| Callback used to return the **UploadTask** object.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400002 | Bad file path. |
**Example**
```js
let uploadTask;
let uploadConfig = {
url: 'https://patch',
url: 'http://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.uploadFile(globalThis.abilityContext, uploadConfig, (err, data) => {
request.upload(globalThis.abilityContext, uploadConfig, (err, data) => {
if (err) {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
return;
......@@ -341,10 +344,10 @@ For details about the error codes, see [Upload and Download Error Codes](../erro
});
```
## UploadTask
Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object.
Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object through [request.uploadFile<sup>9+</sup>](#requestuploadfile9) in promise mode or [request.uploadFile<sup>9+</sup>](#requestuploadfile9-1) in callback mode.
### on('progress')
......@@ -359,10 +362,10 @@ Subscribes to an upload event. This API uses an asynchronous callback to return
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
Parameters of the callback function
......@@ -372,9 +375,8 @@ Subscribes to an upload event. This API uses an asynchronous callback to return
| totalSize | number | Yes| Total size of the files to upload, in KB.|
**Example**
```js
let uploadTask;
uploadTask.on('progress', function callback(uploadedSize, totalSize) {
console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize);
}
......@@ -394,10 +396,10 @@ Subscribes to an upload event. This API uses an asynchronous callback to return
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
Parameters of the callback function
......@@ -406,9 +408,8 @@ Subscribes to an upload event. This API uses an asynchronous callback to return
| header | object | Yes| HTTP Response Header.|
**Example**
```js
let uploadTask;
uploadTask.on('headerReceive', function callback(headers){
console.info("upOnHeader headers:" + JSON.stringify(headers));
}
......@@ -428,10 +429,10 @@ Subscribes to an upload event. This API uses an asynchronous callback to return
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.|
| callback | Callback&lt;Array&lt;TaskState&gt;&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.|
| callback | Callback&lt;Array&lt;TaskState&gt;&gt; | Yes| Callback used to return the result.|
Parameters of the callback function
......@@ -440,9 +441,8 @@ Subscribes to an upload event. This API uses an asynchronous callback to return
| taskstates | Array&lt;[TaskState](#taskstate9)&gt; | Yes| Upload result.|
**Example**
```js
let uploadTask;
uploadTask.on('complete', function callback(taskStates) {
for (let i = 0; i < taskStates.length; i++ ) {
console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i]));
......@@ -471,10 +471,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
Parameters of the callback function
......@@ -484,9 +484,8 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret
| totalSize | number | Yes| Total size of the files to upload, in KB.|
**Example**
```js
let uploadTask;
uploadTask.off('progress', function callback(uploadedSize, totalSize) {
console.info('uploadedSize: ' + uploadedSize, 'totalSize: ' + totalSize);
}
......@@ -506,10 +505,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
Parameters of the callback function
......@@ -518,9 +517,8 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret
| header | object | Yes| HTTP Response Header.|
**Example**
```js
let uploadTask;
uploadTask.off('headerReceive', function callback(headers) {
console.info("upOnHeader headers:" + JSON.stringify(headers));
}
......@@ -539,10 +537,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.|
| callback | Callback&lt;Array&lt;TaskState&gt;&gt; | No| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.|
| callback | Callback&lt;Array&lt;TaskState&gt;&gt; | No| Callback used to return the result.|
Parameters of the callback function
......@@ -551,9 +549,8 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret
| taskstates | Array&lt;[TaskState](#taskstate9)&gt; | Yes| Upload result.|
**Example**
```js
let uploadTask;
uploadTask.off('complete', function callback(taskStates) {
for (let i = 0; i < taskStates.length; i++ ) {
console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i]));
......@@ -569,16 +566,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret
);
```
### delete<sup>9+</sup>
delete(): Promise&lt;boolean&gt;
### remove
remove(): Promise&lt;boolean&gt;
Removes this upload task. This API uses a promise to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9).
Deletes this upload task. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET
......@@ -586,15 +577,14 @@ Removes this upload task. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. It returns **true** if the operation is successful and returns **false** otherwise.|
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result. It returns **true** if the operation is successful and returns **false** otherwise.|
**Example**
```js
let uploadTask;
uploadTask.remove().then((result) => {
uploadTask.delete().then((result) => {
if (result) {
console.info('Upload task removed successfully. ');
} else {
......@@ -606,31 +596,26 @@ Removes this upload task. This API uses a promise to return the result.
```
### remove
### delete<sup>9+</sup>
remove(callback: AsyncCallback&lt;boolean&gt;): void
delete(callback: AsyncCallback&lt;boolean&gt;): void
Removes this upload task. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9-1).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Upload
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
**Example**
```js
let uploadTask;
uploadTask.remove((err, result) => {
uploadTask.delete((err, result) => {
if (err) {
console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err));
return;
......@@ -644,11 +629,15 @@ Removes this upload task. This API uses an asynchronous callback to return the r
```
### delete<sup>9+</sup>
### remove<sup>(deprecated)</sup>
delete(): Promise&lt;boolean&gt;
remove(): Promise&lt;boolean&gt;
Deletes 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.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9).
**Required permissions**: ohos.permission.INTERNET
......@@ -657,14 +646,13 @@ Deletes this upload task. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task deletion result. It returns **true** if the operation is successful and returns **false** otherwise.|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result. It returns **true** if the operation is successful and returns **false** otherwise.|
**Example**
```js
let uploadTask;
uploadTask.delete().then((result) => {
uploadTask.remove().then((result) => {
if (result) {
console.info('Upload task removed successfully. ');
} else {
......@@ -676,11 +664,15 @@ Deletes this upload task. This API uses a promise to return the result.
```
### delete<sup>9+</sup>
### remove<sup>(deprecated)</sup>
delete(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.
Deletes this upload task. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9-1).
**Required permissions**: ohos.permission.INTERNET
......@@ -689,14 +681,13 @@ Deletes this upload task. This API uses an asynchronous callback to return the r
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
**Example**
```js
let uploadTask;
uploadTask.delete((err, result) => {
uploadTask.remove((err, result) => {
if (err) {
console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err));
return;
......@@ -709,7 +700,6 @@ Deletes this upload task. This API uses an asynchronous callback to return the r
});
```
## UploadConfig
**Required permissions**: ohos.permission.INTERNET
......@@ -746,7 +736,7 @@ Deletes this upload task. This API uses an asynchronous callback to return the r
| -------- | -------- | -------- | -------- |
| filename | string | Yes| File name in the header when **multipart** is used.|
| name | string | Yes| 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 | Yes| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.|
......@@ -761,40 +751,43 @@ Deletes this upload task. This API uses an asynchronous callback to return the r
| name | string | Yes| Name of a form element.|
| value | string | Yes| Value of a form element.|
## request.downloadFile<sup>9+</sup>
## request.download
download(config: DownloadConfig): Promise&lt;DownloadTask&gt;
downloadFile(context: BaseContext, config: DownloadConfig): Promise&lt;DownloadTask&gt;
Downloads files. This API uses a promise to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.downloadFile<sup>9+</sup>](#requestdownloadfile9).
This API can be used only in the FA model.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | 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.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[DownloadTask](#downloadtask)&gt; | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400001 | File operation error. |
| 13400002 | Bad file path. |
| 13400003 | Task manager service error. |
**Example**
```js
let downloadTask;
request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => {
request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => {
downloadTask = data;
}).catch((err) => {
console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
......@@ -802,34 +795,38 @@ This API can be used only in the FA model.
```
## request.download
## request.downloadFile<sup>9+</sup>
download(config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void
downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void;
Downloads files. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.downloadFile<sup>9+</sup>](#requestdownloadfile9-1).
This API can be used only in the FA model.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | Yes| Callback used to return the result.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400001 | File operation error. |
| 13400002 | Bad file path. |
| 13400003 | Task manager service error. |
**Example**
```js
let downloadTask;
request.download({ url: 'https://xxxx/xxxxx.hap',
request.downloadFile(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));
......@@ -839,15 +836,17 @@ This API can be used only in the FA model.
});
```
## request.download<sup>9+</sup>
## request.download<sup>(deprecated)</sup>
download(context: BaseContext, config: DownloadConfig): Promise&lt;DownloadTask&gt;
download(config: DownloadConfig): Promise&lt;DownloadTask&gt;
Downloads files. This API uses a promise to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.downloadFile<sup>9+</sup>](#requestdownloadfile9).
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.downloadFile<sup>9+</sup>](#requestdownloadfile9).
**Model restriction**: This API can be used only in the FA model.
**Required permissions**: ohos.permission.INTERNET
......@@ -855,22 +854,21 @@ Downloads files. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | BaseContext | Yes| Application-based context.|
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[DownloadTask](#downloadtask)&gt; | Promise used to return the result.|
| 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) => {
request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => {
downloadTask = data;
}).catch((err) => {
console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
......@@ -878,15 +876,17 @@ Downloads files. This API uses a promise to return the result.
```
## request.download<sup>9+</sup>
## request.download<sup>(deprecated)</sup>
download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void;
download(config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void
Downloads files. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.downloadFile<sup>9+</sup>](#requestdownloadfile9-1).
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.downloadFile<sup>9+</sup>](#requestdownloadfile9-1).
**Model restriction**: This API can be used only in the FA model.
**Required permissions**: ohos.permission.INTERNET
......@@ -894,17 +894,16 @@ Downloads files. This API uses an asynchronous callback to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | BaseContext | Yes| Application-based context.|
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | Yes| Callback used to return the result.|
**Example**
```js
let downloadTask;
request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap',
request.download({ url: 'https://xxxx/xxxxx.hap',
filePath: 'xxx/xxxxx.hap'}, (err, data) => {
if (err) {
console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
......@@ -914,13 +913,16 @@ Downloads files. This API uses an asynchronous callback to return the result.
});
```
## request.download<sup>(deprecated)</sup>
## request.downloadFile<sup>9+</sup>
downloadFile(context: BaseContext, config: DownloadConfig): Promise&lt;DownloadTask&gt;
download(context: BaseContext, config: DownloadConfig): Promise&lt;DownloadTask&gt;
Downloads files. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 9 and is deprecated since API version 9. You are advised to use [request.downloadFile<sup>9+</sup>](#requestdownloadfile9).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
......@@ -928,30 +930,21 @@ Downloads files. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | BaseContext | Yes| Application-based context.|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | 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.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400001 | File operation error. |
| 13400002 | Bad file path. |
| 13400003 | Task manager service error. |
| Promise&lt;[DownloadTask](#downloadtask)&gt; | Promise used to return the result.|
**Example**
```js
let downloadTask;
request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => {
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));
......@@ -959,12 +952,16 @@ For details about the error codes, see [Upload and Download Error Codes](../erro
```
## request.downloadFile<sup>9+</sup>
## request.download<sup>(deprecated)</sup>
downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void;
download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void;
Downloads files. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.downloadFile<sup>9+</sup>](#requestdownloadfile9-1).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
......@@ -972,25 +969,16 @@ Downloads files. This API uses an asynchronous callback to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | BaseContext | Yes| Application-based context.|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | Yes| Callback used to return the result.|
**Error codes**
For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md).
| ID| Error Message|
| -------- | -------- |
| 13400001 | File operation error. |
| 13400002 | Bad file path. |
| 13400003 | Task manager service error. |
**Example**
```js
let downloadTask;
request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap',
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));
......@@ -1003,7 +991,7 @@ For details about the error codes, see [Upload and Download Error Codes](../erro
## DownloadTask
Implements file downloads.
Implements file downloads. Before using any APIs of this class, you must obtain a **DownloadTask** object through [request.downloadFile<sup>9+</sup>](#requestdownloadfile9) in promise mode or [request.downloadFile<sup>9+</sup>](#requestdownloadfile9-1) in callback mode.
### on('progress')
......@@ -1018,10 +1006,10 @@ Subscribes to a download event. This API uses an asynchronous callback to return
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
Parameters of the callback function
......@@ -1031,9 +1019,8 @@ Subscribes to a download event. This API uses an asynchronous callback to return
| totalSize | number | Yes| Total size of the files to download, in KB.|
**Example**
```js
let downloadTask;
downloadTask.on('progress', function download_callback(receivedSize, totalSize) {
console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize);
}
......@@ -1053,10 +1040,10 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
Parameters of the callback function
......@@ -1066,7 +1053,7 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re
| totalSize | number | Yes| Total size of the files to download.|
**Example**
```js
downloadTask .off('progress', function download_callback(receivedSize, totalSize) {
console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize);
......@@ -1087,15 +1074,14 @@ Subscribes to a download event. This API uses an asynchronous callback to return
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
**Example**
```js
let downloadTask;
downloadTask.on('complete', function callback() {
console.info('Download task completed.');
}
......@@ -1115,15 +1101,14 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
**Example**
```js
let downloadTask;
downloadTask.off('complete', function callback() {
console.info('Download task completed.');
}
......@@ -1143,10 +1128,10 @@ Subscribes to the download task failure event. This API uses an asynchronous cal
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
Parameters of the callback function
......@@ -1155,9 +1140,8 @@ Subscribes to the download task failure event. This API uses an asynchronous cal
| err | number | Yes| Error code of the download failure. For details about the error codes, see [ERROR_*](#constants).|
**Example**
```js
let downloadTask;
downloadTask.on('fail', function callBack(err) {
console.info('Download task failed. Cause:' + err);
}
......@@ -1177,10 +1161,10 @@ Unsubscribes from the download task failure event. This API uses an asynchronous
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| 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.|
Parameters of the callback function
......@@ -1189,41 +1173,34 @@ Unsubscribes from the download task failure event. This API uses an asynchronous
| err | number | Yes| Error code of the download failure. For details about the error codes, see [ERROR_*](#constants).|
**Example**
```js
let downloadTask;
downloadTask.off('fail', function callBack(err) {
console.info('Download task failed. Cause:' + err);
}
);
```
### delete<sup>9+</sup>
### remove
remove(): Promise&lt;boolean&gt;
delete(): Promise&lt;boolean&gt;
Removes this download task. This API uses a promise to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9-2).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result.|
**Example**
```js
let downloadTask;
downloadTask.remove().then((result) => {
downloadTask.delete().then((result) => {
if (result) {
console.info('Download task removed.');
} else {
......@@ -1235,31 +1212,26 @@ Removes this download task. This API uses a promise to return the result.
```
### remove
### delete<sup>9+</sup>
remove(callback: AsyncCallback&lt;boolean&gt;): void
delete(callback: AsyncCallback&lt;boolean&gt;): void
Removes this download task. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9-3).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the task removal result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the task removal result.|
**Example**
```js
let downloadTask;
downloadTask.remove((err, result)=>{
downloadTask.delete((err, result)=>{
if(err) {
console.error('Failed to remove the download task.');
return;
......@@ -1273,31 +1245,26 @@ Removes this download task. This API uses an asynchronous callback to return the
```
### query<sup>7+</sup>
### getTaskInfo<sup>9+</sup>
query(): Promise&lt;DownloadInfo&gt;
getTaskInfo(): Promise&lt;DownloadInfo&gt;
Queries this download task. This API uses a promise to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [getTaskInfo<sup>9+</sup>](#gettaskinfo9).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[DownloadInfo](#downloadinfo7)&gt; | Promise used to return the download task information.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[DownloadInfo](#downloadinfo7)&gt; | Promise used to return the download task information.|
**Example**
```js
let downloadTask;
downloadTask.query().then((downloadInfo) => {
downloadTask.getTaskInfo().then((downloadInfo) => {
console.info('Download task queried. Data:' + JSON.stringify(downloadInfo))
}) .catch((err) => {
console.error('Failed to query the download task. Cause:' + err)
......@@ -1305,31 +1272,26 @@ Queries this download task. This API uses a promise to return the result.
```
### query<sup>7+</sup>
### getTaskInfo<sup>9+</sup>
query(callback: AsyncCallback&lt;DownloadInfo&gt;): void
getTaskInfo(callback: AsyncCallback&lt;DownloadInfo&gt;): void
Queries this download task. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [getTaskInfo<sup>9+</sup>](#gettaskinfo9-1).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[DownloadInfo](#downloadinfo7)&gt; | Yes| Callback used to return the download task information.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[DownloadInfo](#downloadinfo7)&gt; | Yes| Callback used to return the download task information.|
**Example**
```js
let downloadTask;
downloadTask.query((err, downloadInfo)=>{
downloadTask.getTaskInfo((err, downloadInfo)=>{
if(err) {
console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err));
} else {
......@@ -1339,15 +1301,11 @@ Queries this download task. This API uses an asynchronous callback to return the
```
### queryMimeType<sup>7+</sup>
queryMimeType(): Promise&lt;string&gt;
### getTaskMimeType<sup>9+</sup>
Queries the **MimeType** of this download task. This API uses a promise to return the result.
getTaskMimeType(): Promise&lt;string&gt;
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [getTaskMimeType<sup>9+</sup>](#gettaskmimetype9).
Obtains the **MimeType** of this download task. This API uses a promise to return the result.
**Required permissions**: ohos.permission.INTERNET
......@@ -1355,15 +1313,14 @@ Queries the **MimeType** of this download task. This API uses a promise to retur
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;string&gt; | Promise used to return the **MimeType** of the download task.|
| Type| Description|
| -------- | -------- |
| Promise&lt;string&gt; | Promise used to return the **MimeType** of the download task.|
**Example**
```js
let downloadTask;
downloadTask.queryMimeType().then((data) => {
downloadTask.getTaskMimeType().then((data) => {
console.info('Download task queried. Data:' + JSON.stringify(data));
}).catch((err) => {
console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err))
......@@ -1371,15 +1328,11 @@ Queries the **MimeType** of this download task. This API uses a promise to retur
```
### queryMimeType<sup>7+</sup>
queryMimeType(callback: AsyncCallback&lt;string&gt;): void;
### getTaskMimeType<sup>9+</sup>
Queries the **MimeType** of this download task. This API uses an asynchronous callback to return the result.
getTaskMimeType(callback: AsyncCallback&lt;string&gt;): void;
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [getTaskMimeType<sup>9+</sup>](#gettaskmimetype9-1).
Obtains the **MimeType** of this download task. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.INTERNET
......@@ -1387,15 +1340,14 @@ Queries the **MimeType** of this download task. This API uses an asynchronous ca
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the **MimeType** of the download task.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the **MimeType** of the download task.|
**Example**
```js
let downloadTask;
downloadTask.queryMimeType((err, data)=>{
downloadTask.getTaskMimeType((err, data)=>{
if(err) {
console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err));
} else {
......@@ -1405,31 +1357,26 @@ Queries the **MimeType** of this download task. This API uses an asynchronous ca
```
### pause<sup>7+</sup>
### suspend<sup>9+</sup>
pause(): Promise&lt;void&gt;
suspend(): Promise&lt;boolean&gt;
Pauses this download task. This API uses a promise to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [suspend<sup>9+</sup>](#suspend9).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the download task pause result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the download task pause result.|
**Example**
```js
let downloadTask;
downloadTask.pause().then((result) => {
downloadTask.suspend().then((result) => {
if (result) {
console.info('Download task paused. ');
} else {
......@@ -1441,13 +1388,9 @@ Pauses this download task. This API uses a promise to return the result.
```
### pause<sup>7+</sup>
pause(callback: AsyncCallback&lt;void&gt;): void
### suspend<sup>9+</sup>
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [suspend<sup>9+</sup>](#suspend9-1).
suspend(callback: AsyncCallback&lt;boolean&gt;): void
Pauses this download task. This API uses an asynchronous callback to return the result.
......@@ -1457,15 +1400,14 @@ Pauses this download task. This API uses an asynchronous callback to return the
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
**Example**
```js
let downloadTask;
downloadTask.pause((err, result)=>{
downloadTask.suspend((err, result)=>{
if(err) {
console.error('Failed to pause the download task. Cause:' + JSON.stringify(err));
return;
......@@ -1479,31 +1421,26 @@ Pauses this download task. This API uses an asynchronous callback to return the
```
### resume<sup>7+</sup>
### restore<sup>9+</sup>
resume(): Promise&lt;void&gt;
restore(): Promise&lt;boolean&gt;
Resumes this download task. This API uses a promise to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [restore<sup>9+</sup>](#restore9).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
**Example**
```js
let downloadTask;
downloadTask.resume().then((result) => {
downloadTask.restore().then((result) => {
if (result) {
console.info('Download task resumed.')
} else {
......@@ -1516,13 +1453,9 @@ Resumes this download task. This API uses a promise to return the result.
```
### resume<sup>7+</sup>
resume(callback: AsyncCallback&lt;void&gt;): void
### restore<sup>9+</sup>
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [restore<sup>9+</sup>](#restore9-1).
restore(callback: AsyncCallback&lt;boolean&gt;): void
Resumes this download task. This API uses an asynchronous callback to return the result.
......@@ -1532,15 +1465,14 @@ Resumes this download task. This API uses an asynchronous callback to return the
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
**Example**
```js
let downloadTask;
downloadTask.resume((err, result)=>{
downloadTask.restore((err, result)=>{
if (err) {
console.error('Failed to resume the download task. Cause:' + err);
return;
......@@ -1554,11 +1486,16 @@ Resumes this download task. This API uses an asynchronous callback to return the
```
### delete<sup>9+</sup>
delete(): Promise&lt;boolean&gt;
### remove<sup>(deprecated)</sup>
Deletes this download task. This API uses a promise to return the result.
remove(): Promise&lt;boolean&gt;
Removes this download task. This API uses a promise to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9-2).
**Required permissions**: ohos.permission.INTERNET
......@@ -1567,14 +1504,13 @@ Deletes this download task. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the task removal result.|
**Example**
```js
let downloadTask;
downloadTask.delete().then((result) => {
downloadTask.remove().then((result) => {
if (result) {
console.info('Download task removed.');
} else {
......@@ -1586,11 +1522,15 @@ Deletes this download task. This API uses a promise to return the result.
```
### delete<sup>9+</sup>
### remove<sup>(deprecated)</sup>
delete(callback: AsyncCallback&lt;boolean&gt;): void
remove(callback: AsyncCallback&lt;boolean&gt;): void
Deletes this download task. This API uses an asynchronous callback to return the result.
Removes this download task. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [delete<sup>9+</sup>](#delete9-3).
**Required permissions**: ohos.permission.INTERNET
......@@ -1599,14 +1539,13 @@ Deletes this download task. This API uses an asynchronous callback to return the
**Parameters**
| 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 task removal result.|
**Example**
```js
let downloadTask;
downloadTask.delete((err, result)=>{
downloadTask.remove((err, result)=>{
if(err) {
console.error('Failed to remove the download task.');
return;
......@@ -1620,12 +1559,16 @@ Deletes this download task. This API uses an asynchronous callback to return the
```
### getTaskInfo<sup>9+</sup>
### query<sup>(deprecated)</sup>
getTaskInfo(): Promise&lt;DownloadInfo&gt;
query(): Promise&lt;DownloadInfo&gt;
Queries this download task. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskInfo<sup>9+</sup>](#gettaskinfo9).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
......@@ -1639,8 +1582,7 @@ Queries this download task. This API uses a promise to return the result.
**Example**
```js
let downloadTask;
downloadTask.getTaskInfo().then((downloadInfo) => {
downloadTask.query().then((downloadInfo) => {
console.info('Download task queried. Data:' + JSON.stringify(downloadInfo))
}) .catch((err) => {
console.error('Failed to query the download task. Cause:' + err)
......@@ -1648,12 +1590,16 @@ Queries this download task. This API uses a promise to return the result.
```
### getTaskInfo<sup>9+</sup>
### query<sup>(deprecated)</sup>
query(callback: AsyncCallback&lt;DownloadInfo&gt;): void
Queries this download task. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskInfo<sup>9+</sup>](#gettaskinfo9-1).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
......@@ -1661,14 +1607,13 @@ Queries this download task. This API uses an asynchronous callback to return the
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[DownloadInfo](#downloadinfo7)&gt; | Yes| Callback used to return the download task information.|
**Example**
```js
let downloadTask;
downloadTask.getTaskInfo((err, downloadInfo)=>{
downloadTask.query((err, downloadInfo)=>{
if(err) {
console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err));
} else {
......@@ -1678,11 +1623,15 @@ Queries this download task. This API uses an asynchronous callback to return the
```
### getTaskMimeType<sup>9+</sup>
### queryMimeType<sup>(deprecated)</sup>
getTaskMimeType(): Promise&lt;string&gt;
queryMimeType(): Promise&lt;string&gt;
Obtains the **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.
> **NOTE**
>
> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskMimeType<sup>9+</sup>](#gettaskmimetype9).
**Required permissions**: ohos.permission.INTERNET
......@@ -1691,14 +1640,13 @@ Obtains the **MimeType** of this download task. This API uses a promise to retur
**Return value**
| Type| Description|
| -------- | -------- |
| -------- | -------- |
| Promise&lt;string&gt; | Promise used to return the **MimeType** of the download task.|
**Example**
```js
let downloadTask;
downloadTask.getTaskMimeType().then((data) => {
downloadTask.queryMimeType().then((data) => {
console.info('Download task queried. Data:' + JSON.stringify(data));
}).catch((err) => {
console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err))
......@@ -1706,11 +1654,15 @@ Obtains the **MimeType** of this download task. This API uses a promise to retur
```
### getTaskMimeType<sup>9+</sup>
### queryMimeType<sup>(deprecated)</sup>
getTaskMimeType(callback: AsyncCallback&lt;string&gt;): void;
queryMimeType(callback: AsyncCallback&lt;string&gt;): void;
Obtains the **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.
> **NOTE**
>
> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskMimeType<sup>9+</sup>](#gettaskmimetype9-1).
**Required permissions**: ohos.permission.INTERNET
......@@ -1719,14 +1671,13 @@ Obtains the **MimeType** of this download task. This API uses an asynchronous ca
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;string&gt; | Yes| Callback used to return the **MimeType** of the download task.|
**Example**
```js
let downloadTask;
downloadTask.getTaskMimeType((err, data)=>{
downloadTask.queryMimeType((err, data)=>{
if(err) {
console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err));
} else {
......@@ -1736,12 +1687,16 @@ Obtains the **MimeType** of this download task. This API uses an asynchronous ca
```
### suspend<sup>9+</sup>
### pause<sup>(deprecated)</sup>
suspend(): Promise&lt;boolean&gt;
pause(): Promise&lt;void&gt;
Pauses this download task. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [suspend<sup>9+</sup>](#suspend9).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
......@@ -1749,14 +1704,13 @@ Pauses this download task. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the download task pause result.|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the download task pause result.|
**Example**
```js
let downloadTask;
downloadTask.suspend().then((result) => {
downloadTask.pause().then((result) => {
if (result) {
console.info('Download task paused. ');
} else {
......@@ -1768,9 +1722,13 @@ Pauses this download task. This API uses a promise to return the result.
```
### suspend<sup>9+</sup>
### pause<sup>(deprecated)</sup>
suspend(callback: AsyncCallback&lt;boolean&gt;): void
pause(callback: AsyncCallback&lt;void&gt;): void
> **NOTE**
>
> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [suspend<sup>9+</sup>](#suspend9-1).
Pauses this download task. This API uses an asynchronous callback to return the result.
......@@ -1781,14 +1739,13 @@ Pauses this download task. This API uses an asynchronous callback to return the
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```js
let downloadTask;
downloadTask.suspend((err, result)=>{
downloadTask.pause((err, result)=>{
if(err) {
console.error('Failed to pause the download task. Cause:' + JSON.stringify(err));
return;
......@@ -1802,12 +1759,16 @@ Pauses this download task. This API uses an asynchronous callback to return the
```
### restore<sup>9+</sup>
### resume<sup>(deprecated)</sup>
restore(): Promise&lt;boolean&gt;
resume(): Promise&lt;void&gt;
Resumes this download task. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [restore<sup>9+</sup>](#restore9).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
......@@ -1815,14 +1776,13 @@ Resumes this download task. This API uses a promise to return the result.
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result.|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```js
let downloadTask;
downloadTask.restore().then((result) => {
downloadTask.resume().then((result) => {
if (result) {
console.info('Download task resumed.')
} else {
......@@ -1835,9 +1795,13 @@ Resumes this download task. This API uses a promise to return the result.
```
### restore<sup>9+</sup>
### resume<sup>(deprecated)</sup>
restore(callback: AsyncCallback&lt;boolean&gt;): void
resume(callback: AsyncCallback&lt;void&gt;): void
> **NOTE**
>
> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [restore<sup>9+</sup>](#restore9-1).
Resumes this download task. This API uses an asynchronous callback to return the result.
......@@ -1848,14 +1812,13 @@ Resumes this download task. This API uses an asynchronous callback to return the
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the result.|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```js
let downloadTask;
downloadTask.restore((err, result)=>{
downloadTask.resume((err, result)=>{
if (err) {
console.error('Failed to resume the download task. Cause:' + err);
return;
......
# Settings
# @ohos.settings
The **settings** module provides APIs for setting data items.
......@@ -24,8 +24,8 @@ Provides data items for setting the time and date formats.
| ------------------- | ------ | ---- | ---- | ------------------------------------------------------------ |
| DATE_FORMAT | string | Yes | Yes | Date format.<br>The value can be **mm/dd/yyyy**, **dd/mm/yyyy**, or **yyyy/mm/dd**, where **mm** indicates the month, **dd** indicates the day, and **yyyy** indicates the year.|
| TIME_FORMAT | string | Yes | Yes | Time format.<br>**12**: 12-hour format.<br>**24**: 24-hour format.|
| AUTO_GAIN_TIME | string | Yes | Yes | Whether the date, time, and time zone are automatically obtained from the Network Identity and Time Zone (NITZ).<br>The value **true** means that the date, time, and time zone are automatically obtained from NITZ; and **false** means the opposite.|
| AUTO_GAIN_TIME_ZONE | string | Yes | Yes | Whether the time zone is automatically obtained from NITZ.<br>The value **true** means that the time zone is automatically obtained from NITZ; and **false** means the opposite.|
| AUTO_GAIN_TIME | string | Yes | Yes | Whether the date, time, and time zone are automatically obtained from the Network Identity and Time Zone (NITZ).<br>The value **true** means that the date, time, and time zone are automatically obtained from NITZ; and **false** means the opposite. |
| AUTO_GAIN_TIME_ZONE | string | Yes | Yes | Whether the time zone is automatically obtained from NITZ.<br>The value **true** means that the time zone is automatically obtained from NITZ; and **false** means the opposite. |
## display
......@@ -39,7 +39,7 @@ Provides data items for setting the display effects.
| ----------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ |
| FONT_SCALE | string | Yes | Yes | Scale factor of the font. The value is a floating point number. |
| SCREEN_BRIGHTNESS_STATUS | string | Yes | Yes | Screen brightness. The value ranges from 0 to 255. |
| AUTO_SCREEN_BRIGHTNESS | string | Yes | Yes | Whether automatic screen brightness adjustment is enabled.<br>**AUTO_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is enabled.<br>**MANUAL_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is disabled.|
| AUTO_SCREEN_BRIGHTNESS | string | Yes | Yes | Whether automatic screen brightness adjustment is enabled.<br>**AUTO_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is enabled.<br>**MANUAL_SCREEN_BRIGHTNESS_MODE**: Automatic screen brightness adjustment is disabled. |
| AUTO_SCREEN_BRIGHTNESS_MODE | number | Yes | Yes | Value of **AUTO_SCREEN_BRIGHTNESS** when automatic screen brightness adjustment is enabled. |
| MANUAL_SCREEN_BRIGHTNESS_MODE | number | Yes | Yes | Value of **AUTO_SCREEN_BRIGHTNESS** when automatic screen brightness adjustment is disabled. |
| SCREEN_OFF_TIMEOUT | string | Yes | Yes | Waiting time for the device to enter the sleep state when not in use (unit: ms). |
......@@ -47,7 +47,7 @@ Provides data items for setting the display effects.
| ANIMATOR_DURATION_SCALE | string | Yes | Yes | Scale factor for the animation duration. This affects the start delay and duration of all such animations.<br>If the value is **0**, the animation ends immediately. The default value is **1**.|
| TRANSITION_ANIMATION_SCALE | string | Yes | Yes | Scale factor for transition animations.<br>The value **0** indicates that the transition animations are disabled. |
| WINDOW_ANIMATION_SCALE | string | Yes | Yes | Scale factor for normal window animations.<br>The value **0** indicates that window animations are disabled. |
| DISPLAY_INVERSION_STATUS | string | Yes | Yes | Whether display color inversion is enabled.<br>**1**: Display color inversion is enabled.<br>**0**: Display color inversion is disabled.|
| DISPLAY_INVERSION_STATUS | string | Yes | Yes | Whether display color inversion is enabled.<br>**1**: Display color inversion is enabled.<br>**0**: Display color inversion is disabled. |
## general
......@@ -248,7 +248,7 @@ Obtains the value of a data item in the database. This API uses an asynchronous
| Name | Type | Mandatory| Description |
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br> - Existing data items in the database<br>- Custom data items|
| callback | AsyncCallback\<object> | Yes | Callback used to return the value of the data item. |
......@@ -280,7 +280,7 @@ Obtains the value of a data item in the database. This API uses a promise to ret
| Name | Type | Mandatory| Description |
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br> - Existing data items in the database<br>- Custom data items|
**Return value**
......@@ -315,7 +315,7 @@ Sets the value for a data item. This API uses an asynchronous callback to return
| Name | Type | Mandatory| Description |
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br>- Existing data items in the database<br>- Custom data items|
| value | object | Yes | Value of the data item. The value range varies by service. |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. Returns **true** if the operation is successful; returns **false** otherwise. |
......@@ -347,7 +347,7 @@ Sets the value for a data item. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br>- Existing data items in the database<br>- Custom data items|
| value | object | Yes | Value of the data item. The value range varies by service. |
......@@ -512,9 +512,9 @@ Obtains the value of a data item. Unlike **getValue**, this API returns the resu
| Name | Type | Mandatory| Description |
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br>- Existing data items in the database<br>- Custom data items|
| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this attribute as needed.|
| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this parameter as needed. |
**Return value**
......@@ -541,7 +541,7 @@ Sets the value for a data item. Unlike **setValue**, this API returns the result
If the specified data item exists in the database, the **setValueSync** method updates the value of the data item. If the data item does not exist in the database, the **setValueSync** method inserts the data item into the database.
**Required permissions**: ohos.permission.MANAGE_SECUER_SETTINGS (available only to system applications)
**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS (available only to system applications)
**System capability**: SystemCapability.Applications.settings.Core
......@@ -549,7 +549,7 @@ If the specified data item exists in the database, the **setValueSync** method u
| Name | Type | Mandatory| Description |
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br>- Existing data items in the database<br>- Custom data items|
| value | string | Yes | Value of the data item. The value range varies by service. |
......
# Wallpaper
# @ohos.wallpaper
The **wallpaper** module is part of the theme framework and provides the system-level wallpaper management service in OpenHarmony. You can use the APIs of this module to show, set, and switch between wallpapers.
> **NOTE**
>
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
```js
import wallpaper from '@ohos.wallpaper';
```
## WallpaperType
Enumerates the wallpaper types.
......@@ -27,15 +26,25 @@ Enumerates the wallpaper types.
| WALLPAPER_LOCKSCREEN | 1 |Lock screen wallpaper.|
## wallpaper.getColors
## RgbaColor
getColors(wallpaperType: WallpaperType, callback: AsyncCallback&lt;Array&lt;RgbaColor&gt;&gt;): void
Defines the RGBA color space for the wallpaper.
Obtains the main color information of the wallpaper of the specified type. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.Wallpaper
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync<sup>9+</sup>](#wallpapergetcolorssync9) instead.
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| red | number | Yes| Yes| Red color. The value ranges from 0 to 255.|
| green | number | Yes| Yes| Green color. The value ranges from 0 to 255.|
| blue | number | Yes| Yes| Blue color. The value ranges from 0 to 255.|
| alpha | number | Yes| Yes| Alpha value. The value ranges from 0 to 255.|
## wallpaper.getColorsSync<sup>9+</sup>
getColorsSync(wallpaperType: WallpaperType): Array&lt;RgbaColor&gt;
Obtains the main color information of the wallpaper of the specified type.
**System capability**: SystemCapability.MiscServices.Wallpaper
......@@ -44,30 +53,24 @@ Obtains the main color information of the wallpaper of the specified type. This
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;Array&lt;[RgbaColor](#rgbacolor)&gt;&gt; | Yes| Callback used to return the main color information of the wallpaper.|
**Example**
**Return value**
```js
wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => {
if (error) {
console.error(`failed to getColors because: ` + JSON.stringify(error));
return;
}
console.log(`success to getColors.`);
});
```
| Type| Description|
| -------- | -------- |
| Array&lt;[RgbaColor](#rgbacolor)&gt; | Promise used to return the main color information of the wallpaper.|
**Example**
## wallpaper.getColors
```js
let colors = wallpaper.getColorsSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM);
```
getColors(wallpaperType: WallpaperType): Promise&lt;Array&lt;RgbaColor&gt;&gt;
## wallpaper.getIdSync<sup>9+</sup>
Obtains the main color information of the wallpaper of the specified type. This API uses a promise to return the result.
getIdSync(wallpaperType: WallpaperType): number
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync<sup>9+</sup>](#wallpapergetcolorssync9) instead.
Obtains the ID of the wallpaper of the specified type.
**System capability**: SystemCapability.MiscServices.Wallpaper
......@@ -81,24 +84,130 @@ Obtains the main color information of the wallpaper of the specified type. This
| Type| Description|
| -------- | -------- |
| Promise&lt;Array&lt;[RgbaColor](#rgbacolor)&gt;&gt; | Promise used to return the main color information of the wallpaper.|
| number | ID of the wallpaper. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.|
**Example**
```js
wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.log(`success to getColors.`);
}).catch((error) => {
console.error(`failed to getColors because: ` + JSON.stringify(error));
});
```
```js
let id = wallpaper.getIdSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM);
```
## wallpaper.getMinHeightSync<sup>9+</sup>
## wallpaper.getColorsSync<sup>9+</sup>
getMinHeightSync(): number
getColorsSync(wallpaperType: WallpaperType): Array&lt;RgbaColor&gt;
Obtains the minimum height of this wallpaper.
Obtains the main color information of the wallpaper of the specified type. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Return value**
| Type| Description|
| -------- | -------- |
| number | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.|
**Example**
```js
let minHeight = wallpaper.getMinHeightSync();
```
## wallpaper.getMinWidthSync<sup>9+</sup>
getMinWidthSync(): number
Obtains the minimum width of this wallpaper.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Return value**
| Type| Description|
| -------- | -------- |
| number | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.|
**Example**
```js
let minWidth = wallpaper.getMinWidthSync();
```
## wallpaper.isChangeAllowed<sup>9+</sup>
isChangeAllowed(): boolean
Checks whether to allow the application to change the wallpaper for the current user.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.|
**Example**
```js
let isChangeAllowed = wallpaper.isChangeAllowed();
```
## wallpaper.isUserChangeAllowed<sup>9+</sup>
isUserChangeAllowed(): boolean
Checks whether the user is allowed to set wallpapers.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.|
**Example**
```js
let isUserChangeAllowed = wallpaper.isUserChangeAllowed();
```
## wallpaper.restore<sup>9+</sup>
restore(wallpaperType: WallpaperType, callback: AsyncCallback&lt;void&gt;): void
Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_WALLPAPER
**System capability**: SystemCapability.MiscServices.Wallpaper
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.|
**Example**
```js
wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => {
if (error) {
console.error(`failed to restore because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to restore.`);
});
```
## wallpaper.restore<sup>9+</sup>
restore(wallpaperType: WallpaperType): Promise&lt;void&gt;
Resets the wallpaper of the specified type to the default wallpaper. This API uses a promise to return the result.
**Required permissions**: ohos.permission.SET_WALLPAPER
**System capability**: SystemCapability.MiscServices.Wallpaper
......@@ -112,24 +221,25 @@ Obtains the main color information of the wallpaper of the specified type. This
| Type| Description|
| -------- | -------- |
| Array&lt;[RgbaColor](#rgbacolor)&gt; | Promise used to return the main color information of the wallpaper.|
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```js
var colors = wallpaper.getColorsSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM);
```
```js
wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => {
console.log(`success to restore.`);
}).catch((error) => {
console.error(`failed to restore because: ${JSON.stringify(error)}`);
});
```
## wallpaper.getId
## wallpaper.setImage<sup>9+</sup>
getId(wallpaperType: WallpaperType, callback: AsyncCallback&lt;number&gt;): void
setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback&lt;void&gt;): void
Obtains the ID of the wallpaper of the specified type. This API uses an asynchronous callback to return the result.
Sets a specified source as the wallpaper of a specified type. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getIdSync<sup>9+</sup>](#wallpapergetidsync9) instead.
**Required permissions**: ohos.permission.SET_WALLPAPER
**System capability**: SystemCapability.MiscServices.Wallpaper
......@@ -137,31 +247,52 @@ Obtains the ID of the wallpaper of the specified type. This API uses an asynchro
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.|
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the wallpaper ID. If the wallpaper of the specified type is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.|
**Example**
```js
wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => {
if (error) {
console.error(`failed to getId because: ` + JSON.stringify(error));
return;
}
console.log(`success to getId: ` + JSON.stringify(data));
});
```
```js
//The source type is string.
let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg";
wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => {
if (error) {
console.error(`failed to setImage because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to setImage.`);
});
// The source type is image.PixelMap.
import image from '@ohos.multimedia.image';
let imageSource = image.createImageSource("file://" + wallpaperPath);
let opts = {
"desiredSize": {
"height": 3648,
"width": 2736
}
};
imageSource.createPixelMap(opts).then((pixelMap) => {
wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => {
if (error) {
console.error(`failed to setImage because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to setImage.`);
});
}).catch((error) => {
console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`);
});
```
## wallpaper.getId
## wallpaper.setImage<sup>9+</sup>
getId(wallpaperType: WallpaperType): Promise&lt;number&gt;
setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise&lt;void&gt;
Obtains the ID of the wallpaper of the specified type. This API uses a promise to return the result.
Sets a specified source as the wallpaper of a specified type. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getIdSync<sup>9+</sup>](#wallpapergetidsync9) instead.
**Required permissions**: ohos.permission.SET_WALLPAPER
**System capability**: SystemCapability.MiscServices.Wallpaper
......@@ -169,30 +300,53 @@ Obtains the ID of the wallpaper of the specified type. This API uses a promise t
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.|
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the wallpaper ID. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.|
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```js
wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.log(`success to getId: ` + JSON.stringify(data));
}).catch((error) => {
console.error(`failed to getId because: ` + JSON.stringify(error));
});
```
```js
//The source type is string.
let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg";
wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => {
console.log(`success to setImage.`);
}).catch((error) => {
console.error(`failed to setImage because: ${JSON.stringify(error)}`);
});
// The source type is image.PixelMap.
import image from '@ohos.multimedia.image';
let imageSource = image.createImageSource("file://" + wallpaperPath);
let opts = {
"desiredSize": {
"height": 3648,
"width": 2736
}
};
imageSource.createPixelMap(opts).then((pixelMap) => {
wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => {
console.log(`success to setImage.`);
}).catch((error) => {
console.error(`failed to setImage because: ${JSON.stringify(error)}`);
});
}).catch((error) => {
console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`);
});
```
## wallpaper.getFileSync<sup>9+</sup>
## wallpaper.getIdSync<sup>9+</sup>
getFileSync(wallpaperType: WallpaperType): number;
getIdSync(wallpaperType: WallpaperType): number
Obtains the wallpaper of the specified type.
Obtains the ID of the wallpaper of the specified type. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_WALLPAPER
**System capability**: SystemCapability.MiscServices.Wallpaper
......@@ -206,105 +360,109 @@ Obtains the ID of the wallpaper of the specified type. This API uses an asynchro
| Type| Description|
| -------- | -------- |
| number | ID of the wallpaper. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.|
| number | Promise used to return the result. If the operation is successful, the file descriptor ID to the wallpaper is returned. Otherwise, error information is returned.|
**Example**
```js
var id = wallpaper.getIdSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM);
```
```js
let file = wallpaper.getFileSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM);
```
## wallpaper.getMinHeight
## wallpaper.getImage<sup>9+</sup>
getMinHeight(callback: AsyncCallback&lt;number&gt;): void
getImage(wallpaperType: WallpaperType, callback: AsyncCallback&lt;image.PixelMap&gt;): void;
Obtains the minimum height of this wallpaper. This API uses an asynchronous callback to return the result.
Obtains the pixel map for the wallpaper of the specified type. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinHeightSync<sup>9+</sup>](#wallpapergetminheightsync9) instead.
**Required permissions**: ohos.permission.GET_WALLPAPER
**System capability**: SystemCapability.MiscServices.Wallpaper
**System API**: This is a system API.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.|
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes| Callback used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.|
**Example**
```js
wallpaper.getMinHeight((error, data) => {
if (error) {
console.error(`failed to getMinHeight because: ` + JSON.stringify(error));
return;
}
console.log(`success to getMinHeight: ` + JSON.stringify(data));
});
```
```js
wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (error, data) {
if (error) {
console.error(`failed to getImage because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to getImage: ${JSON.stringify(data)}`);
});
```
## wallpaper.getMinHeight
## wallpaper.getImage<sup>9+</sup>
getMinHeight(): Promise&lt;number&gt;
getImage(wallpaperType: WallpaperType): Promise&lt;image.PixelMap&gt;
Obtains the minimum height of this wallpaper. This API uses a promise to return the result.
Obtains the pixel map for the wallpaper of the specified type. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinHeightSync<sup>9+</sup>](#wallpapergetminheightsync9) instead.
**Required permissions**: ohos.permission.GET_WALLPAPER
**System capability**: SystemCapability.MiscServices.Wallpaper
**System API**: This is a system API.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.|
| Promise&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Promise used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.|
**Example**
```js
wallpaper.getMinHeight().then((data) => {
console.log(`success to getMinHeight: ` + JSON.stringify(data));
```js
wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.log(`success to getImage: ${JSON.stringify(data)}`);
}).catch((error) => {
console.error(`failed to getMinHeight because: ` + JSON.stringify(error));
});
```
console.error(`failed to getImage because: ${JSON.stringify(error)}`);
});
```
## wallpaper.getMinHeightSync<sup>9+</sup>
## wallpaper.on('colorChange')<sup>9+</sup>
getMinHeightSync(): number
on(type: 'colorChange', callback: (colors: Array&lt;RgbaColor&gt;, wallpaperType: WallpaperType) =&gt; void): void
Obtains the minimum height of this wallpaper. This API uses an asynchronous callback to return the result.
Subscribes to the wallpaper color change event.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Return value**
**Parameters**
| Type| Description|
| -------- | -------- |
| number | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value **'colorChange'** indicates subscribing to the wallpaper color change event.|
| callback | function | Yes| Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned.<br>- colors<br> Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).<br>- wallpaperType<br> Wallpaper type.|
**Example**
```js
var minHeight = wallpaper.getMinHeightSync();
```
## wallpaper.getMinWidth
```js
let listener = (colors, wallpaperType) => {
console.log(`wallpaper color changed.`);
};
wallpaper.on('colorChange', listener);
```
getMinWidth(callback: AsyncCallback&lt;number&gt;): void
## wallpaper.off('colorChange')<sup>9+</sup>
Obtains the minimum width of this wallpaper. This API uses an asynchronous callback to return the result.
off(type: 'colorChange', callback?: (colors: Array&lt;RgbaColor&gt;, wallpaperType: WallpaperType) =&gt; void): void
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinWidthSync<sup>9+</sup>](#wallpapergetminwidthsync9) instead.
Unsubscribes from the wallpaper color change event.
**System capability**: SystemCapability.MiscServices.Wallpaper
......@@ -312,80 +470,96 @@ Obtains the minimum width of this wallpaper. This API uses an asynchronous callb
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.|
| type | string | Yes| Type of the event to unsubscribe from. The value **'colorChange'** indicates unsubscribing from the wallpaper color change event.|
| callback | function | No| Callback for the wallpaper color change event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.<br>- colors<br> Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).<br>- wallpaperType<br> Wallpaper type.|
**Example**
```js
wallpaper.getMinWidth((error, data) => {
if (error) {
console.error(`failed to getMinWidth because: ` + JSON.stringify(error));
return;
}
console.log(`success to getMinWidth: ` + JSON.stringify(data));
});
```
```js
let listener = (colors, wallpaperType) => {
console.log(`wallpaper color changed.`);
};
wallpaper.on('colorChange', listener);
// Unsubscribe from the listener.
wallpaper.off('colorChange', listener);
// Unsubscribe from all subscriptions of the colorChange type.
wallpaper.off('colorChange');
```
## wallpaper.getMinWidth
## wallpaper.getColors<sup>(deprecated)</sup>
getMinWidth(): Promise&lt;number&gt;
getColors(wallpaperType: WallpaperType, callback: AsyncCallback&lt;Array&lt;RgbaColor&gt;&gt;): void
Obtains the minimum width of this wallpaper. This API uses a promise to return the result.
Obtains the main color information of the wallpaper of the specified type. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinWidthSync<sup>9+</sup>](#wallpapergetminwidthsync9) instead.
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync<sup>9+</sup>](#wallpapergetcolorssync9) instead.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Return value**
**Parameters**
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;Array&lt;[RgbaColor](#rgbacolor)&gt;&gt; | Yes| Callback used to return the main color information of the wallpaper.|
**Example**
```js
wallpaper.getMinWidth().then((data) => {
console.log(`success to getMinWidth: ` + JSON.stringify(data));
}).catch((error) => {
console.error(`failed to getMinWidth because: ` + JSON.stringify(error));
});
```
```js
wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => {
if (error) {
console.error(`failed to getColors because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to getColors: ${JSON.stringify(data)}`);
});
```
## wallpaper.getColors<sup>(deprecated)</sup>
## wallpaper.getMinWidthSync<sup>9+</sup>
getColors(wallpaperType: WallpaperType): Promise&lt;Array&lt;RgbaColor&gt;&gt;
getMinWidthSync(): number
Obtains the main color information of the wallpaper of the specified type. This API uses a promise to return the result.
Obtains the minimum width of this wallpaper. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync<sup>9+</sup>](#wallpapergetcolorssync9) instead.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.|
| Promise&lt;Array&lt;[RgbaColor](#rgbacolor)&gt;&gt; | Promise used to return the main color information of the wallpaper.|
**Example**
```js
var minWidth = wallpaper.getMinWidthSync();
```
```js
wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.log(`success to getColors: ${JSON.stringify(data)}`);
}).catch((error) => {
console.error(`failed to getColors because: ${JSON.stringify(error)}`);
});
```
## wallpaper.isChangePermitted
## wallpaper.getId<sup>(deprecated)</sup>
isChangePermitted(callback: AsyncCallback&lt;boolean&gt;): void
getId(wallpaperType: WallpaperType, callback: AsyncCallback&lt;number&gt;): void
Checks whether to allow the application to change the wallpaper for the current user. This API uses an asynchronous callback to return the result.
Obtains the ID of the wallpaper of the specified type. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isChangeAllowed<sup>9+</sup>](#wallpaperischangeallowed9) instead.
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getIdSync<sup>9+</sup>](#wallpapergetidsync9) instead.
**System capability**: SystemCapability.MiscServices.Wallpaper
......@@ -393,136 +567,152 @@ Checks whether to allow the application to change the wallpaper for the current
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.|
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the wallpaper ID. If the wallpaper of the specified type is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.|
**Example**
```js
wallpaper.isChangePermitted((error, data) => {
if (error) {
console.error(`failed to isChangePermitted because: ` + JSON.stringify(error));
return;
}
console.log(`success to isChangePermitted: ` + JSON.stringify(data));
});
```
```js
wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => {
if (error) {
console.error(`failed to getId because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to getId: ${JSON.stringify(data)}`);
});
```
## wallpaper.isChangePermitted
## wallpaper.getId<sup>(deprecated)</sup>
isChangePermitted(): Promise&lt;boolean&gt;
getId(wallpaperType: WallpaperType): Promise&lt;number&gt;
Checks whether to allow the application to change the wallpaper for the current user. This API uses a promise to return the result.
Obtains the ID of the wallpaper of the specified type. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isChangeAllowed<sup>9+</sup>](#wallpaperischangeallowed9) instead.
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getIdSync<sup>9+</sup>](#wallpapergetidsync9) instead.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.|
| Promise&lt;number&gt; | Promise used to return the wallpaper ID. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.|
**Example**
```js
wallpaper.isChangePermitted().then((data) => {
console.log(`success to isChangePermitted: ` + JSON.stringify(data));
```js
wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.log(`success to getId: ${JSON.stringify(data)}`);
}).catch((error) => {
console.error(`failed to isChangePermitted because: ` + JSON.stringify(error));
});
```
console.error(`failed to getId because: ${JSON.stringify(error)}`);
});
```
## wallpaper.getMinHeight<sup>(deprecated)</sup>
## wallpaper.isChangeAllowed<sup>9+</sup>
getMinHeight(callback: AsyncCallback&lt;number&gt;): void
isChangeAllowed(): boolean
Obtains the minimum height of this wallpaper. This API uses an asynchronous callback to return the result.
Checks whether to allow the application to change the wallpaper for the current user. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinHeightSync<sup>9+</sup>](#wallpapergetminheightsync9) instead.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Return value**
**Parameters**
| Type| Description|
| -------- | -------- |
| boolean | Whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.|
**Example**
```js
var isChangeAllowed = wallpaper.isChangeAllowed();
```
```js
wallpaper.getMinHeight((error, data) => {
if (error) {
console.error(`failed to getMinHeight because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to getMinHeight: ${JSON.stringify(data)}`);
});
```
## wallpaper.isOperationAllowed
## wallpaper.getMinHeight<sup>(deprecated)</sup>
isOperationAllowed(callback: AsyncCallback&lt;boolean&gt;): void
getMinHeight(): Promise&lt;number&gt;
Checks whether the user is allowed to set wallpapers. This API uses an asynchronous callback to return the result.
Obtains the minimum height of this wallpaper. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isUserChangeAllowed<sup>9+</sup>](#wallpaperisuserchangeallowed9) instead.
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinHeightSync<sup>9+</sup>](#wallpapergetminheightsync9) instead.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Parameters**
**Return value**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.|
| Type| Description|
| -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.|
**Example**
```js
wallpaper.isOperationAllowed((error, data) => {
if (error) {
console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error));
return;
}
console.log(`success to isOperationAllowed: ` + JSON.stringify(data));
});
```
```js
wallpaper.getMinHeight().then((data) => {
console.log(`success to getMinHeight: ${JSON.stringify(data)}`);
}).catch((error) => {
console.error(`failed to getMinHeight because: ${JSON.stringify(error)}`);
});
```
## wallpaper.isOperationAllowed
## wallpaper.getMinWidth<sup>(deprecated)</sup>
isOperationAllowed(): Promise&lt;boolean&gt;
getMinWidth(callback: AsyncCallback&lt;number&gt;): void
Checks whether the user is allowed to set wallpapers. This API uses a promise to return the result.
Obtains the minimum width of this wallpaper. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isUserChangeAllowed<sup>9+</sup>](#wallpaperisuserchangeallowed9) instead.
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinWidthSync<sup>9+</sup>](#wallpapergetminwidthsync9) instead.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Return value**
**Parameters**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.|
**Example**
```js
wallpaper.isOperationAllowed().then((data) => {
console.log(`success to isOperationAllowed: ` + JSON.stringify(data));
}).catch((error) => {
console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error));
});
```
```js
wallpaper.getMinWidth((error, data) => {
if (error) {
console.error(`failed to getMinWidth because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to getMinWidth: ${JSON.stringify(data)}`);
});
```
## wallpaper.getMinWidth<sup>(deprecated)</sup>
## wallpaper.isUserChangeAllowed<sup>9+</sup>
getMinWidth(): Promise&lt;number&gt;
isUserChangeAllowed(): boolean
Obtains the minimum width of this wallpaper. This API uses a promise to return the result.
Checks whether the user is allowed to set wallpapers. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinWidthSync<sup>9+</sup>](#wallpapergetminwidthsync9) instead.
**System capability**: SystemCapability.MiscServices.Wallpaper
......@@ -530,26 +720,27 @@ Checks whether the user is allowed to set wallpapers. This API uses an asynchron
| Type| Description|
| -------- | -------- |
| boolean | Whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.|
| Promise&lt;number&gt; | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.|
**Example**
```js
var isUserChangeAllowed = wallpaper.isUserChangeAllowed();
```
```js
wallpaper.getMinWidth().then((data) => {
console.log(`success to getMinWidth: ${JSON.stringify(data)}`);
}).catch((error) => {
console.error(`failed to getMinWidth because: ${JSON.stringify(error)}`);
});
```
## wallpaper.reset
## wallpaper.isChangePermitted<sup>(deprecated)</sup>
reset(wallpaperType: WallpaperType, callback: AsyncCallback&lt;void&gt;): void
isChangePermitted(callback: AsyncCallback&lt;boolean&gt;): void
Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result.
Checks whether to allow the application to change the wallpaper for the current user. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.restore<sup>9+</sup>](#wallpaperrestore9) instead.
**Required permissions**: ohos.permission.SET_WALLPAPER
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isChangeAllowed<sup>9+</sup>](#wallpaperischangeallowed9) instead.
**System capability**: SystemCapability.MiscServices.Wallpaper
......@@ -557,66 +748,57 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, the result of removal is returned. Otherwise, error information is returned.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.|
**Example**
```js
wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => {
if (error) {
console.error(`failed to reset because: ` + JSON.stringify(error));
return;
}
console.log(`success to reset.`);
});
```
```js
wallpaper.isChangePermitted((error, data) => {
if (error) {
console.error(`failed to isChangePermitted because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to isChangePermitted: ${JSON.stringify(data)}`);
});
```
## wallpaper.reset
## wallpaper.isChangePermitted<sup>(deprecated)</sup>
reset(wallpaperType: WallpaperType): Promise&lt;void&gt;
isChangePermitted(): Promise&lt;boolean&gt;
Resets the wallpaper of the specified type to the default wallpaper. This API uses a promise to return the result.
Checks whether to allow the application to change the wallpaper for the current user. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.restore<sup>9+</sup>](#wallpaperrestore9) instead.
**Required permissions**: ohos.permission.SET_WALLPAPER
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isChangeAllowed<sup>9+</sup>](#wallpaperischangeallowed9) instead.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.|
| Promise&lt;boolean&gt; | Promise used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.|
**Example**
```js
wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.log(`success to reset.`);
}).catch((error) => {
console.error(`failed to reset because: ` + JSON.stringify(error));
});
```
```js
wallpaper.isChangePermitted().then((data) => {
console.log(`success to isChangePermitted: ${JSON.stringify(data)}`);
}).catch((error) => {
console.error(`failed to isChangePermitted because: ${JSON.stringify(error)}`);
});
```
## wallpaper.restore<sup>9+</sup>
## wallpaper.isOperationAllowed<sup>(deprecated)</sup>
restore(wallpaperType: WallpaperType, callback: AsyncCallback&lt;void&gt;): void
isOperationAllowed(callback: AsyncCallback&lt;boolean&gt;): void
Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result.
Checks whether the user is allowed to set wallpapers. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_WALLPAPER
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isUserChangeAllowed<sup>9+</sup>](#wallpaperisuserchangeallowed9) instead.
**System capability**: SystemCapability.MiscServices.Wallpaper
......@@ -624,64 +806,57 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, the result of removal is returned. Otherwise, error information is returned.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.|
**Example**
```js
wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => {
if (error) {
console.error(`failed to restore because: ` + JSON.stringify(error));
return;
}
console.log(`success to restore.`);
});
```
```js
wallpaper.isOperationAllowed((error, data) => {
if (error) {
console.error(`failed to isOperationAllowed because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to isOperationAllowed: ${JSON.stringify(data)}`);
});
```
## wallpaper.restore<sup>9+</sup>
## wallpaper.isOperationAllowed<sup>(deprecated)</sup>
restore(wallpaperType: WallpaperType): Promise&lt;void&gt;
isOperationAllowed(): Promise&lt;boolean&gt;
Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result.
Checks whether the user is allowed to set wallpapers. This API uses a promise to return the result.
**Required permissions**: ohos.permission.SET_WALLPAPER
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isUserChangeAllowed<sup>9+</sup>](#wallpaperisuserchangeallowed9) instead.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.|
| Promise&lt;boolean&gt; | Promise used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.|
**Example**
```js
wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.log(`success to restore.`);
```js
wallpaper.isOperationAllowed().then((data) => {
console.log(`success to isOperationAllowed: ${JSON.stringify(data)}`);
}).catch((error) => {
console.error(`failed to restore because: ` + JSON.stringify(error));
});
```
console.error(`failed to isOperationAllowed because: ${JSON.stringify(error)}`);
});
```
## wallpaper.setWallpaper
## wallpaper.reset<sup>(deprecated)</sup>
setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback&lt;void&gt;): void
reset(wallpaperType: WallpaperType, callback: AsyncCallback&lt;void&gt;): void
Sets a specified source as the wallpaper of a specified type. This API uses an asynchronous callback to return the result.
Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.setImage<sup>9+</sup>](#wallpapersetimage9) instead.
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.restore<sup>9+</sup>](#wallpaperrestore9) instead.
**Required permissions**: ohos.permission.SET_WALLPAPER
......@@ -691,55 +866,30 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.|
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.|
**Example**
```js
//The source type is string.
let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg";
wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => {
if (error) {
console.error(`failed to setWallpaper because: ` + JSON.stringify(error));
return;
}
console.log(`success to setWallpaper.`);
});
// The source type is image.PixelMap.
import image from '@ohos.multimedia.image';
let imageSource = image.createImageSource("file://" + wallpaperPath);
let opts = {
"desiredSize": {
"height": 3648,
"width": 2736
}
};
imageSource.createPixelMap(opts).then((pixelMap) => {
wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => {
if (error) {
console.error(`failed to setWallpaper because: ` + JSON.stringify(error));
return;
}
console.log(`success to setWallpaper.`);
});
}).catch((error) => {
console.error(`failed to createPixelMap because: ` + JSON.stringify(error));
});
```
```js
wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => {
if (error) {
console.error(`failed to reset because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to reset.`);
});
```
## wallpaper.setWallpaper
## wallpaper.reset<sup>(deprecated)</sup>
setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise&lt;void&gt;
reset(wallpaperType: WallpaperType): Promise&lt;void&gt;
Sets a specified source as the wallpaper of a specified type. This API uses a promise to return the result.
Resets the wallpaper of the specified type to the default wallpaper. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.setImage<sup>9+</sup>](#wallpapersetimage9) instead.
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.restore<sup>9+</sup>](#wallpaperrestore9) instead.
**Required permissions**: ohos.permission.SET_WALLPAPER
......@@ -749,53 +899,34 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.|
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.|
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```js
//The source type is string.
let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg";
wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.log(`success to setWallpaper.`);
}).catch((error) => {
console.error(`failed to setWallpaper because: ` + JSON.stringify(error));
});
// The source type is image.PixelMap.
import image from '@ohos.multimedia.image';
let imageSource = image.createImageSource("file://" + wallpaperPath);
let opts = {
"desiredSize": {
"height": 3648,
"width": 2736
}
};
imageSource.createPixelMap(opts).then((pixelMap) => {
wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.log(`success to setWallpaper.`);
}).catch((error) => {
console.error(`failed to setWallpaper because: ` + JSON.stringify(error));
});
}).catch((error) => {
console.error(`failed to createPixelMap because: ` + JSON.stringify(error));
});
```
```js
wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => {
console.log(`success to reset.`);
}).catch((error) => {
console.error(`failed to reset because: ${JSON.stringify(error)}`);
});
```
## wallpaper.setImage<sup>9+</sup>
## wallpaper.setWallpaper<sup>(deprecated)</sup>
setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback&lt;void&gt;): void
setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback&lt;void&gt;): void
Sets a specified source as the wallpaper of a specified type. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.setImage<sup>9+</sup>](#wallpapersetimage9) instead.
**Required permissions**: ohos.permission.SET_WALLPAPER
**System capability**: SystemCapability.MiscServices.Wallpaper
......@@ -804,51 +935,54 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.|
| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.|
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is error information.|
**Example**
```js
//The source type is string.
let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg";
wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => {
if (error) {
console.error(`failed to setImage because: ` + JSON.stringify(error));
return;
}
console.log(`success to setImage.`);
});
// The source type is image.PixelMap.
import image from '@ohos.multimedia.image';
let imageSource = image.createImageSource("file://" + wallpaperPath);
let opts = {
"desiredSize": {
"height": 3648,
"width": 2736
}
};
imageSource.createPixelMap(opts).then((pixelMap) => {
wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => {
if (error) {
console.error(`failed to setImage because: ` + JSON.stringify(error));
return;
}
console.log(`success to setImage.`);
});
}).catch((error) => {
console.error(`failed to createPixelMap because: ` + JSON.stringify(error));
});
```
```js
//The source type is string.
let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg";
wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => {
if (error) {
console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to setWallpaper.`);
});
// The source type is image.PixelMap.
import image from '@ohos.multimedia.image';
let imageSource = image.createImageSource("file://" + wallpaperPath);
let opts = {
"desiredSize": {
"height": 3648,
"width": 2736
}
};
imageSource.createPixelMap(opts).then((pixelMap) => {
wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => {
if (error) {
console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to setWallpaper.`);
});
}).catch((error) => {
console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`);
});
```
## wallpaper.setWallpaper<sup>(deprecated)</sup>
## wallpaper.setImage<sup>9+</sup>
setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise&lt;void&gt;
setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise&lt;void&gt;
Sets a specified source as the wallpaper of a specified type. This API uses a promise to return the result.
Sets a specified source as the wallpaper of a specified type. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.setImage<sup>9+</sup>](#wallpapersetimage9) instead.
**Required permissions**: ohos.permission.SET_WALLPAPER
......@@ -858,48 +992,48 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.|
| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.|
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.|
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
```js
//The source type is string.
let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg";
wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.log(`success to setImage.`);
```js
//The source type is string.
let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg";
wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => {
console.log(`success to setWallpaper.`);
}).catch((error) => {
console.error(`failed to setImage because: ` + JSON.stringify(error));
});
console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`);
});
// The source type is image.PixelMap.
import image from '@ohos.multimedia.image';
let imageSource = image.createImageSource("file://" + wallpaperPath);
let opts = {
"desiredSize": {
"height": 3648,
"width": 2736
}
};
imageSource.createPixelMap(opts).then((pixelMap) => {
wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.log(`success to setImage.`);
}).catch((error) => {
console.error(`failed to setImage because: ` + JSON.stringify(error));
});
}).catch((error) => {
console.error(`failed to createPixelMap because: ` + JSON.stringify(error));
});
```
// The source type is image.PixelMap.
import image from '@ohos.multimedia.image';
let imageSource = image.createImageSource("file://" + wallpaperPath);
let opts = {
"desiredSize": {
"height": 3648,
"width": 2736
}
};
imageSource.createPixelMap(opts).then((pixelMap) => {
wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => {
console.log(`success to setWallpaper.`);
}).catch((error) => {
console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`);
});
}).catch((error) => {
console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`);
});
```
## wallpaper.getFile<sup>8+</sup>
## wallpaper.getFile<sup>(deprecated)</sup>
getFile(wallpaperType: WallpaperType, callback: AsyncCallback&lt;number&gt;): void
......@@ -922,17 +1056,17 @@ Obtains the wallpaper of the specified type. This API uses an asynchronous callb
**Example**
```js
wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => {
if (error) {
console.error(`failed to getFile because: ` + JSON.stringify(error));
return;
}
console.log(`success to getFile: ` + JSON.stringify(data));
});
```
```js
wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => {
if (error) {
console.error(`failed to getFile because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to getFile: ${JSON.stringify(data)}`);
});
```
## wallpaper.getFile<sup>8+</sup>
## wallpaper.getFile<sup>(deprecated)</sup>
getFile(wallpaperType: WallpaperType): Promise&lt;number&gt;
......@@ -960,45 +1094,15 @@ Obtains the wallpaper of the specified type. This API uses a promise to return t
**Example**
```js
wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.log(`success to getFile: ` + JSON.stringify(data));
```js
wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.log(`success to getFile: ${JSON.stringify(data)}`);
}).catch((error) => {
console.error(`failed to getFile because: ` + JSON.stringify(error));
});
```
## wallpaper.getFileSync<sup>9+</sup>
getFileSync(wallpaperType: WallpaperType): number;
Obtains the wallpaper of the specified type. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_WALLPAPER
**System capability**: SystemCapability.MiscServices.Wallpaper
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
**Return value**
| Type| Description|
| -------- | -------- |
| number | Promise used to return the result. If the operation is successful, the file descriptor ID to the wallpaper is returned. Otherwise, error information is returned.|
**Example**
```js
var file = wallpaper.getFileSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM);
```
console.error(`failed to getFile because: ${JSON.stringify(error)}`);
});
```
## wallpaper.getPixelMap
## wallpaper.getPixelMap<sup>(deprecated)</sup>
getPixelMap(wallpaperType: WallpaperType, callback: AsyncCallback&lt;image.PixelMap&gt;): void;
......@@ -1012,7 +1116,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses an
**System capability**: SystemCapability.MiscServices.Wallpaper
**System API**: This is a system API and cannot be called by third-party applications.
**System API**: This is a system API.
**Parameters**
......@@ -1023,15 +1127,17 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses an
**Example**
```js
wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (err, data) {
console.info('wallpaperXTS ===> testGetPixelMapCallbackSystem err : ' + JSON.stringify(err));
console.info('wallpaperXTS ===> testGetPixelMapCallbackSystem data : ' + JSON.stringify(data));
```js
wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (error, data) {
if (error) {
console.error(`failed to getPixelMap because: ${JSON.stringify(error)}`);
return;
}
console.log(`success to getPixelMap : ${JSON.stringify(data)}`);
});
```
```
## wallpaper.getPixelMap
## wallpaper.getPixelMap<sup>(deprecated)</sup>
getPixelMap(wallpaperType: WallpaperType): Promise&lt;image.PixelMap&gt;
......@@ -1045,7 +1151,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses a p
**System capability**: SystemCapability.MiscServices.Wallpaper
**System API**: This is a system API and cannot be called by third-party applications.
**System API**: This is a system API.
**Parameters**
......@@ -1061,144 +1167,10 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses a p
**Example**
```js
wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + data);
console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + JSON.stringify(data));
}).catch((err) => {
console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem err : ' + err);
console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem err : ' + JSON.stringify(err));
});
```
## wallpaper.getImage<sup>9+</sup>
getImage(wallpaperType: WallpaperType, callback: AsyncCallback&lt;image.PixelMap&gt;): void;
Obtains the pixel map for the wallpaper of the specified type. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_WALLPAPER
**System capability**: SystemCapability.MiscServices.Wallpaper
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
| callback | AsyncCallback&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Yes| Callback used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.|
**Example**
```js
wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (err, data) {
console.info('wallpaperXTS ===> testgetImageCallbackSystem err : ' + JSON.stringify(err));
console.info('wallpaperXTS ===> testgetImageCallbackSystem data : ' + JSON.stringify(data));
});
```
## wallpaper.getImage<sup>9+</sup>
getImage(wallpaperType: WallpaperType): Promise&lt;image.PixelMap&gt;
Obtains the pixel map for the wallpaper of the specified type. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_WALLPAPER
**System capability**: SystemCapability.MiscServices.Wallpaper
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[image.PixelMap](js-apis-image.md#pixelmap7)&gt; | Promise used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.|
**Example**
```js
wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.info('wallpaperXTS ===> testgetImagePromiseSystem data : ' + data);
console.info('wallpaperXTS ===> testgetImagePromiseSystem data : ' + JSON.stringify(data));
}).catch((err) => {
console.info('wallpaperXTS ===> testgetImagePromiseSystem err : ' + err);
console.info('wallpaperXTS ===> testgetImagePromiseSystem err : ' + JSON.stringify(err));
});
```
## wallpaper.on('colorChange')<sup>9+</sup>
on(type: 'colorChange', callback: (colors: Array&lt;RgbaColor&gt;, wallpaperType: WallpaperType) =&gt; void): void
Subscribes to the wallpaper color change event.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to subscribe to. The value **'colorChange'** indicates subscribing to the wallpaper color change event.|
| callback | function | Yes| Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned.<br>- colors<br>Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).<br>- wallpaperType<br>Wallpaper type.|
**Example**
```js
let listener = (colors, wallpaperType) => {
console.log(`wallpaper color changed.`);
};
wallpaper.on('colorChange', listener);
```
## wallpaper.off('colorChange')<sup>9+</sup>
off(type: 'colorChange', callback?: (colors: Array&lt;RgbaColor&gt;, wallpaperType: WallpaperType) =&gt; void): void
Unsubscribes from the wallpaper color change event.
**System capability**: SystemCapability.MiscServices.Wallpaper
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Type of the event to unsubscribe from. The value **colorChange** indicates unsubscribing from the wallpaper color change event.|
| callback | function | No| Callback for the wallpaper color change event. If this parameter is not specified, all callbacks corresponding to the wallpaper color change event are invoked.<br>- colors<br>Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).<br>- wallpaperType<br>Wallpaper type.|
**Example**
```js
let listener = (colors, wallpaperType) => {
console.log(`wallpaper color changed.`);
};
wallpaper.on('colorChange', listener);
// Unsubscribe from the listener.
wallpaper.off('colorChange', listener);
// Unsubscribe from all subscriptions of the colorChange type.
wallpaper.off('colorChange');
```
## RgbaColor
**System capability**: SystemCapability.MiscServices.Wallpaper
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| red | number | Yes| Yes| Red color. The value ranges from 0 to 255.|
| green | number | Yes| Yes| Green color. The value ranges from 0 to 255.|
| blue | number | Yes| Yes| Blue color. The value ranges from 0 to 255.|
| alpha | number | Yes| Yes| Alpha value. The value ranges from 0 to 255.|
```js
wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => {
console.log(`success to getPixelMap : ${JSON.stringify(data)}`);
}).catch((error) => {
console.error(`failed to getPixelMap because: ${JSON.stringify(error)}`);
});
```
......@@ -18,7 +18,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| Name | Type | Default Value | Mandatory | Description |
| ---------------------- | ------- | ----- | ---- | ---------------------------------------- |
| type | string | - | No | Button type. The value cannot be dynamically updated. If this attribute is not set, a capsule-like button is displayed. Unlike the capsule button, the capsule-like button allows its corners to be configured using **border-radius**. Available button types are as follows:<br>- **capsule**: capsule button with fillets, background color, and text.<br>- **circle**: circle button that can accommodate icons.<br>- **text**: text button, which displays only text.<br>- **arc**: arc button. This value is applicable to wearables only.<br>- **download**: download button, with an extra download progress bar.|
| type | string | - | No | Button type. The value cannot be dynamically updated. By default, a capsule-like button is displayed. Unlike the capsule button, the capsule-like button allows its corners to be configured using **border-radius**. The options are as follows:<br>- **capsule**: capsule button with fillets, background color, and text.<br>- **circle**: circle button that can accommodate icons.<br>- **text**: text button, which displays only text.<br>- **arc**: arc button. This value is applicable to wearables only.<br>- **download**: download button, with an extra download progress bar.|
| value | string | - | No | Text value of the button. |
| icon | string | - | No | Path of the button icon. The supported icon formats are JPG, PNG, and SVG. |
| placement<sup>5+</sup> | string | end | No | Position of the button icon in text. This attribute is valid only when **type** is not set. Available values are as follows:<br>- **start**: The button icon is at the beginning of the text.<br>- **end**: The button icon is at the end of the text.<br>- **top**: The button icon is at the top of the text.<br>- **bottom**: The button icon is at the bottom of the text.|
......@@ -39,7 +39,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.|
| font-style | string | normal | No | Font style of the button. |
| font-weight | number \| string | normal | No | Font weight of the button. For details, see **font-weight** of the [**\<text>** component](../arkui-js/js-components-basic-text.md#styles).|
| font-family | &lt;string&gt; | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. |
| font-family | &lt;string&gt; | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.|
| icon-width | &lt;length&gt; | - | No | Width of the internal icon of a circle button. The entire circle button is filled by default.<br>This style must be set when the icon uses the SVG image.|
| icon-height | &lt;length&gt; | - | No | Height of the internal icon of a circle button. The entire circle button is filled by default.<br>This style must be set when the icon uses the SVG image.|
| radius | &lt;length&gt; | - | No | Corner radius of the button. For a circle button, this style takes precedence over **width** and **height** in the universal styles.|
......@@ -55,8 +55,8 @@ In addition to the **background-color**, **opacity**, **display**, **visibility*
| font-size | &lt;length&gt; | 37.5px | No | Font size of the arc button. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings. |
| font-style | string | normal | No | Font style of the arc button. |
| font-weight | number \| string | normal | No | Font weight of the arc button. For details, see **font-weight** of the [**\<text>** component](../arkui-js/js-components-basic-text.md#styles).|
| font-family | &lt;string&gt; | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. |
| font-weight | number \| string | normal | No | Font weight of the arc button. For details, see **font-weight** of the [**\<text>**](../arkui-js/js-components-basic-text.md#styles) component. |
| font-family | &lt;string&gt; | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.|
## Events
......
......@@ -22,7 +22,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| Name | Type | Default Value | Mandatory | Description |
| ------------------------------ | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| type | string | line | No | Chart type. Dynamic modification is not supported. Available values include:<br>- **bar**: bar chart.<br>- **line**: line chart.<br>- **gauge**: gauge chart.<br>- **progress**<sup>5+</sup>: circle chart of progresses.<br>- **loading**<sup>5+</sup>: circle chart of loading processes.<br>- **rainbow**<sup>5+</sup>: circle chart of proportions.|
| type | string | line | No | Chart type. Dynamic modification is not supported. Available values include:<br>- **bar**: bar chart<br>- **line**: line chart<br>- **gauge**: gauge chart<br>- **progress**<sup>5+</sup>: circle chart of progresses<br>- **loading**<sup>5+</sup>: circle chart of loading processes<br>- **rainbow**<sup>5+</sup>: circle chart of proportions|
| options | ChartOptions | - | No | Chart parameters. You must set parameters for bar charts and line charts. Parameter settings for gauge charts do not take effect. You can set the minimum value, maximum value, scale, and line width of the x-axis or y-axis, whether to display the x-axis and y-axis, and whether the line is smooth. Dynamic modification is not supported.|
| datasets | Array&lt;ChartDataset&gt; | - | No | Data sets. You must set data sets for bar charts and line charts. Data sets for a gauge chart do not take effect. You can set multiple datasets and their background colors.|
| segments<sup>5+</sup> | DataSegment \| Array&lt;DataSegment&gt; | - | No | Data structures used by **progress**, **loading**, and **rainbow** charts.<br>**DataSegment** is available for **progress** and **loading** charts.<br>**Array&lt;DataSegment&gt;** is available for **rainbow** charts. A maximum of nine **DataSegment**s are supported in the array.|
......@@ -99,7 +99,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| description | string | - | No | Description text of the point. |
| textLocation | string | - | No | Position of the description text relative to the point. Available values are as follows: **top**: above the point<br>**bottom**: below the point<br>**none**: not displayed|
| textColor | &lt;color&gt; | \#000000 | No | Color of the description text. |
| lineDash | string | solid | No | Dashed line pattern. You can set the dash length and space length between the dashes. For example, **"dashed, 5, 5"** indicates a dashed line with each dash in 5 px and a 5 px space between each two dashes. Default value **"solid"** indicates a solid line.|
| lineDash | string | solid | No | Dashed line pattern. You can set the dash length and space length between the dashes. - **"dashed, 5, 5"**: dashed line with each dash in 5 px and a 5 px space between each two dashes. Default value **"solid"** indicates a solid line.|
| lineColor | &lt;color&gt; | \#000000 | No | Line color. If this attribute is not set, the value of **strokeColor** is used. |
**Table 9** DataSegment<sup>5+</sup>
......@@ -144,7 +144,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| center-x | &lt;length&gt; | - | No | Center of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **position** style in the common styles, and must be used together with **center-y** and **radius**. This style is supported by the gauge chart only.|
| center-y | &lt;length&gt; | - | No | Center of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **position** style in the common styles, and must be used together with **center-x** and **radius**. This style is supported by the gauge chart only.|
| radius | &lt;length&gt; | - | No | Radius of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **width** and **height** in the common styles, and must be used together with **center-x** and **center-y**. This style is supported by the gauge chart only.|
| colors | Array | - | No | Color of each section for the scale bar of the gauge component.<br>For example, **colors: \#ff0000, #00ff00**. This style is supported by the gauge chart only.|
| colors | Array | - | No | Color of each section for the scale bar of the gauge component.<br>For example, **colors: \#ff0000, \#00ff00**. This style is supported by the gauge chart only.|
| weights | Array | - | No | Weight of each section for the scale bar of the gauge component.<br>For example, **weights: 2, 2**. This style is supported by the gauge chart only.|
| font-family<sup>5+</sup> | Array | - | No | Font style of the description text. You can use a [custom font](../arkui-js/js-components-common-customizing-font.md).|
| font-size<sup>5+</sup> | &lt;length&gt; | - | No | Font size of the description text. |
......@@ -161,7 +161,7 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
| Name | Parameter | Description |
| ------ | ---------------------------------------- | ---------------------------------------- |
| append | {<br>serial: number, // Set the data subscript of the line chart to be updated.<br>data: Array&lt;number&gt;, // Set the new data.<br>} | Data is dynamically added to an existing data sequence. The target sequence is specified based on **serial**, which is the subscript of the datasets array and starts from 0. **datasets[index].data** is not updated. Only line charts support this attribute. The value is incremented by 1 based on the horizontal coordinate and is related to the **xAxis min/max** setting.|
| append | {<br>serial: number, <br>data: Array&lt;number&gt;, <br>} | Data is dynamically added to an existing data sequence. The target sequence is specified based on **serial**, which is the subscript of the datasets array and starts from 0. For example, if the value of **serial** is **index**, use **data** to update **datasets[index].data**. Only line charts support this attribute. The value is incremented by 1 based on the horizontal coordinate and is related to the **xAxis min/max** setting.|
## Example
......@@ -212,24 +212,24 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
strokeColor: '#0081ff',
fillColor: '#cce5ff',
data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716],
gradient: true,
gradient: true
}
],
lineOps: {
xAxis: {
min: 0,
max: 20,
display: false,
display: false
},
yAxis: {
min: 0,
max: 1000,
display: false,
display: false
},
series: {
lineStyle: {
width: "5px",
smooth: true,
smooth: true
},
headPoint: {
shape: "circle",
......@@ -237,14 +237,14 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
strokeWidth: 5,
fillColor: '#ffffff',
strokeColor: '#007aff',
display: true,
display: true
},
loop: {
margin: 2,
gradient: true,
gradient: true
}
}
},
}
},
addData() {
this.$refs.linechart.append({
......@@ -295,15 +295,15 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
barData: [
{
fillColor: '#f07826',
data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628],
data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628]
},
{
fillColor: '#cce5ff',
data: [535, 776, 615, 444, 694, 785, 677, 609, 562, 410],
data: [535, 776, 615, 444, 694, 785, 677, 609, 562, 410]
},
{
fillColor: '#ff88bb',
data: [673, 500, 574, 483, 702, 583, 437, 506, 693, 657],
data: [673, 500, 574, 483, 702, 583, 437, 506, 693, 657]
},
],
barOps: {
......@@ -311,14 +311,14 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
min: 0,
max: 20,
display: false,
axisTick: 10,
axisTick: 10
},
yAxis: {
min: 0,
max: 1000,
display: false,
},
},
display: false
}
}
}
}
```
......@@ -353,3 +353,76 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
```
![en-us_image_0000001127125264](figures/en-us_image_0000001127125264.png)
4. Circle chart of progresses, loading progresses, or proportions
```html
<!-- xxx.hml -->
<div class="container">
<text class="text">progress Example</text>
<stack class="chart-region">
<chart class="" type="progress" segments="{{ progressdata }}"></chart>
</stack>
<text class="text">loading Example</text>
<stack class="chart-region">
<chart class="" type="loading" segments="{{ loadingdata }}"></chart>
</stack>
<text class="text">rainbow Example</text>
<stack class="chart-region">
<chart class="" type="rainbow" segments="{{ rainbowdata }}" effects="true" animationduration="5000"></chart>
</stack>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
}
.chart-region {
height: 400px;
width: 700px;
margin-top: 10px;
}
.text {
margin-top: 30px;
}
```
```js
// xxx.js
export default {
data: {
progressdata: {
value: 50,
name: 'progress'
},
loadingdata: {
startColor: "#ffc0cb",
endColor: "#00bfff",
},
rainbowdata: [
{
value: 50,
name: 'item1'
},
{
value: 10,
name: 'item2'
},
{
value: 20,
name: 'item3'
},
{
value: 10,
name: 'item4'
},
{
value: 10,
name: 'item5'
}
]
}
}
```
![rainbow](figures/rainbow.gif)
......@@ -31,7 +31,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| object-fit | string | cover | No | Image scale type. This style is not supported for SVG images. For details about available values, see **object-fit**.|
| match-text-direction | boolean | false | No | Whether image orientation changes with the text direction. This style is not supported for SVG images. |
| fit-original-size | boolean | false | No | Whether the **\<image>** component adapts to the image source size when its width and height are not set. If this style is set to **true**, **object-fit** will not take effect. This style is not supported for SVG images.|
| object-position<sup>7+</sup> | string | 0px 0px | No | Position of an image in the component.<br>The options are as follows:<br>1. Pixels. For example, **15px 15px** indicates the moving position along the x-axis or y-axis.<br>2. Characters. Optional values are as follows:<br>- **left**: The image is displayed on the left of the component.<br>- **top** The image is displayed on the top of the component.<br>- **right** The image is displayed on the right of the component.<br>- **bottom** The image is displayed at the bottom of the component.|
| object-position<sup>7+</sup> | string | 0px 0px | No | Position of the image in the component.<br>The options are as follows:<br>1. Pixels, in px. For example, **15px 15px** indicates the position to move along the x-axis or y-axis.<br>2. Characters. Optional values are as follows:<br>- **left**: The image is displayed on the left of the component.<<br>- **top**: The image is displayed on the top of the component.<br>- **right**: The image is displayed on the right of the component.<br>- **bottom**: The image is displayed at the bottom of the component.|
**Table 1** object-fit
......@@ -56,16 +56,18 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
> 1. If the **\<image>** component is too small to afford the SVG image, the SVG image is cropped and only its upper left part is displayed in the component.
>
> 2. If the **\<image>** component is big enough to afford the SVG image, this SVG image is displayed in the upper left corner of the component.
>
> - For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, **polygon**, **animate**, **animateMotion**, and **animateTransform**.
## Events
In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported.
| Name | Parameter | Description |
| -------------- | ---------------------------------------- | ------------------------- |
| complete(Rich) | {<br> width: width,<br> height: height<br> } | Triggered when an image is successfully loaded. The loaded image size is returned.|
| error(Rich) | {<br> width: width,<br> height: height<br> } | Triggered when an exception occurs during image loading. In this case, the width and height are **0**. |
| Name | Parameter | Description |
| -------- | ---------------------------------------- | ------------------------- |
| complete | {<br> width: width,<br> height: height<br> } | Triggered when an image is successfully loaded. The loaded image size is returned.|
| error | {<br> width: width,<br> height: height<br> } | Triggered when an exception occurs during image loading. In this case, the width and height are **0**. |
## Methods
......
......@@ -20,44 +20,44 @@ Not supported
In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported.
| Name | Type | Default Value | Mandatory | Description |
| -------------------------------- | ----------------------- | ------------- | --------- | ---------------------------------------- |
| type | string | text<br> | No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.<br>The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.<br>The **button**, **checkbox**, and **radio** types cannot be dynamically modified. <br>- **button**: a button that can be clicked.<br>- **checkbox**: a check box.<br>- **radio**: a radio button that allows users to select one from multiple others with the same name.<br>- **text**: a single-line text field.<br>- **email**: a field used for an email address.<br>- **date**: date component, including the year, month, and day, but excluding time.<br>- **time**: time component, without the time zone.<br>- **number**: field for entering digits.<br>- **password**: password field, in which characters will be shielded. |
| checked | boolean | false | No | Whether the **\<input>** component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**. |
| name | string | - | No | Name of the **\<input>** component.<br>This attribute is mandatory when **type** is set to **radio**. |
| value | string | - | No | Value of the **\<input>** component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name. |
| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text** \|email\|date\|time\|number\|**password**. |
| maxlength | number | - | No | Maximum number of characters that can be entered in the input box. The empty value indicates no limit. |
| enterkeytype | string | default | No | Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.<br>Available values include:<br>- default<br>- next<br>- go<br>- done<br>- send<br>- search<br>Except for the **next** type, clicking the Enter key hides the soft keyboard. |
| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG. |
| showcounter<sup>5+</sup> | boolean | false | No | Whether to display the character counter for an input box. This attribute takes effect only when **maxlength** is set. |
| menuoptions<sup>5+</sup> | Array&lt;MenuOption&gt; | - | No | Menu options displayed after users click the **More** button. |
| autofocus<sup>6+</sup> | boolean | false | No | Whether to automatically obtain focus.<br>This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**. |
| selectedstart<sup>6+</sup> | number | -1 | No | Start position for text selection. |
| selectedend<sup>6+</sup> | number | -1 | No | End position for text selection. |
| softkeyboardenabled<sup>6+</sup> | boolean | true | No | Whether to display the soft keyboard during editing. |
| showpasswordicon<sup>6+</sup> | boolean | true | No | Whether to display the icon at the end of the password text box. This attribute is available only when **type** is set to **password**. |
| Name | Type | Default Value | Mandatory | Description |
| -------------------------------- | ----------------------- | --------- | ---- | ---------------------------------------- |
| type | string | text<br>| No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.<br>The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.<br>The **button**, **checkbox**, and **radio** types cannot be dynamically modified. <br>- **button**: a button that can be clicked.<br>- **checkbox**: a check box.<br>- **radio**: a radio button that allows users to select one from multiple others with the same name.<br>- **text**: a single-line text field.<br>- **email**: a field used for an email address.<br>- **date**: date component, including the year, month, and day, but excluding time.<br>- **time**: time component, without the time zone.<br>- **number**: field for entering digits.<br>- **password**: password field, in which characters will be shielded.|
| checked | boolean | false | No | Whether the **\<input>** component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**. |
| name | string | - | No | Name of the **\<input>** component.<br>This attribute is mandatory when **type** is set to **radio**. |
| value | string | - | No | Value of the **\<input>** component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name.|
| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text** \|email\|date\|time\|number\|**password**.|
| maxlength | number | - | No | Maximum number of characters that can be entered in the input box. The empty value indicates no limit. |
| enterkeytype | string | default | No | Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.<br>Available values include:<br>- default<br>- next<br>- go<br>- done<br>- send<br>- search<br>Except for the **next** type, clicking the Enter key hides the soft keyboard.|
| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG.|
| showcounter<sup>5+</sup> | boolean | false | No | Whether to display the character counter for an input box. This attribute takes effect only when **maxlength** is set. |
| menuoptions<sup>5+</sup> | Array&lt;MenuOption&gt; | - | No | Menu options displayed after users click the **More** button. |
| autofocus<sup>6+</sup> | boolean | false | No | Whether to automatically obtain focus.<br>This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**.|
| selectedstart<sup>6+</sup> | number | -1 | No | Start position for text selection. |
| selectedend<sup>6+</sup> | number | -1 | No | End position for text selection. |
| softkeyboardenabled<sup>6+</sup> | boolean | true | No | Whether to display the soft keyboard during editing. |
| showpasswordicon<sup>6+</sup> | boolean | true | No | Whether to display the icon at the end of the password text box. This attribute is available only when **type** is set to **password**. |
**Table 1** MenuOption<sup>5+</sup>
| Name | Type | Description |
| ------- | ------ | ----------------------------------- |
| icon | string | Path of the icon for a menu option. |
| content | string | Text content of a menu option. |
| Name | Type | Description |
| ------- | ------ | ----------- |
| icon | string | Path of the icon for a menu option.|
| content | string | Text content of a menu option.|
## Styles
In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported.
| Name | Type | Default Value | Mandatory | Description |
| ------------------------ | ---------------- | ------------- | --------- | ---------------------------------------- |
| color | &lt;color&gt; | \#e6000000 | No | Font color of the single-line text box or button. |
| font-size | &lt;length&gt; | 16px | No | Font size of the single-line text box or button. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart. |
| placeholder-color | &lt;color&gt; | \#99000000 | No | Color of the hint text in the single-line text box. This attribute is available only when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**. |
| font-weight | number \| string | normal | No | Font weight of the single-line text box or button. For details, see **font-weight** of the [**\<text>**](../arkui-js/js-components-basic-text.md) component. |
| caret-color<sup>6+</sup> | &lt;color&gt; | - | No | Color of the caret. |
| Name | Type | Default Value | Mandatory | Description |
| ------------------------ | -------------------------- | ---------- | ---- | ---------------------------------------- |
| color | &lt;color&gt; | \#e6000000 | No | Font color of the single-line text box or button. |
| font-size | &lt;length&gt; | 16px | No | Font size of the single-line text box or button. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.|
| placeholder-color | &lt;color&gt; | \#99000000 | No | Color of the hint text in the single-line text box. This attribute is available only when the component type is set to **text**, **email**, **date**, **time**, **number**, or **password**. |
| font-weight | number \| string | normal | No | Font weight of the single-line text box or button. For details, see **font-weight** of the [**\<text>**](../arkui-js/js-components-basic-text.md) component. |
| caret-color<sup>6+</sup> | &lt;color&gt; | - | No | Color of the caret. |
## Events
......@@ -66,27 +66,27 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md
- When **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**, the following events are supported.
| Name | Parameter | Description |
| Name | Parameter | Description |
| ------------------------- | ---------------------------------------- | ---------------------------------------- |
| change | {<br> value: inputValue<br> } | Triggered when the content entered in the input box changes. The most recent content entered by the user is returned.<br>If you change the **value** attribute directly, this event will not be triggered. |
| enterkeyclick | {<br> value: enterKey<br> } | Triggered when the **Enter** key on the soft keyboard is clicked. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:<br>- **2**: returned if **enterkeytype** is **go**.<br>- **3**: returned if **enterkeytype** is **search**.<br>- **4**: returned if **enterkeytype** is **send**.<br>- **5**: returned if **enterkeytype** is **next**.<br>- **6**: returned if **enterkeytype** is **default**, **done**, or is not set. |
| translate<sup>5+</sup> | {<br> value: selectedText<br> } | Triggered when users click the translate button in the menu displayed after they select a text segment. The selected text content is returned. |
| share<sup>5+</sup> | {<br> value: selectedText<br> } | Triggered when users click the share button in the menu displayed after they select a text segment. The selected text content is returned. |
| search<sup>5+</sup> | {<br> value: selectedText<br> } | Triggered when users click the search button in the menu displayed after they select a text segment. The selected text content is returned. |
| optionselect<sup>5+</sup> | {<br> index: optionIndex,<br> value: selectedText<br> } | Triggered when users click a menu option in the menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned. |
| selectchange<sup>6+</sup> | {<br>start: number,<br>end: number<br> } | Triggered when the text selection changes. |
| change | {<br> value: inputValue<br> } | Triggered when the content entered in the input box changes. The most recent content entered by the user is returned.<br>If you change the **value** attribute directly, this event will not be triggered.|
| enterkeyclick | {<br> value: enterKey<br> } | Triggered when the **Enter** key on the soft keyboard is clicked. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:<br>- **2**: returned if **enterkeytype** is **go**.<br>- **3**: returned if **enterkeytype** is **search**.<br>- **4**: returned if **enterkeytype** is **send**.<br>- **5**: returned if **enterkeytype** is **next**.<br>- **6**: returned if **enterkeytype** is **default**, **done**, or is not set.|
| translate<sup>5+</sup> | {<br> value: selectedText<br> } | Triggered when users click the translate button in the menu displayed after they select a text segment. The selected text content is returned.|
| share<sup>5+</sup> | {<br> value: selectedText<br> } | Triggered when users click the share button in the menu displayed after they select a text segment. The selected text content is returned.|
| search<sup>5+</sup> | {<br> value: selectedText<br> } | Triggered when users click the search button in the menu displayed after they select a text segment. The selected text content is returned.|
| optionselect<sup>5+</sup> | {<br> index: optionIndex,<br> value: selectedText<br> } | Triggered when users click a menu option in the menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned.|
| selectchange<sup>6+</sup> | {<br>start: number,<br>end: number<br> } | Triggered when the text selection changes. |
- When **type** is set to **checkbox** or **radio**, the following events are supported.
| Name | Parameter | Description |
| ------ | --------------------------------- | ---------------------------------------- |
| change | {<br> checked:true \| false <br>} | Triggered when the checked status of the **checkbox** or **radio** button changes. |
| Name | Parameter | Description |
| ------ | ---------------------------------------- | ---------------------------------------- |
| change | {<br> checked:true \| false <br>} | Triggered when the checked status of the **checkbox** or **radio** button changes.|
## Methods
In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported.
| Name | Parameter | Description |
| Name | Parameter | Description |
| ------------------- | ---------------------------------------- | ---------------------------------------- |
| focus | {<br> focus: true\|false<br> }:<br>If **focus** is not passed, the default value **true** is used. | Obtains or loses focus. When **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**, the input method can be displayed or collapsed. |
| showError | {<br> error: string <br>} | Displays the error message. This method is available when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**. |
......@@ -102,38 +102,40 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
headericon="/common/search.svg" placeholder="Please input text" onchange="change"
onenterkeyclick="enterkeyClick">
</input>
<input class="button" type="button" value="Submit" onclick="buttonClick"></input>
<input class="button" type="button" value="Submit" onclick="buttonClick" style="color: blue"></input>
</div>
```
```css
/* xxx.css */
.content {
width: 60%;
width: 100%;
flex-direction: column;
align-items: center;
}
.input {
width: 60%;
placeholder-color: gray;
}
.button {
width: 60%;
background-color: gray;
margin-top: 20px;
}
}
```
```js
// xxx.js
import prompt from '@system.prompt'
import promptAction from '@ohos.promptAction'
export default {
change(e){
prompt.showToast({
promptAction.showToast({
message: "value: " + e.value,
duration: 3000,
});
},
enterkeyClick(e){
prompt.showToast({
promptAction.showToast({
message: "enterkey clicked",
duration: 3000,
});
......@@ -143,11 +145,11 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
error: 'error text'
});
},
}
}
```
![1-2](figures/1-2.png)
2. Common button
```html
<!-- xxx.hml -->
......@@ -190,10 +192,10 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
```js
// xxx.js
import prompt from '@system.prompt'
import promptAction from '@ohos.promptAction'
export default {
checkboxOnChange(e) {
prompt.showToast({
promptAction.showToast({
message:'checked: ' + e.checked,
duration: 3000,
});
......@@ -225,11 +227,11 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
```js
// xxx.js
import prompt from '@system.prompt'
import promptAction from '@ohos.promptAction'
export default {
onRadioChange(inputValue, e) {
if (inputValue === e.value) {
prompt.showToast({
promptAction.showToast({
message: 'The chosen radio is ' + e.value,
duration: 3000,
});
......
......@@ -35,8 +35,8 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| font-size | &lt;length&gt; | 30px | No | Font size. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>For details about how to make the configuration take effect dynamically, see the **config-changes** attribute in the **config.json** file.|
| letter-spacing | &lt;length&gt; | 0px | No | Character spacing (px). |
| font-style | string | normal | No | Font style. Available values are as follows:<br>- **normal**: standard font style<br>- **italic**: italic font style|
| font-weight | number \| string | normal | No | Font width. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a larger font width.<br>The value of the number type must be an integer multiple of 100.<br>The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.|
| font-style | string | normal | No | Font style. Available values are as follows:<br>- **normal**: standard font style.<br>- **italic**: italic font style.|
| font-weight | number \| string | normal | No | Font weight. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a heavier font weight.<br>The value of the number type must be an integer multiple of 100.<br>The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.|
| text-decoration | string | none | No | Text decoration. Available values are as follows:<br>- **underline**: An underline is used.<br>- **line-through**: A strikethrough is used.<br>- **none**: The standard text is used.|
| text-align | string | start<br>| No | Text alignment mode. Available values are as follows:<br>- **left**: The text is left-aligned.<br>- **center**: The text is center-aligned.<br>- **right**: The text is right-aligned.<br>- **start**: The text is aligned with the direction in which the text is written.<br>- **end**: The text is aligned with the opposite direction in which the text is written.<br>If the text width is not specified, the alignment effect may not be obvious when the text width is the same as the width of the parent container.|
| line-height | &lt;length&gt; | 0px | No | Text line height. When this parameter is set to **0px**, the text line height is not limited and the font size is adaptive. |
......@@ -46,7 +46,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| min-font-size | &lt;length&gt; | - | No | Minimum font size in the text. This style must be used together with **max-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.|
| max-font-size | &lt;length&gt; | - | No | Maximum font size in the text. This style must be used together with **min-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.|
| font-size-step | &lt;length&gt; | 1px | No | Step for dynamically adjusting the font size in the text. The minimum and maximum font sizes must be set. |
| prefer-font-sizes | &lt;array&gt; | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.<br>Example values: **12px,14px,16px**|
| prefer-font-sizes | &lt;array&gt; | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.<br>Example: prefer-font-sizes: 12px,14px,16px|
## Events
......@@ -83,7 +83,7 @@ Not supported
/*xxx.css */
.container {
flex-direction: column;
align-items: center;
margin-left: 20px;
}
.row {
flex-direction: row;
......
......@@ -37,7 +37,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| color | &lt;color&gt; | \#e5000000 | No | Font color of the scrolling text. |
| font-size | &lt;length&gt; | 37.5 | No | Font size of the scrolling text. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.|
| font-weight | number&nbsp;\|&nbsp;string | normal | No | Font weight of the scrolling text. For details, see **font-weight** of the **[\<text> component](../arkui-js/js-components-basic-text.md#styles)**.|
| font-weight | number \| string | normal | No | Font weight of the scrolling text. For details, see **font-weight** of the **[\<text> component](../arkui-js/js-components-basic-text.md#styles)**.|
| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.|
......@@ -45,17 +45,17 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported.
| Name | Parameter | Description |
| ------------ | ---- | ---------------------------------------- |
| bounce(Rich) | - | Triggered when the marquee scrolls to the end. |
| finish(Rich) | - | Triggered when the marquee finishes the specified number of scrollings (value of the **loop** attribute). It can be triggered only when the **loop** attribute is set to a number greater than 0.|
| start(Rich) | - | Triggered when the marquee starts to scroll. |
| Name | Parameter | Description |
| ------ | ---- | ---------------------------------------- |
| bounce | - | Triggered when the marquee scrolls to the end. |
| finish | - | Triggered when the marquee finishes the specified number of scrollings (value of the **loop** attribute). It can be triggered only when the **loop** attribute is set to a number greater than 0.|
| start | - | Triggered when the marquee starts to scroll. |
## Methods
In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported.
| Name | Parameter | Description |
| Name | Parameter | Description |
| ----- | ---- | ----- |
| start | - | Starts scrolling.|
| stop | - | Stops scrolling.|
......@@ -65,72 +65,75 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
```html
<!-- xxx.hml -->
<div class="container">
<marquee id="customMarquee" class="customMarquee" scrollamount="{{scrollAmount}}" loop="{{loop}}"direction="{{marqueeDir}}"
onbounce="onMarqueeBounce" onstart="onMarqueeStart" onfinish="onMarqueeFinish">{{marqueeCustomData}}</marquee>
<div class="content">
<button class="controlButton" onclick="onStartClick">Start</button>
<button class="controlButton" onclick="onStopClick">Stop</button>
<div class="tutorial-page">
<div class="mymarquee">
<marquee style="color: {{color1}}" loop="{{loopval}}" scrollamount="{{scroll}}" direction="{{isleft}}" class="marqueetext"
id="testmarquee" onfinish="setfinish">
Life is a journey, not the destination.
</marquee>
</div>
<div style="width: 600px;height: 150px;flex-direction: row;justify-content: space-around;">
<button onclick="makestart" value="start"></button>
<button onclick="makestop" value="stop"></button>
</div>
</div>
```
```css
/* xxx.css */
.container {
.tutorial-page {
width: 750px;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #ffffff;
justify-content: center;
}
.customMarquee {
width: 100%;
height: 80px;
padding: 10px;
margin: 20px;
border: 4px solid #ff8888;
border-radius: 20px;
font-size: 40px;
color: #ff8888;
font-weight: bolder;
font-family: serif;
background-color: #ffdddd;
.marqueetext {
font-size: 37px;
}
.content {
flex-direction: row;
.mymarquee {
margin-top: 20px;
width:100%;
height: 100px;
margin-left: 50px;
margin-right: 50px;
border: 1px solid #dc0f27;
border-radius: 15px;
align-items: center;
}
.controlButton {
flex-grow: 1;
background-color: #F2F2F2;
text-color: #0D81F2;
button{
width: 200px;
height: 80px;
margin-top: 100px;
}
```
```js
// xxx.js
export default {
data: {
scrollAmount: 30,
loop: 3,
marqueeDir: 'left',
marqueeCustomData: 'Custom marquee',
},
onMarqueeBounce: function() {
console.log("onMarqueeBounce");
private: {
loopval: 1,
scroll: 8,
color1: 'red'
},
onMarqueeStart: function() {
console.log("onMarqueeStart");
onInit(){
},
onMarqueeFinish: function() {
console.log("onMarqueeFinish");
setfinish(e) {
this.loopval= this.loopval + 1,
this.r = Math.floor(Math.random()*255),
this.g = Math.floor(Math.random()*255),
this.b = Math.floor(Math.random()*255),
this.color1 = 'rgba('+ this.r +','+ this.g +','+ this.b +',0.8)',
this.$element('testmarquee').start(),
this.loopval= this.loopval - 1
},
onStartClick (evt) {
this.$element('customMarquee').start();
makestart(e) {
this.$element('testmarquee').start()
},
onStopClick (evt) {
this.$element('customMarquee').stop();
makestop(e) {
this.$element('testmarquee').stop()
}
}
```
![lite_bar](figures/lite_bar.gif)
![zh-cn_image_0000001176075554](figures/zh-cn_image_0000001176075554.gif)
......@@ -20,7 +20,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| ---- | ------ | ---- | ---- | ---------------------------------------- |
| type | string | text | No | Type of the scrollable selector, which cannot be changed dynamically. Available values are as follows:<br>- **text**: text selector.<br>- **time**: time selector.<br>- **date**: date selector.<br>- **datetime**: date and time selector.<br>- **multi-text**: multi-column text selector.|
Text selector (**type** is **text**)
### Text Selector
| Name | Type | Default Value | Mandatory | Description |
| --------------- | ------ | ---- | ---- | ---------------------------------------- |
......@@ -29,15 +29,15 @@ Text selector (**type** is **text**)
| indicatorprefix | string | - | No | Prefix field added when a value is specified for the text selector. |
| indicatorsuffix | string | - | No | Suffix field added when a value is specified for the text selector. |
Time selector (**type** is **time**)
### Time Selector
| Name | Type | Default Value | Mandatory | Description |
| ------------- | ------- | ----------------------------------- | ---- | ---------------------------------------- |
| containsecond | boolean | false | No | Whether seconds are contained. |
| selected | string | Current time | No | Default value of the time selector, in the format of HH:mm.<br>If seconds are contained, the format is HH:mm:ss.|
| hours | number | 24<sup>1-4</sup> | No | Time format used by the time selector. Available values are as follows:<br>- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.<br>- **24**: displayed in 24-hour format.<br>Since API version 5, the default value is the most commonly-used hour format in the current locale.|
| hours | number | 24<sup>1-4</sup><br>-<sup>5+</sup> | No | Time format used by the time selector. Available values are as follows:<br>- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.<br>- **24**: displayed in 24-hour format.<br>Since API version 5, the default value is the most commonly-used hour format in the current locale.|
Date selector (**type** is **date**)
### Date Selector
| Name | Type | Default Value | Mandatory | Description |
| ------------------ | ------------ | ---------- | ---- | ---------------------------------------- |
......@@ -47,16 +47,16 @@ Date selector (**type** is **date**)
| lunar<sup>5+</sup> | boolean | false | No | Whether the pop-up window displays the lunar calendar. |
| lunarswitch | boolean | false | No | Whether to display the lunar calendar switch in the date selector. When this switch is displayed, the user can switch between the lunar calendar and Gregorian calendar. Turn on the switch to display the lunar calendar, and turn off the switch to hide the lunar calendar.|
Date and time selector (**type** is **datetime**)
### Date and Time Selector
| Name | Type | Default Value | Mandatory | Description |
| ------------------ | ------- | ----------------------------------- | ---- | ---------------------------------------- |
| selected | string | Current date and time | No | Default value of the date and time selector. The value can be in the format of MM-DD-HH-mm or YYYY-MM-DD-HH-mm. If the year is not set, the current year is used by default. The value you set is the date selected by default in the pop-up window.|
| hours | number | 24<sup>1-4</sup> | No | Time format used by the date and time selector. Available values are as follows:<br>- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.<br>- **24**: displayed in 24-hour format.<br>Since API version 5, the default value is the most commonly-used hour format in the current locale.|
| hours | number | 24<sup>1-4</sup><br>-<sup>5+</sup> | No | Time format used by the date and time selector. Available values are as follows:<br>- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.<br>- **24**: displayed in 24-hour format.<br>Since API version 5, the default value is the most commonly-used hour format in the current locale.|
| lunar<sup>5+</sup> | boolean | false | No | Whether the pop-up window displays the lunar calendar. |
| lunarswitch | boolean | false | No | Whether to display the lunar calendar switch in the date and time selector. When this switch is displayed, the user can switch between the lunar calendar and Gregorian calendar. Turn on the switch to display the lunar calendar, and turn off the switch to hide the lunar calendar.|
Multi-column text selector (**type** is **multi-text**)
### Multi-Column Text Selector
| Name | Type | Default Value | Mandatory | Description |
| -------- | ------- | --------- | ---- | ---------------------------------------- |
......@@ -77,42 +77,42 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| selected-font-size | &lt;length&gt; | 20px | No | Font size of the selected item. The value is of the length type, in pixels. |
| disappear-color<sup>5+</sup> | &lt;color&gt; | \#ffffff | No | Font color of the items that gradually disappear. Disappearing items are the top option and bottom option of a column containing five options in total. |
| disappear-font-size<sup>5+</sup> | &lt;length&gt; | 14px | No | Font size of the items that gradually disappear. Disappearing items are the top option and bottom option of a column containing five options in total. |
| font-family | string | sans-serif | No | Font family of the selector, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.|
| font-family | string | sans-serif | No | Font family of the selector, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. |
## Events
The following events are supported.
Text selector (**type** is **text**)
### Text Selector
| Name | Parameter | Description |
| ------ | ---------------------------------------- | --------------- |
| change | {&nbsp;newValue:&nbsp;newValue,&nbsp;newSelected:&nbsp;newSelected&nbsp;} | Triggered when a value is specified for the text selector.|
| change | { newValue: newValue, newSelected: newSelected } | Triggered when a value is specified for the text selector.|
Time selector (**type** is **time**)
### Time Selector
| Name | Parameter | Description |
| ------ | ---------------------------------------- | ------------------------------- |
| change | {&nbsp;hour:&nbsp;hour,&nbsp;minute:&nbsp;minute,&nbsp;[second:second]} | Triggered when a value is specified for the time selector.<br>If seconds are contained, the value contains hour, minute, and second.|
| change | { hour: hour, minute: minute, [second:second]} | Triggered when a value is specified for the time selector.<br>If seconds are contained, the value contains hour, minute, and second.|
Date selector (**type** is **date**)
### Date Selector
| Name | Parameter | Description |
| ------ | ---------------------------------------- | --------------- |
| change | {&nbsp;year:year,&nbsp;month:month,&nbsp;day:day&nbsp;} | Triggered when a value is specified for the date selector.|
| change | { year:year, month:month, day:day } | Triggered when a value is specified for the date selector.|
Date and time selector (**type** is **datetime**)
### Date and Time Selector
| Name | Parameter | Description |
| ------ | ---------------------------------------- | ----------------- |
| change | {&nbsp;year:year,&nbsp;month:month,&nbsp;day:day,&nbsp;&nbsp;hour:hour,&nbsp;minute:minute&nbsp;} | Triggered when a value is specified for the date and time selector.|
| change | { year:year, month:month, day:day, hour:hour, minute:minute } | Triggered when a value is specified for the date and time selector.|
Multi-text selector (**type** is **multi-text**)
### Multi-Column Text Selector
| Name | Parameter | Description |
| ------------ | ---------------------------------------- | ---------------------------------------- |
| columnchange | {&nbsp;column:column,&nbsp;newValue:newValue,&nbsp;newSelected:newSelected&nbsp;} | Triggered when the value of a column in the multi-column selector changes. <br>**column**: column whose value has changed. <br>**newValue**: selected value. <br>**newSelected**: index of the selected value.|
| columnchange | { column:column, newValue:newValue, newSelected:newSelected } | Triggered when the value of a column in the multi-column selector changes. <br>**column**: column whose value has changed. <br>**newValue**: selected value. <br>**newSelected**: index of the selected value.|
## Methods
......@@ -121,67 +121,252 @@ Not supported
## Example
```html
<!-- xxx.hml -->
<div class="container" @swipe="handleSwipe">
<text class="title">
Selected: {{time}}
</text>
<picker-view class="time-picker" type="time" selected="{{defaultTime}}" @change="handleChange"></picker-view>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 454px;
height: 454px;
}
.title {
font-size: 30px;
text-align: center;
}
.time-picker {
width: 500px;
height: 400px;
margin-top: 20px;
}
```
```js
/* xxx.js */
export default {
data: {
defaultTime: "",
time: "",
},
onInit() {
this.defaultTime = this.now();
},
handleChange(data) {
this.time = this.concat(data.hour, data.minute);
},
now() {
const date = new Date();
const hours = date.getHours();
const minutes = date.getMinutes();
return this.concat(hours, minutes);
},
fill(value) {
return (value > 9 ? "" : "0") + value;
},
concat(hours, minutes) {
return `${this.fill(hours)}:${this.fill(minutes)}`;
},
}
```
![lite_bar-4](figures/lite_bar-4.png)
1. Text Selector
```html
<!-- xxx.hml -->
<div class="container">
<text class="title">
Selected value: {{value}} Selected index: {{index}}
</text>
<picker-view class="text-picker" type="text" range="{{options}}" selected="0" indicatorprefix="prefix" indicatorsuffix="suffix" @change="handleChange"></picker-view>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 454px;
height: 454px;
}
.title {
font-size: 30px;
text-align: center;
margin-top: 20px;
}
```
```js
/* xxx.js */
export default {
data: {
options: ['Option 1','Option 2','Option 3'],
value: "Option 1",
index: 0
},
handleChange(data) {
this.value = data.newValue;
this.index = data.newSelected;
},
}
```
![](figures/pickerview1.gif)
2. Time Selector
```html
<!-- xxx.hml -->
<div class="container">
<text class="title">
Selected: {{time}}
</text>
<picker-view class="time-picker" type="time" selected="{{defaultTime}}" @change="handleChange"></picker-view>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 454px;
height: 454px;
}
.title {
font-size: 30px;
text-align: center;
}
.time-picker {
width: 500px;
height: 400px;
margin-top: 20px;
}
```
```js
/* xxx.js */
export default {
data: {
defaultTime: "",
time: "",
},
onInit() {
this.defaultTime = this.now();
},
handleChange(data) {
this.time = this.concat(data.hour, data.minute);
},
now() {
const date = new Date();
const hours = date.getHours();
const minutes = date.getMinutes();
return this.concat(hours, minutes);
},
fill(value) {
return (value > 9 ? "" : "0") + value;
},
concat(hours, minutes) {
return `${this.fill(hours)}:${this.fill(minutes)}`;
},
}
```
![](figures/pickerview2.gif)
3. Date Selector
```html
<!-- xxx.hml -->
<div class="container">
<text class="title">
Selected: {{time}}
</text>
<picker-view class="time-picker" type="time" selected="{{defaultTime}}" @change="handleChange"></picker-view>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 454px;
height: 454px;
}
.title {
font-size: 30px;
text-align: center;
margin-top: 20px;
}
.date-picker {
width: 500px;
height: 400px;
margin-top: 50px;
}
```
```js
/* xxx.js */
export default {
data: {
date: "",
},
handleChange(data) {
this.date = data.year + "" + data.month + "" + data.day + "";
},
}
```
4. Date and Time Selector
```html
<!-- xxx.hml -->
<div class="container">
<text class="title">
Selected: {{datetime}}
</text>
<picker-view class="date-picker" type="datetime" hours="24" lunarswitch="true" @change="handleChange"></picker-view>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 500px;
height: 454px;
}
.title {
font-size: 30px;
text-align: center;
margin-top: 20px;
}
.date-picker {
width: 500px;
height: 400px;
margin-top: 50px;
}
```
```js
/* xxx.js */
export default {
data: {
datetime: "",
},
handleChange(data) {
this.datetime = data.year + "" + data.month + "" + data.day + "" + data.hour + "" + data.minute + "";
},
}
```
5. Multi-Column Text Selector
```html
<!-- xxx.hml -->
<div class="container">
<text class="title">
Selected: {{ value }}
</text>
<picker-view class="multitype-picker" type="multi-text" columns="3" range="{{ multitext }}" @columnchange="handleChange"></picker-view>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 500px;
height: 454px;
}
.title {
font-size: 30px;
text-align: center;
margin-top: 20px;
}
```
```js
/* xxx.js */
export default {
data: {
multitext: [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
],
value: ""
},
handleChange(data) {
this.value = "Column: " + data.column + "," + "Value: " + data.newValue + ", Index:" + data.newSelected;
},
}
```
![](figures/pickerview5.gif)
......@@ -58,7 +58,7 @@ When **type** is set to **time**, a time selector is used.
| Name | Type | Default Value | Mandatory | Description |
| ------------- | ------- | ----------------------------------- | ---- | ---------------------------------------- |
| containsecond | boolean | false | No | Whether seconds are contained. |
| selected | string | Current time | No | Default value of the time selector, in format of HH:mm. If seconds are contained, the format is HH:mm:ss. |
| selected | string | Current time | No | Default value of the time selector, in format of HH:mm. If seconds are contained, the format is HH:mm:ss.<br> |
| value | string | - | No | Value of the time selector. |
| hours | number | 24<sup>1-4</sup><br>-<sup>5+</sup> | No | Time format used by the time selector. Available values are as follows:<br>- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.<br>- **24**: displayed in 24-hour format.<br>Since API version 5, the default value is the most commonly-used hour format in the current locale.|
......@@ -166,52 +166,59 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
```html
<!-- xxx.hml -->
<div class="container">
<select @change="selectChange">
<select @change="selectChange">
<option value="{{ item }}" for="item in selectList">
{{ item }}
</option>
</select>
<picker id="picker0" type="text" value="{{textvalue}}" selected="{{textselect}}" range="{{rangetext}}" onchange="textonchange"
oncancel="textoncancel" class="pickertext"></picker>
<picker id="picker1" type="date" value="{{datevalue}}" start="2002-2-5" end="2030-6-5" selected="{{dateselect}}" lunarswitch="true"
onchange="dateonchange" oncancel="dateoncancel" class="pickerdate" show="false"></picker>
<picker id="picker2" type="time" value="{{timevalue}}" containsecond="{{containsecond}}" selected="{{timeselect}}" hours="12"
onchange="timeonchange" oncancel="timeoncancel" class="pickertime" show="false"></picker>
<picker id="picker3" type="datetime" value="{{datetimevalue}}" selected="{{datetimeselect}}" hours="24" lunarswitch="true"
onchange="datetimeonchange" oncancel="datetimeoncancel" class="pickerdatetime" show="false"></picker>
<picker id="picker4" type="multi-text" value="{{multitextvalue}}" columns="3" range="{{multitext}}" selected="{{multitextselect}}"
onchange="multitextonchange" oncancel="multitextoncancel" class="pickermuitl" show="false"></picker>
</select>
<picker id="picker0" type="text" value="{{ textvalue }}" selected="{{ textselect }}" range="{{ rangetext }}"
onchange="textonchange"
oncancel="textoncancel" class="pickertext" show="false"></picker>
<picker id="picker1" type="date" value="{{ datevalue }}" start="2002-2-5" end="2030-6-5" selected="{{ dateselect }}"
lunarswitch="true"
onchange="dateonchange" oncancel="dateoncancel" class="pickerdate" show="false"></picker>
<picker id="picker2" type="time" value="{{ timevalue }}" containsecond="{{ containsecond }}"
selected="{{ timeselect }}" hours="12"
onchange="timeonchange" oncancel="timeoncancel" class="pickertime" show="false"></picker>
<picker id="picker3" type="datetime" value="{{ datetimevalue }}" selected="{{ datetimeselect }}" hours="24"
lunarswitch="true"
onchange="datetimeonchange" oncancel="datetimeoncancel" class="pickerdatetime" show="false"></picker>
<picker id="picker4" type="multi-text" value="{{ multitextvalue }}" columns="3" range="{{ multitext }}"
selected="{{ multitextselect }}"
onchange="multitextonchange" oncancel="multitextoncancel" class="pickermuitl" show="false"></picker>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
.container {
flex-direction: column;
justify-content: center;
align-items: center;
}
picker{
width:60%;
height:80px;
border-radius:20px;
text-color:white;
font-size:15px;
background-color:#4747e3;
margin-left:20%;
picker {
width: 60%;
height: 80px;
border-radius: 20px;
text-color: white;
font-size: 15px;
background-color: #4747e3;
margin-left: 20%;
}
select{
background-color: #efecec;
height: 50px;
width: 60%;
margin-left: 20%;
margin-top: 300px;
margin-bottom: 50px;
font-size: 22px;
select {
background-color: #efecec;
height: 50px;
width: 60%;
margin-left: 20%;
margin-top: 300px;
margin-bottom: 50px;
font-size: 22px;
}
```
......@@ -219,72 +226,96 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
// xxx.js
import router from '@system.router';
import prompt from '@system.prompt';
export default {
data: {
selectList:["text","data","time","datetime","multitext"],
rangetext:['15', "20", "25"],
multitext:[["a", "b", "c"], ["e", "f", "g"], ["h", "i"], ["k", "l", "m"]],
textvalue:'default textvalue',
datevalue:'default datevalue',
timevalue:'default timevalue',
datetimevalue:'default datetimevalue',
multitextvalue:'default multitextvalue',
containsecond:true,
multitextselect:[1,2,0],
datetimeselect:'2012-5-6-11-25',
timeselect:'11:22:30',
dateselect:'2021-3-2',
textselect:'2'
},
selectChange(e){
for(let i = 0;i<this.selectList.length;i++){
if(e.newValue == this.selectList[i]){
this.$element("picker"+i).show();
data: {
selectList: ["text", "data", "time", "datetime", "multitext"],
rangetext: ['15', "20", "25"],
multitext: [["a", "b", "c"], ["e", "f", "g"], ["h", "i"], ["k", "l", "m"]],
textvalue: 'default textvalue',
datevalue: 'default datevalue',
timevalue: 'default timevalue',
datetimevalue: 'default datetimevalue',
multitextvalue: 'default multitextvalue',
containsecond: true,
multitextselect: [1, 2, 0],
datetimeselect: '2012-5-6-11-25',
timeselect: '11:22:30',
dateselect: '2021-3-2',
textselect: '2'
},
selectChange(e) {
for (let i = 0;i < this.selectList.length; i++) {
if (e.newValue == this.selectList[i]) {
this.$element("picker" + i).show();
}
}
},
textonchange(e) {
this.textvalue = e.newValue;
prompt.showToast({ message:"text:"+e.newValue+",newSelected:"+e.newSelected })
},
textoncancel(e) {
prompt.showToast({ message:"text: textoncancel" })
},
dateonchange(e) {
this.datevalue = e.year + "-" + e.month + "-" + e.day;
prompt.showToast({ message:"date:"+e.year+"-"+(e.month+1)+"-"+e.day })
},
dateoncancel() {
prompt.showToast({ message:"date: dateoncancel" })
},
timeonchange(e) {
if(this.containsecond){
this.timevalue=e.hour+":"+e.minute+":"+e.second;
prompt.showToast({ message:"Time:" + e.hour + ":" + e.minute + ":" + e.second })
} else {
this.timevalue=e.hour+":"+e.minute;
prompt.showToast({ message:"Time:" + e.hour + ":" + e.minute })
}},
timeoncancel() {
prompt.showToast({ message:"timeoncancel" })
},
datetimeonchange(e) {
this.datetimevalue=e.year+"-"+e.month+"-"+e.day+" "+e.hour+":"+e.minute;
prompt.showToast({ message:"Time:"+(e.month+1)+"-"+e.day+" "+e.hour+":"+e.minute })
},
datetimeoncancel() {
prompt.showToast({ message:"datetimeoncancel" })
},
multitextonchange(e) {
this.multitextvalue=e.newValue;
prompt.showToast({ message:"Multi-column text change" + e.newValue })
},
multitextoncancel() {
prompt.showToast({ message:"multitextoncancel" })
},
popup_picker() {
this.$element("picker_text").show();
},
textonchange(e) {
this.textvalue = e.newValue;
prompt.showToast({
message: "text:" + e.newValue + ",newSelected:" + e.newSelected
})
},
textoncancel(e) {
prompt.showToast({
message: "text: textoncancel"
})
},
dateonchange(e) {
this.datevalue = e.year + "-" + e.month + "-" + e.day;
prompt.showToast({
message: "date:" + e.year + "-" + (e.month + 1) + "-" + e.day
})
},
dateoncancel() {
prompt.showToast({
message: "date: dateoncancel"
})
},
timeonchange(e) {
if (this.containsecond) {
this.timevalue = e.hour + ":" + e.minute + ":" + e.second;
prompt.showToast({
message: "Time:" + e.hour + ":" + e.minute + ":" + e.second
})
} else {
this.timevalue = e.hour + ":" + e.minute;
prompt.showToast({
message: "Time:" + e.hour + ":" + e.minute
})
}
},
timeoncancel() {
prompt.showToast({
message: "timeoncancel"
})
},
datetimeonchange(e) {
this.datetimevalue = e.year + "-" + e.month + "-" + e.day + " " + e.hour + ":" + e.minute;
prompt.showToast({
message: "Time:" + (e.month + 1) + "-" + e.day + " " + e.hour + ":" + e.minute
})
},
datetimeoncancel() {
prompt.showToast({
message: "datetimeoncancel"
})
},
multitextonchange(e) {
this.multitextvalue = e.newValue;
prompt.showToast({
message: "Multi-column text change" + e.newValue
})
},
multitextoncancel() {
prompt.showToast({
message: "multitextoncancel"
})
},
popup_picker() {
this.$element("picker_text").show();
},
}
```
......
# qrcode
The **\<qrcode>** component is used to generate and display a QR code.
> **NOTE**
>
> This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version.
The **\<qrcode>** component is used to generate and display a QR code.
## Required Permissions
......@@ -24,7 +23,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| Name | Type | Default Value | Mandatory | Description |
| ----- | ------ | ---- | ---- | ---------------------------------------- |
| value | string | - | Yes | Content used to generate the QR code. |
| type | string | rect | No | QR code type. Available values are as follows:<br>- **rect**: rectangular QR code<br>- **circle**: round QR code|
| type | string | rect | No | QR code type. Available values are as follows:<br>- **rect**: rectangular QR code.<br>- **circle**: round QR code.|
## Styles
......@@ -60,8 +59,6 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support
<div class="container">
<qrcode value="{{qr_value}}" type="{{qr_type}}"
style="color: {{qr_col}};background-color: {{qr_bcol}};width: {{qr_size}};height: {{qr_size}};margin-bottom: 70px;"></qrcode>
<text class="txt">Value</text>
<input onChange="setValue">123</input>
<text class="txt">Type</text>
<switch showtext="true" checked="true" texton="rect" textoff="circle" onchange="settype"></switch>
<text class="txt">Color</text>
......@@ -98,7 +95,6 @@ select{
/* index.js */
export default {
data: {
qr_value:'',
qr_type: 'rect',
qr_size: '300px',
qr_col: '#87ceeb',
......@@ -113,9 +109,6 @@ export default {
this.qr_type = 'circle'
}
},
setvalue(e) {
this.qr_value = e.newValue
},
setcol(e) {
this.qr_col = e.newValue
},
......
# search
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Search>** component provides an input area for users to search.
The **\<search>** component provides an input area for users to search.
## Child Components
......@@ -42,7 +41,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| font-size | &lt;length&gt; | 16px | No | Font size of the search box. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.|
| placeholder-color | &lt;color&gt; | \#99000000<br>| No | Color of the hint text. |
| font-weight | number \| string | normal | No | Font weight. For details, see **font-weight** of the **[\<text>](../arkui-js/js-components-basic-text.md#styles)** component.|
| font-weight | number \| string | normal | No | Font weight. For details, see [font-weight](../arkui-js/js-components-basic-text.md#styles) of the **\<text>** component.|
| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.|
| caret-color<sup>6+</sup> | &lt;color&gt; | - | No | Color of the caret. |
......
......@@ -2,9 +2,9 @@
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Slider>** 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.
## Child Components
......@@ -22,7 +22,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| max | number | 100 | No| Maximum value of the slider.|
| step | number | 1 | No| Step of each slide.|
| value | number | 0 | No| Initial value of the slider.|
| mode<sup>5+</sup> | string | outset | No| Slider style. Available values are as follows:<br>- **outset**: The slider is on the sliding bar.<br>- **inset**: The slider is inside the sliding bar.|
| mode<sup>5+</sup> | string | outset | No| Slider style. Available values are as follows:<br>- **outset**: The slider is on the slider track.<br>- **inset**: The slider is in the slider track.|
| showsteps<sup>5+</sup> | boolean | false | No| Whether to display slider scales.|
| showtips<sup>5+</sup> | boolean | false | No| Whether a tooltip is displayed to show the percentage value on the slider.|
......@@ -51,7 +51,7 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md
| Attribute| Type| Description|
| -------- | -------- | -------- |
| value<sup>5+</sup> | number | Current value of the slider.|
| mode<sup>5+</sup> | string | Type of the change event. Available values are as follows:<br>- **start**: The **value** starts to change.<br>- **move**: The **value** is changing with users' dragging.<br>- **end**: The **value** stops changing.|
| mode<sup>5+</sup> | string | Type of the change event. Available values are as follows:<br>- **start**: The **value** starts to change.<br>- **move**: The **value** is changing with users' dragging.<br>- **end**: The **value** stops changing.<br>- **click**: The **value** changes upon a touch on the slider.|
## Example
......@@ -59,48 +59,23 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md
```html
<!-- xxx.hml -->
<div class="container">
<text>slider start value is {{startValue}}</text>
<text>slider current value is {{currentValue}}</text>
<text>slider end value is {{endValue}}</text>
<slider min="0" max="100" value="{{value}}" onchange="setvalue" ></slider>
<slider min="0" max="100" value="{{ value }}" mode="outset" showtips="true"></slider>
<slider class="" min="0" max="100" value="{{ value }}" step="20" mode="inset" showtips="true"></slider>
<slider class="" min="0" max="100" value="{{ value }}" showsteps="true" step="20" mode="inset" showtips="false"></slider>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
flex-direction: column;
justify-content: center;
align-items: center;
}
```
```js
// xxx.js
export default {
data: {
value: 0,
startValue: 0,
currentValue: 0,
endValue: 0,
},
setvalue(e) {
if (e.mode == "start") {
this.value = e.value;
this.startValue = e.value;
} else if (e.mode == "move") {
this.value = e.value;
this.currentValue = e.value;
} else if (e.mode == "end") {
this.value = e.value;
this.endValue = e.value;
} else if (e.mode == "click) {
this.value = e.value;
this.currentValue = e.value;
}
}
slider{
margin-top: 100px;
}
```
![slider](figures/slider.png)
......@@ -30,18 +30,20 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
## Styles
In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported.
| Name | Type | Default Value | Mandatory | Description |
| ------------------- | -------------------------- | ---------- | ---- | ---------------------------------------- |
| texton-color(Rich) | &lt;color&gt; | \#000000 | No | Text color displayed when the component is checked. |
| textoff-color(Rich) | &lt;color&gt; | \#000000 | No | Text color displayed when the component is not checked. |
| text-padding(Rich) | number | 0px | No | Distance between the two sides of the longest text in **texton** and **textoff** and the border of the slider. |
| font-size(Rich) | &lt;length&gt; | - | No | Font size. This attribute is available only when **texton** and **textoff** are set. |
| allow-scale(Rich) | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.|
| font-style(Rich) | string | normal | No | Font style. This attribute is available only when **texton** and **textoff** are set. For details, see **font-style** of the [**\<text>**](../arkui-js/js-components-basic-text.md#styles) component.|
| font-weight(Rich) | number \| string | normal | No | Font weight. This attribute is available only when **texton** and **textoff** are set. For details, see **font-weight** of the [**\<text>**](../arkui-js/js-components-basic-text.md#styles) component.|
| font-family(Rich) | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. This attribute is available only when **texton** and **textoff** are set.|
| Name | Type | Default Value | Mandatory | Description |
| ------------- | -------------------------- | ---------- | ---- | ---------------------------------------- |
| texton-color | &lt;color&gt; | \#000000 | No | Text color displayed when the component is checked. This attribute is available only when **texton** and **textoff** are set. |
| textoff-color | &lt;color&gt; | \#000000 | No | Text color displayed when the component is not checked. This attribute is available only when **texton** and **textoff** are set. |
| text-padding | number | 0px | No | Distance between the two sides of the longest text in **texton** and **textoff** and the border of the slider. |
| font-size | &lt;length&gt; | - | No | Font size. This attribute is available only when **texton** and **textoff** are set. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.|
| font-style | string | normal | No | Font style. This attribute is available only when **texton** and **textoff** are set. For details, see [font-style](../arkui-js/js-components-basic-text.md#styles) of the **\<text>** component.|
| font-weight | number \| string | normal | No | Font weight. This attribute is available only when **texton** and **textoff** are set. For details, see [font-weight](../arkui-js/js-components-basic-text.md#styles) of the **\<text>** component.|
| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. This attribute is available only when **texton** and **textoff** are set.|
## Events
......@@ -61,45 +63,63 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support
```html
<!-- xxx.hml -->
<div class="container">
<switch showtext="true" texton="On" textoff="Off" checked="true" @change="switchChange">
</switch>
<switch @change="normalswitchChange">
</switch>
<switch class="switch" showtext="true" texton="On" textoff="Off" @change="switchChange">
</switch>
<switch class="switch text" showtext="true" texton="Switch on" textoff="Switch off" checked="true" @change="switchChange">
</switch>
</div>
```
```css
/* xxx.css */
.container {
display: flex;
justify-content: center;
align-items: center;
display: flex;
justify-content: center;
align-items: center;
}
.switch {
texton-color: red;
textoff-color: forestgreen;
}
switch{
texton-color:#002aff;
textoff-color:silver;
text-padding:20px;
.text {
text-padding: 20px;
font-size: 30px;
font-weight: 700;
}
```
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
data: {
title: 'World'
},
switchChange(e){
console.log(e.checked);
if(e.checked){
prompt.showToast({
message: "Switch on."
});
}else{
prompt.showToast({
message: "Switch off."
});
data: {
title: 'World'
},
switchChange(e) {
if (e.checked) {
promptAction.showToast({
message: "Switch on."
});
} else {
promptAction.showToast({
message: "Switch off."
});
}
},
normalswitchChange(e) {
if (e.checked) {
promptAction.showToast({
message: "switch on"
});
} else {
promptAction.showToast({
message: "switch off"
});
}
}
}
}
```
![en-us_image_0000001152862510](figures/en-us_image_0000001152862510.gif)
![en-us_image_0000001152862510](figures/switch.gif)
......@@ -15,7 +15,7 @@ None
## Child Components
Only the **[\<span>](../arkui-js/js-components-basic-span.md)** component is supported.
The **[\<span>](../arkui-js/js-components-basic-span.md)** child component is supported.
## Attributes
......@@ -34,19 +34,19 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>For details about how to make the configuration take effect dynamically, see the **config-changes** attribute in the **config.json** file.|
| letter-spacing | &lt;length&gt; | 0px | No | Character spacing (px). |
| word-spacing<sup>7+</sup> | &lt;length&gt; \| &lt;percentage&gt; \| string | normal | No | Spacing between texts. If the input is a string, the options are as follows:<br>**normal**: default spacing.|
| font-style | string | normal | No | Font style. Available values are as follows:<br>- **normal**: standard font style<br>- **italic**: italic font style|
| font-weight | number \| string | normal | No | Font width. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a larger font width. The value of the number type must be an integer multiple of 100.<br>The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.|
| font-style | string | normal | No | Font style. Available values are as follows:<br>- **normal**: standard font style.<br>- **italic**: italic font style.|
| font-weight | number \| string | normal | No | Font weight. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a heavier font weight. The value of the number type must be an integer multiple of 100.<br>The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.|
| text-decoration | string | none | No | Text decoration. Available values are as follows:<br>- **underline**: An underline is used.<br>- **line-through**: A strikethrough is used.<br>- **none**: The standard text is used.|
| text-decoration-color<sup>7+</sup> | &lt;color&gt; | - | No | Color of the text decoration. |
| text-align | string | start<br> | No | Text alignment mode. Available values are as follows:<br>- **left**: The text is left-aligned.<br>- **center**: The text is center-aligned.<br>- **right**: The text is right-aligned.<br>- **start**: The text is aligned with the direction in which the text is written.<br>- **end**: The text is aligned with the opposite direction in which the text is written.<br>If the text width is not specified, the alignment effect may not be obvious when the text width is the same as the width of the parent container.|
| line-height | &lt;length&gt; \| &lt;percentage&gt;<sup>7+</sup> \| string<sup>7+</sup> | 0px<sup>1-6</sup><br>normal<sup>7+</sup> | No | Text line height. When this parameter is set to **0px**, the text line height is not limited and the font size is adaptive. The value of the string type is as follows:<br>**normal**<sup>7+</sup>: default line height |
| line-height | &lt;length&gt; \| &lt;percentage&gt;<sup>7+</sup> \| string<sup>7+</sup> | 0px<sup>1-6</sup><br>normal<sup>7+</sup> | No | Text line height. When this parameter is set to **0px**, the text line height is not limited and the font size is adaptive. The value of the string type is as follows:<br>**normal**<sup>7+</sup>: default line height|
| text-overflow | string | clip | No | Display mode when the text is too long. This style takes effect when the maximum number of lines is specified. Available values are as follows:<br>- **clip**: The text is clipped and displayed based on the size of the parent container.<br>- **ellipsis**: The text is displayed based on the size of the parent container. The text that cannot be displayed is replaced with ellipsis. This style must be used together with **max-lines**.|
| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.|
| max-lines | number \| string<sup>7+</sup> | - | No | Maximum number of text lines. The value of the string type is as follows:<br>- **auto**<sup>7+</sup>: The number of text lines adapts to the container height. |
| max-lines | number \| string<sup>7+</sup> | - | No | Maximum number of text lines. The value of the string type is as follows:<br>- **auto**<sup>7+</sup>: The number of text lines adapts to the container height.|
| min-font-size | &lt;length&gt; | - | No | Minimum font size in the text. This style must be used together with **max-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.|
| max-font-size | &lt;length&gt; | - | No | Maximum font size in the text. This style must be used together with **min-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.|
| font-size-step | &lt;length&gt; | 1px | No | Step for dynamically adjusting the font size in the text. The minimum and maximum font sizes must be set. |
| prefer-font-sizes | &lt;array&gt; | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.<br>Example values: **12px,14px,16px**|
| prefer-font-sizes | &lt;array&gt; | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.<br>Example: prefer-font-sizes: 12px,14px,16px|
| word-break<sup>6+</sup> | string | normal | No | Text line breaking mode. The options are as follows:<br>- **normal**: Allows text line breaks between words as appropriate to the relevant language writing systems. This is the default mode.<br>- **break-all**: Allows text line breaks between any characters for writing systems other than Chinese, Japanese, and Korean.<br>- **break-word**: Works in the same way as **break-all**, except that it does not break unbreakable words.|
| text-indent<sup>7+</sup> | &lt;length&gt; | - | No | Indentation of the first line. |
| white-space<sup>7+</sup> | string | pre | No | Mode for processing blanks in the component. The options are as follows:<br>- **normal**: All spaces, carriage returns, and tabs are combined into one space, and the text is automatically wrapped.<br>- **nowrap**: All spaces, carriage returns, and tabs are combined into one space, and the text is not wrapped.<br>- **pre**: All contents are output as-is.<br>- **pre-wrap**: All contents are output as-is with line breaks.<br>- **pre-line**: All spaces and tabs are combined into one space, the carriage return remains unchanged, and the text is wrapped.|
......@@ -76,84 +76,65 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support
## Example
1.
```html
<!-- xxx.hml -->
<div class="container">
<div class="content">
<text class="title">
Hello {{ title }}
</text>
</div>
<text class="title">default text</text>
<text class="title textcolor">hello world with color</text>
<text class="title textsize">hello world with font-size</text>
<text class="title textletterspacing">hello world with letter-spacing</text>
<text class="title textwordspacing">hello world with word-spacing</text>
<text class="title textstyle">hello world with italic</text>
<text class="title textweight">hello world with font-weight</text>
<text class="title textdecoration1">hello world with underline</text>
<text class="title textdecoration2">hello world with line-through</text>
<text class="title textalign">hello world with text-align:right</text>
</div>
```
```css
/* xxx.css */
.container {
display: flex;
justify-content: center;
align-items: center;
}
.content{
width: 400px;
height: 400px;
border: 20px;
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
}
.title {
font-size: 80px;
text-align: center;
width: 400px;
height: 400px;
text-align: center;
width: 800px;
height: 60px;
}
```
```js
// xxx.js
export default {
data: {
title: 'World'
}
.textcolor {
color: indianred;
}
```
![3](figures/3.png)
```html
<!-- xxx.hml -->
<div class="container">
<text class="text1">
This is a passage
</text>
<text class="text2">
This is a passage
</text>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
align-items: center;
background-color: #F1F3F5;
justify-content: center;
.textsize {
font-size: 40px;
}
.textletterspacing {
letter-spacing: -3px;
}
.text1{
word-spacing: 10px;
adapt-height: true;
.textwordspacing {
word-spacing: 20px;
}
.text2{
width: 200px;
max-lines: 1;
text-overflow: ellipsis;
text-valign: middle;
line-height: 40px;
text-decoration: underline;
text-decoration-color: red;
text-indent: 20px;
white-space: pre;
.textstyle {
font-style: italic;
}
.textweight {
font-weight: 700;
}
.textdecoration1 {
text-decoration: underline;
}
.textdecoration2 {
text-decoration: line-through;
text-decoration-color: red;
}
.textalign {
text-align: right;
}
```
![2](figures/2.png)
![en-us_image_0000001167823076](figures/text.png)
......@@ -11,7 +11,7 @@ The **\<canvas>** component is used for customizing drawings.
None
## Child Component
## Child Components
Not supported
......@@ -38,7 +38,7 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
### getContext
getContext(type: '2d', options?: ContextAttrOptions): CanvasRendering2dContext
getContext(type: '2d', options?: ContextAttrOptions): CanvasRenderingContext2D
Obtains the canvas drawing context. This API cannot be called in **onInit** or **onReady**.
......@@ -49,7 +49,7 @@ Obtains the canvas drawing context. This API cannot be called in **onInit** or *
| type | string | Yes | Object type. The value is set to **'2d'**, indicating that a 2D drawing object is returned. This object can be used to draw rectangles, texts, and images on the canvas component.|
| options<sup>6+</sup> | ContextAttrOptions | No | Whether to enable anti-aliasing. By default, anti-aliasing is disabled. |
**Table 1** ContextAttrOptions
**Table 1** ContextAttrOptions
| Name | Type | Description |
| --------- | ------- | ------------------- |
......@@ -59,7 +59,7 @@ Obtains the canvas drawing context. This API cannot be called in **onInit** or *
| Type | Description |
| ---------------------------------------- | -------------------- |
| [CanvasRenderingContext2D](../arkui-js/js-components-canvas-canvasrenderingcontext2d.md) | 2D drawing object, which can be used to draw rectangles, images, and texts, on the canvas component. |
| [CanvasRenderingContext2D](../arkui-js/js-components-canvas-canvasrenderingcontext2d.md) | 2D drawing object, which can be used to draw rectangles, images, and texts on the canvas component.|
### toDataURL<sup>6+</sup>
......
......@@ -25,19 +25,21 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 500px; height: 500px; background-color: #ffff00;"></canvas>
<input type="button" style="width: 180px; height: 60px;" value="fillStyle"onclick="handleClick" />
</div>
```
```js
// xxx.js
export default {
handleClick() {
onShow() {
const el =this.$refs.canvas;
const ctx =el.getContext('2d');
const gradient = ctx.createLinearGradient(0,0,100,0);
gradient.addColorStop(0,'#00ffff');
gradient.addColorStop(1,'#ffff00');
const ctx = el.getContext('2d');
const gradient = ctx.createLinearGradient(50,0,300,100);
gradient.addColorStop(0.0, 'red')
gradient.addColorStop(0.5, 'white')
gradient.addColorStop(1.0, 'green')
ctx.fillStyle = gradient
ctx.fillRect(0, 0, 300, 300)
}
}
```
......
......@@ -2,7 +2,7 @@
> **NOTE**
>
> Supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
**CanvasRenderingContext2D** allows you to draw rectangles, text, images, and other objects on a canvas.
......@@ -426,9 +426,9 @@ export default {
}
```
![en-us_image_0000001213192781](figures/en-us_image_0000001213192781.png)
![en-us_image_0000001213192781](figures/en-us_image_0000001213192781.png)
In the above example, the blue rectangle represents the new drawing, and the red rectangle represents the existing drawing.
In the above example, the blue rectangle represents the new drawing, and the red rectangle represents the existing drawing.
### shadowBlur
......@@ -585,7 +585,7 @@ Fills a rectangle on the canvas.
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px; "></canvas>
<canvas ref="canvas" style="width: 500px; height: 500px; "></canvas>
</div>
```
......@@ -621,7 +621,7 @@ Clears the content in a rectangle on the canvas.
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px;"></canvas>
<canvas ref="canvas" style="width: 500px; height: 500px;"></canvas>
</div>
```
......@@ -984,7 +984,7 @@ Creates a pattern for image filling based on a specified source image and repeti
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px;"></canvas>
<canvas ref="canvas" style="width: 1000px; height: 1000px;"></canvas>
</div>
```
......@@ -998,7 +998,7 @@ Creates a pattern for image filling based on a specified source image and repeti
img.src = 'common/images/example.jpg';
var pat = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pat;
ctx.fillRect(0, 0, 20, 20);
ctx.fillRect(0, 0, 500, 500);
}
}
```
......@@ -1429,7 +1429,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para
setTransform(scaleX: number, skewX: number, skewY: number, scale: number, translateX: number, translateY: number): void
Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** function.
Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** API.
**Parameters**
......@@ -1574,7 +1574,7 @@ Draws an image on the canvas.
```html
<!-- xxx.hml -->
<div>
<canvas style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<canvas ref="canvas" style="width: 500px; height: 500px; background-color: #ffff00;"></canvas>
</div>
```
......@@ -1582,11 +1582,11 @@ Draws an image on the canvas.
//xxx.js
export default {
onShow() {
var test = this.$element('drawImage');
var test = this.$refs.canvas;
var ctx = test.getContext('2d');
var img = new Image();
img.src = 'common/image/test.jpg';
ctx.drawImage(img, 50, 80, 80, 80);
ctx.drawImage(img, 0, 0, 200, 200, 10, 10, 200, 200);
}
}
```
......
......@@ -65,7 +65,7 @@ Sets the path transformation matrix.
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<canvas ref="canvas" style="width: 300px; height: 250px; background-color: #ffff00;"></canvas>
</div>
```
......@@ -95,7 +95,7 @@ Moves the current point of the path back to the start point of the path, and dra
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<canvas ref="canvas" style="width: 500px; height: 500px; background-color: #ffff00;"></canvas>
</div>
```
......@@ -223,7 +223,7 @@ Draws a cubic bezier curve on the canvas.
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<canvas ref="canvas" style="width: 300px; height: 250px; background-color: #ffff00;"></canvas>
</div>
```
......@@ -264,7 +264,7 @@ Draws a quadratic curve on the canvas.
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<canvas ref="canvas" style="width: 300px; height: 250px; background-color: #ffff00;"></canvas>
</div>
```
......@@ -307,7 +307,7 @@ Draws an arc on the canvas.
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<canvas ref="canvas" style="width: 300px; height: 250px; background-color: #ffff00;"></canvas>
</div>
```
......@@ -348,7 +348,7 @@ Draws an arc based on the radius and points on the arc.
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<canvas ref="canvas" style="width: 300px; height: 250px; background-color: #ffff00;"></canvas>
</div>
```
......
......@@ -11,14 +11,14 @@
| Name | Type | Default Value | Description |
| ------- | ------ | ---- | ---------------------------------------- |
| shareid | string | - | Used for the transition of shared elements, which takes effect only when this attribute is set. **\<list-item>**, **\<image>**, **\<text>**, **\<button>**, and **\<label>** components are supported for the transition of shared elements. |
| shareid | string | - | Used for the transition of shared elements, which takes effect only when this attribute is set. **\<list-item>**, **\<image>**, **\<text>**, **\<button>**, and **\<label>** components are supported for the transition of shared elements.|
### Styles
| Name | Type | Default Value | Description |
| --------------------------------- | ------ | -------- | ---------------------------------------- |
| shared-transition-effect | string | exchange | Entry style of a shared element during transition.<br>-&nbsp;**exchange** (default): The source page element is moved to the position of the target page element and is zoomed in or out properly.<br>-&nbsp;**static**: The position of the target page element remains unchanged. You can configure the opacity animation. Currently, only the static effect configured on the target page takes effect.|
| shared-transition-effect | string | exchange | Entry style of a shared element during transition.<br>- **exchange** (default): The source page element is moved to the position of the target page element and is zoomed in or out properly.<br>- **static**: The position of the target page element remains unchanged. You can configure the opacity animation. Currently, only the static effect configured on the target page takes effect.|
| shared-transition-name | string | - | During the transition, the style configured on the target page takes effect preferentially. This style is used to configure the animation effect of shared elements. The animation effect is an animation sequence defined by **@keyframes** supporting transform and opacity animations. If the effect of shared elements conflicts with the custom animation, the latter is used.|
| shared-transition-timing-function | string | friction | During the transition, the style configured on the target page takes effect preferentially. This style defines the difference curve during the transition of shared elements. If it is not configured, the friction curve is used.|
......@@ -52,7 +52,7 @@ In the example below, where **PageA** jumps to **PageB**, the shared element is
<image src="item.jpg" shareid="shareImage" onclick="jump" class="shared-transition-style"></image>
</list-item>
<list-item>
<text onclick="jump">Click on picture to Jump to the details</text>
<text onclick="jump">Click on picture to jump to the details</text>
</list-item>
</list>
</div>
......@@ -60,12 +60,12 @@ In the example below, where **PageA** jumps to **PageB**, the shared element is
```js
// xxx.js
import router from '@system.router';
import router from '@ohos.router';
export default {
jump() {
router.push({
// The path must be the same as that in the config.json file.
uri: 'pages/detailpage',
url: 'pages/detailpage',
});
},
}
......@@ -93,7 +93,7 @@ export default {
```js
// xxx.js
import router from '@system.router';
import router from '@ohos.router';
export default {
jumpBack() {
router.back();
......@@ -117,7 +117,6 @@ export default {
## Widget Transition
> **NOTE**
>
> Widget transitions are not available when other transitions (including shared element transitions and custom transitions) are used.
......@@ -125,7 +124,7 @@ export default {
| Name | Type | Default Value | Description |
| ----------------- | ------ | ---- | ---------------------------------------- |
| transition-effect | string | - | Whether a component on the current page displays the transition effect during a widget transition. Available values are as follows:<br>-&nbsp;**unfold**: The component will move upwards by one widget height if the component is located above the widget tapped by the user, or move downwards by one widget height if the component is located below the widget.<br>-&nbsp;**none**: No transition effect is displayed. |
| transition-effect | string | - | Whether a component on the current page displays the transition effect during a widget transition. Available values are as follows:<br>- **unfold**: The component will move upwards by one widget height if the component is located above the widget tapped by the user, or move downwards by one widget height if the component is located below the widget.<br>- **none**: No transition effect is displayed.|
### Example
......@@ -140,7 +139,7 @@ The **source_page** has a title area on the top and a widget list. Users can tap
<text style="font-size: 23px; margin-bottom: 20px" >MAIN TITLE</text>
</div>
<list style="width:340px;height:600px;flex-direction:column;justify-content:center;align-items:center">
<list-item type="listItem" class="item" card="true" for="list" id="{{$item.id}}" onclick="jumpPage({{$item.id}}, {{$item.uri}})">
<list-item type="listItem" class="item" card="true" for="list" id="{{$item.id}}" onclick="jumpPage({{$item.id}}, {{$item.url}})">
<text style="margin-left: 10px; font-size: 23px;">{{$item.title}}</text>
</list-item>
</list>
......@@ -149,19 +148,19 @@ The **source_page** has a title area on the top and a widget list. Users can tap
```js
// xxx.js
import router from '@system.router'
import router from '@ohos.router'
export default {
data: { list: [] },
onInit() {
for(var i = 0; i < 10; i++) {
var item = { uri: "pages/card_transition/target_page/index",
var item = { url: "pages/card_transition/target_page/index",
title: "this is title" + i, id: "item_" + i }
this.list.push(item);
}
},
jumpPage(id, uri) {
jumpPage(id, url) {
var cardId = this.$element(id).ref;
router.push({ uri: uri, params : { ref : cardId } });
router.push({ url: url, params : { ref : cardId } });
}
}
```
......@@ -169,6 +168,8 @@ export default {
```css
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
background-color: #ABDAFF;
......@@ -199,6 +200,8 @@ export default {
```css
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
background-color: #EBFFD7;
......@@ -223,7 +226,7 @@ export default {
| -------------------------- | ------ | ------------- | ---------------------------------------- |
| transition-enter | string | - | Works with **@keyframes** and supports transform and opacity animations. For details, see [Attributes available for the @keyframes rule](../arkui-js/js-components-common-animation.md).|
| transition-exit | string | - | Works with **@keyframes** and supports transform and opacity animations. For details, see [Attributes available for the @keyframes rule](../arkui-js/js-components-common-animation.md).|
| transition-duration | string | Follows the default page transition time of the device | The unit can be s or ms. The default unit is ms. If no value is specified, the default value is used. |
| transition-duration | string | Follows the default page transition time of the device| The unit can be s|or ms. The default unit is ms. If no value is specified, the default value is used.|
| transition-timing-function | string | friction | Speed curve of the transition animation, which makes the animation more fluent. For details, see the description of **animation-timing-function **in [Animation Styles](../arkui-js/js-components-common-animation.md).|
......@@ -255,16 +258,16 @@ export default {
</div>
```
```css
```js
// xxx.js
import router from '@system.router';
import router from '@ohos.router';
export default {
data: {
},
jump() {
router.push({
uri:'pages/transition2/transition2'
url:'pages/transition2/transition2'
})
}
}
......@@ -288,13 +291,13 @@ export default {
transition-duration: 5s;
transition-timing-function: friction;
}
@keyframes go_page {
from {
opacity: 0;
transform: translate(0px) rotate(60deg) scale(1.0);
}
to {
opacity: 1;
transform: translate(100px) rotate(360deg) scale(1.0);
......@@ -305,7 +308,7 @@ export default {
opacity: 1;
transform: translate(200px) rotate(60deg) scale(2);
}
to {
opacity: 0;
transform: translate(200px) rotate(360deg) scale(2);
......@@ -321,15 +324,15 @@ export default {
<div class="container">
<text>transition</text>
<div class="move_page" onclick="jumpBack"></div>
</div
</div>
```
```js
// xxx.js
import router from '@system.router';
import router from '@ohos.router';
export default {
data: {
},
jumpBack() {
router.back()
......@@ -346,7 +349,7 @@ export default {
width: 100%;
height: 100%;
}
.move_page {
width: 100px;
height: 100px;
......@@ -356,7 +359,7 @@ export default {
transition-duration: 5s;
transition-timing-function: ease;
}
@keyframes go_page {
from {
opacity: 0;
......@@ -367,7 +370,7 @@ export default {
transform:translate(100px) rotate(180deg) scale(2.0);
}
}
@keyframes exit_page {
from {
opacity: 1;
......
......@@ -72,7 +72,7 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md
| scrollend | - | Triggered when the list stops scrolling. |
| scrolltouchup | - | Triggered when the list continues scrolling after the user lifts their fingers. |
| requestitem | - | Triggered for a request to create a list-item.<br>This event is triggered when the number of cached list-items outside the visible area is less than the value of **cachedcount** during long list loading with delay.|
| rotate<sup>7+</sup> | { rotateValue: number } | Triggered to indicate the incremental value of the rotation angle of the watch crown. This parameter is only supported by wearables. |
| rotation<sup>7+</sup> | { rotateValue: number } | Triggered to indicate the incremental value of the rotation angle of the watch crown. This parameter is only supported by wearables. |
## Methods
......@@ -112,22 +112,6 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
</list>
</div>
```
```js
// index.js
export default {
data: {
todolist: [{
title: 'Prepare for the interview',
date: '2021-12-31 10:00:00',
}, {
title: 'Watch the movie',
date: '2021-12-31 20:00:00',
}],
},
}
```
```css
/* index.css */
.container {
......@@ -153,4 +137,21 @@ export default {
}
```
```js
// index.js
export default {
data: {
todolist: [{
title: 'Prepare for the interview',
date: '2021-12-31 10:00:00'
}, {
title: 'Watch the movie',
date: '2021-12-31 20:00:00'
}],
},
}
```
![en-us_image_0000001185033226](figures/en-us_image_0000001185033226.png)
......@@ -86,58 +86,63 @@ The following methods are supported.
```html
<!-- xxx.hml -->
<div class="doc-page">
<div class="btn-div">
<button type="capsule" value="Click here" onclick="showPanel"></button>
</div>
<panel id="simplepanel" type="foldable" mode="half" onsizechange="changeMode" miniheight="200px">
<div class="panel-div">
<div class="inner-txt">
<text class="txt">Simple panel in {{modeFlag}} mode</text>
</div>
<div class="inner-btn">
<button type="capsule" value="Close" onclick="closePanel"></button>
</div>
<div class="btn-div">
<button type="capsule" value="Click here" onclick="showPanel"></button>
</div>
</panel>
<panel id="simplepanel" type="foldable" mode="half" onsizechange="changeMode" miniheight="200px">
<div class="panel-div">
<div class="inner-txt">
<text class="txt">Simple panel in {{ modeFlag }} mode</text>
</div>
<div class="inner-btn">
<button type="capsule" value="Close" onclick="closePanel"></button>
</div>
</div>
</panel>
</div>
```
```css
/* xxx.css */
.doc-page {
flex-direction: column;
justify-content: center;
align-items: center;
flex-direction: column;
justify-content: center;
align-items: center;
}
.btn-div {
width: 100%;
height: 200px;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 200px;
flex-direction: column;
align-items: center;
justify-content: center;
}
.txt {
color: #000000;
font-weight: bold;
font-size: 39px;
color: #000000;
font-weight: bold;
font-size: 39px;
}
.panel-div {
width: 100%;
flex-direction: column;
align-items: center;
width: 100%;
flex-direction: column;
align-items: center;
}
.inner-txt {
width: 100%;
height: 160px;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: 160px;
flex-direction: column;
align-items: center;
justify-content: center;
}
.inner-btn {
width: 100%;
height: 120px;
justify-content: center;
align-items: center;
width: 100%;
height: 120px;
justify-content: center;
align-items: center;
}
```
......
......@@ -4,7 +4,7 @@
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
Bubble indication. The **\<popup>** component is used to display a pop-up to offer instructions after a user clicks a bound control.
The **\<popup>** component is used to display a pop-up to offer instructions after a user clicks a bound component.
## Required Permissions
......@@ -116,7 +116,7 @@ export default {
visibilitychange(e) {
prompt.showToast({
message: 'visibility change visibility: ' + e.visibility,
duration: 3000,
duration: 3000
});
},
showpopup() {
......@@ -124,7 +124,7 @@ export default {
},
hidepopup() {
this.$element("popup").hide();
},
}
}
```
......
......@@ -4,7 +4,7 @@
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
The **<Refresh\>** component is used to refresh a page through a pull-down gesture.
The **<refresh\>** component is used to refresh a page through a pull-down gesture.
## Required Permissions
......@@ -22,7 +22,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| offset | &lt;length&gt; | - | No| Distance to the top of the parent component from the **<Refresh\>** component that comes to rest after a successful pull-down gesture.|
| offset | &lt;length&gt; | - | No| Distance to the top of the parent component from the **<refresh\>** component that comes to rest after a successful pull-down gesture.|
| refreshing | boolean | false | No| Whether the **\<refresh>** component is being used for refreshing.|
| type | string | auto | No| Dynamic effect when the component is refreshed. Two options are available and cannot be modified dynamically.<br>- **auto**: default effect. When the list is pulled to the top, the list does not move. When the list is pulled to the bottom, a circle is displayed.<br>- **pulldown**: When the list is pulled to the top, users can continue to pull down to trigger a refresh. The rebound effect will appear after the refresh. If the child component contains a list, set **scrolleffect** of the list to **no** to prevent drop-down effect conflicts.|
| lasttime | boolean | false | No| Whether to display the last update time. The character string format is **last update time: XXXX**, where **XXXX** is displayed based on the certain time and date formats and cannot be dynamically modified. (It is recommended that this attribute be used when **type** is set to **pulldown**. The fixed distance is at the bottom of the content drop-down area. Pay attention to the **offset** attribute setting to prevent overlapping.)|
......@@ -36,8 +36,8 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| background-color | &lt;color&gt; | white | No| Background color of the **\<refresh>** component.|
| progress-color | &lt;color&gt; | black | No| Loading color of the **\<refresh>** component.|
| background-color | &lt;color&gt; | white<br>| No| Background color of the **\<refresh>** component.|
| progress-color | &lt;color&gt; | black<br>| No| Color of the loading icon of the **\<refresh>** component.|
## Events
......@@ -107,7 +107,7 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are not sup
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
data: {
list:[],
......@@ -121,7 +121,7 @@ export default {
}
},
refresh: function (e) {
prompt.showToast({
promptAction.showToast({
message: 'Refreshing...'
})
var that = this;
......@@ -130,7 +130,7 @@ export default {
that.fresh = false;
var addItem ='Refresh element';
that.list.unshift(addItem);
prompt.showToast({
promptAction.showToast({
message: 'Refreshed.'
})
}, 2000)
......
......@@ -27,7 +27,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| Name | Type | Default Value | Description |
| ----- | ------ | ---- | ------------------------------ |
| index | number | - | Index of the **\<stepper-item>** child component that is currently displayed.|
| index | number | 0 | Index of the **\<stepper-item>** child component to display. By default, the first one is displayed.|
## Styles
......@@ -46,10 +46,10 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md
| Name | Parameter | Description |
| ------ | ---------------------------------------- | ---------------------------------------- |
| finish | - | Triggered when the last step on the navigator is complete. |
| skip | - | Triggered when users click the skip button, which works only if you have called **setNextButtonStatus** method to allow users to skip all steps.|
| skip | - | Triggered when users click the skip button to skip steps.|
| change | { prevIndex: prevIndex, index: index} | Triggered when users click the left or right (text) button of the step navigator to switch between steps. **prevIndex** indicates the index of the previous step, and **index** indicates that of the current step.|
| next | { index: index, pendingIndex: pendingIndex } | Triggered when users click the next (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **\<stepper-item>** child component as the next step to go.|
| back | { index: index, pendingIndex: pendingIndex } | Triggered when users click the previous (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in Object:{ **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **\<stepper-item>** child component as the previous step.|
| next | { index: index, pendingIndex: pendingIndex } | Triggered when users click the next (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **<stepper-item>** child component as the next step to go.|
| back | { index: index, pendingIndex: pendingIndex } | Triggered when users click the previous (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in Object:{ **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **<stepper-item>** child component as the previous step.|
## Methods
......@@ -58,101 +58,137 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
| Name | Parameter | Description |
| ------------------- | ---------------------------------------- | ---------------------------------------- |
| setNextButtonStatus | { status: string, label: label } | Sets the status of the next (text) button in this step navigator. Available **status** values are as follows:<br>- **normal**: The next button is displayed normally and can navigate users to the next step when it is clicked.<br>- **disabled**: The next button is grayed out and unavailable.<br>- **waiting**: The next button is not displayed, and a process bar is displayed instead.<br>- **skip**: The skip button is displayed to allow users to skip all remaining steps.|
| setNextButtonStatus | { status: string, label: label } | Sets the text and status of the next button in the step navigator. **label** indicates the button text, and **status** indicates the button status. Available **status** values are as follows:<br>- **normal**: The next button is displayed normally and can navigate users to the next step when it is clicked.<br>- **disabled**: The next button is grayed out and unavailable.<br>- **waiting**: The next button is not displayed, and a process bar is displayed instead.<br>- **skip**: The skip button is displayed to allow users to skip all remaining steps.|
## Example
```html
<!-- xxx.hml -->
<div class = "container">
<stepper class="stepper" id="mystepper" index="0" onnext="nextclick" onback="backclick">
<stepper-item class ="stepperItem" label="{{label_1}}">
<div class = "stepperItemContent" >
<text class = "text">First screen</text>
</div>
<button type="capsule" class ="button" value="setRightButtonStatus" onclick="setRightButton"></button>
</stepper-item>
<stepper-item class ="stepperItem" label="{{label_2}}">
<div class = "stepperItemContent" >
<text class = "text">Second screen</text>
</div>
<button type="capsule" class ="button" value="setRightButtonStatus" onclick="setRightButton"></button>
</stepper-item>
<stepper-item class ="stepperItem" label="{{label_3}}">
<div class = "stepperItemContent" >
<text class = "text">Third screen</text>
</div>
<button type="capsule" class ="button" value="setRightButtonStatus" onclick="setRightButton"></button>
</stepper-item>
</stepper>
<div class="container">
<stepper class="stepper" id="mystepper" onnext="nextclick" onback="backclick" onchange="statuschange"
onfinish="finish" onskip="skip" style="height : 100%;">
<stepper-item class="stepper-item" label="{{ label_1 }}">
<div class="item">
<text>Page One</text>
<button type="capsule" class="button" value="change status" onclick="setRightButton"></button>
</div>
</stepper-item>
<stepper-item class="stepper-item" label="{{ label_2 }}">
<div class="item">
<text>Page Two</text>
<button type="capsule" class="button" value="change status" onclick="setRightButton"></button>
</div>
</stepper-item>
<stepper-item class="stepper-item" label="{{ label_3 }}">
<div class="item">
<text>Page Three</text>
<button type="capsule" class="button" value="change status" onclick="setRightButton"></button>
</div>
</stepper-item>
</stepper>
</div>
```
```css
/* xxx.css */
.container {
margin-top: 20px;
flex-direction: column;
align-items: center;
height: 300px;
flex-direction: column;
align-items: center;
height: 100%;
width: 100%;
background-color: #f7f7f7;
}
.stepperItem {
width: 100%;
flex-direction: column;
align-items: center;
.stepper{
width: 100%;
height: 100%;
}
.stepperItemContent {
color: #0000ff;
font-size: 50px;
justify-content: center;
.stepper-item {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
}
.item{
width: 90%;
height: 86%;
margin-top: 80px;
background-color: white;
border-radius: 60px;
flex-direction: column;
align-items: center;
padding-top: 160px;
}
text {
font-size: 78px;
color: #182431;
opacity: 0.4;
}
.button {
width: 60%;
margin-top: 30px;
justify-content: center;
width: 40%;
margin-top: 100px;
justify-content: center;
}
```
```js
// xxx.js
import prompt from '@system.prompt';
export default {
data: {
label_1:
{
prevLabel: 'BACK',
nextLabel: 'NEXT',
status: 'normal'
},
label_2:
{
prevLabel: 'BACK',
nextLabel: 'NEXT',
status: 'normal'
},
label_3:
{
prevLabel: 'BACK',
nextLabel: 'NEXT',
status: 'normal'
},
},
setRightButton(e) {
this.$element('mystepper').setNextButtonStatus({status: 'skip', label: 'SKIP'});
},
nextclick(e) {
var index = {
pendingIndex: e.pendingIndex
}
return index;
},
backclick(e) {
var index = {
pendingIndex: e.pendingIndex
data: {
label_1:
{
prevLabel: 'BACK',
nextLabel: 'NEXT',
status: 'normal'
},
label_2:
{
prevLabel: 'BACK',
nextLabel: 'NEXT',
status: 'normal'
},
label_3:
{
prevLabel: 'BACK',
nextLabel: 'NEXT',
status: 'normal'
}
},
setRightButton(e) {
this.$element('mystepper').setNextButtonStatus({
status: 'waiting', label: 'SKIP'
});
},
nextclick(e) {
var index = {
pendingIndex: e.pendingIndex
}
return index;
},
backclick(e) {
var index = {
pendingIndex: e.pendingIndex
}
return index;
},
statuschange(e) {
prompt.showToast({
message: 'Previous step index' + e.prevIndex + 'Current step index' + e.index
})
},
finish() {
prompt.showToast({
message:'Finished.'
})
},
skip() {
prompt.showToast({
message: 'Skip triggered'
})
}
return index;
},
}
```
![en-us_image_0000001127125114](figures/en-us_image_0000001127125114.gif)
![](figures/stepper.gif)
......@@ -4,7 +4,7 @@
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Swiper>** component provides a container that allows users to switch among child components using swipe gestures.
The **\<swiper>** component provides a container that allows users to switch among child components using swipe gestures.
## Required Permissions
......
......@@ -3,17 +3,7 @@
> **NOTE**
>
> - This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
>
> - Set **configChanges** under **abilities** in the **config.json** file to **orientation**.
> ```
> "abilities": [
> {
> "configChanges": ["orientation"],
> ...
> }
> ]
> ```
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
The **\<video>** component provides a video player.
......@@ -27,58 +17,58 @@ Not supported
In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported.
| Name | Type | Default Value | Mandatory | Description |
| -------- | ------- | ------------- | --------- | ---------------------------------------- |
| muted | boolean | false | No | Whether the video is muted. |
| src | string | - | No | Path of the video content to play. |
| autoplay | boolean | false | No | Whether the video is played automatically after being rendered. |
| controls | boolean | true | No | Whether the control bar is displayed during video playback. If the value is set to **false**, the control bar is not displayed. The default value is **true**, indicating that the platform can either show or hide the control bar. |
| Name | Type | Default Value | Mandatory | Description |
| -------- | ------- | ----- | ---- | ---------------------------------------- |
| muted | boolean | false | No | Whether the video is muted. |
| src | string | - | No | Path of the video content to play. |
| autoplay | boolean | false | No | Whether the video is played automatically after being rendered. |
| controls | boolean | true | No | Whether the control bar is displayed during video playback. If the value is set to **false**, the control bar is not displayed. The default value is **true**, indicating that the platform can either show or hide the control bar.|
## Styles
In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported.
| Name | Type | Default Value | Mandatory | Description |
| ---------- | ------ | ------------- | --------- | ---------------------------------------- |
| object-fit | string | contain | No | Video scale type. If **poster** has been assigned a value, the setting of this style will affect the scaling type of the video poster. For details, see object-fit enums. |
| Name | Type | Default Value | Mandatory | Description |
| ---------- | ------ | ------- | ---- | ---------------------------------------- |
| object-fit | string | contain | No | Video scale type. If **poster** has been assigned a value, the setting of this style will affect the scaling type of the video poster. For details, see object-fit enums.|
**Table 1** object-fit enums
| Type | Description |
| ---- | ---------------------------------------- |
| fill | The image is resized to fill the display area, and its aspect ratio is not retained. |
| Type | Description |
| ---- | ------------------------- |
| fill | The image is resized to fill the display area, and its aspect ratio is not retained.|
## Events
In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported.
| Name | Parameter | Description |
| ---------- | ---------------------------------------- | ---------------------------------------- |
| prepared | {&nbsp;duration:&nbsp;value&nbsp;}<sup>5+</sup> | Triggered when the video preparation is complete. The video duration (in seconds) is obtained from **duration**. |
| start | - | Triggered when the video is played. |
| pause | - | Triggered when the video playback is paused. |
| finish | - | Triggered when the video playback is finished. |
| error | - | Triggered when the video playback fails. |
| seeking | {&nbsp;currenttime:&nbsp;value&nbsp;} | Triggered to report the time (in seconds) when the progress bar is being dragged. |
| seeked | {&nbsp;currenttime:&nbsp;value&nbsp;} | Triggered to report the playback time (in seconds) when the user finishes dragging the progress bar. |
| timeupdate | {&nbsp;currenttime:&nbsp;value&nbsp;} | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second. |
| Name | Parameter | Description |
| ---------- | ---------------------------------------- | ------------------------------------- |
| prepared | { duration: value }<sup>5+</sup> | Triggered when the video preparation is complete. The video duration (in seconds) is obtained from **duration**.|
| start | - | Triggered when the video is played. |
| pause | - | Triggered when the video playback is paused. |
| finish | - | Triggered when the video playback is finished. |
| error | - | Triggered when the video playback fails. |
| seeking | { currenttime: value } | Triggered to report the time (in seconds) when the progress bar is being dragged. |
| seeked | { currenttime: value } | Triggered to report the playback time (in seconds) when the user finishes dragging the progress bar. |
| timeupdate | { currenttime: value } | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second. |
## Methods
In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported.
| Name | Parameter | Description |
| -------------- | ------------------------------------- | ---------------------------------------- |
| start | - | Starts playing a video. |
| pause | - | Pauses a video. |
| setCurrentTime | {&nbsp;currenttime:&nbsp;value&nbsp;} | Sets the video playback position, in seconds. |
| Name | Parameter | Description |
| -------------- | ------------------------------------- | ----------------- |
| start | - | Starts playing a video. |
| pause | - | Pauses a video. |
| setCurrentTime | { currenttime: value } | Sets the video playback position, in seconds.|
> **NOTE**
> **NOTE**
>
> The methods in the above table can be called after the **attached** callback is invoked.
> The methods in the above table can be called after the **attached** callback is invoked.
## Example
......
......@@ -19,7 +19,7 @@ In addition to the attributes that are supported by **CanvasRenderingContext2D**
**Example**
```html
<!-- xxx.hml -->
<div style="width: 180px; height: 60px;">
<div style="width: 500px; height: 500px;">
<canvas ref="canvasId" style="width: 500px; height: 500px; background-color: #ffff00;"></canvas>
</div>
```
......@@ -95,7 +95,7 @@ Checks whether a specified point is in the path area.
**Example**
```html
<!-- xxx.hml -->
<div style="width: 180px; height: 60px;">
<div style="width: 500px; height: 500px;">
<text>In path:{{textValue}}</text>
<canvas ref="canvas" style="width: 500px; height: 500px; background-color: #ffff00;"></canvas>
</div>
......@@ -145,7 +145,7 @@ Checks whether a specified point is on the edge line of a path.
**Example**
```html
<!-- xxx.hml -->
<div style="width: 180px; height: 60px;">
<div style="width: 500px; height: 500px;">
<text>In path:{{textValue}}</text>
<canvas ref="canvas" style="width: 500px; height: 500px; background-color: #ffff00;"></canvas>
</div>
......@@ -181,7 +181,7 @@ resetTransform(): void
**Example**
```html
<!-- xxx.hml -->
<div style="width: 180px; height: 60px;">
<div style="width: 500px; height: 500px;">
<text>In path:{{textValue}}</text>
<canvas ref="canvas" style="width: 500px; height: 500px; background-color: #ffff00;"></canvas>
</div>
......
......@@ -37,7 +37,7 @@ In addition to the [universal events](ts-universal-events-click.md), the followi
| Name | Description|
| ----------| -------- |
|onChange(callback: (value: boolean) => void) | Triggered when the selection status of the check box changes.<br>- The value **true** means that the check box is selected.<br>- The value **false** means that the check box is not selected.|
|onChange(callback: (value: boolean) => void) | Triggered when the selected status of the check box changes due to a manual operation.<br>- The value **true** means that the check box is selected.<br>- The value **false** means that the check box is not selected. |
## Example
......
......@@ -18,6 +18,8 @@ Creates a check box group so that you can select or deselect all check boxes in
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| group | string | No| Group name.|
......@@ -28,7 +30,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Description|
| -------- | -------- | -------- |
| selectAll | boolean | Whether to select all.<br>Default value: **false**|
| selectAll | boolean | Whether to select all.<br>Default value: **false**<br>If **select** is explicitly set for check boxes in the group, the check box settings are prioritized.|
| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected check box.|
## Events
......@@ -37,13 +39,13 @@ In addition to the [universal events](ts-universal-events-click.md), the followi
| Name| Description|
| -------- | -------- |
| onChange (callback: (event: CheckboxGroupResult) => void ) |Triggered when the selection status of the check box group or any check box wherein changes.|
| onChange (callback: (event: [CheckboxGroupResult](#checkboxgroupresult)) => void ) |Triggered when the selected status of the check box group or any check box wherein changes due to a manual operation.|
## CheckboxGroupResult
| Name | Type | Description |
| ------ | ------ | ------- |
| name | Array&lt;string&gt; | Names of all the selected check boxes in the group.|
| status | SelectStatus | Selected status.|
| status | [SelectStatus](#selectstatus) | Selected status.|
## SelectStatus
......@@ -64,47 +66,48 @@ struct CheckboxExample {
build() {
Scroll() {
Column() {
// Select All button
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
CheckboxGroup({ group: 'checkboxGroup' })
.selectedColor(0xed6f21)
.selectedColor('#007DFF')
.onChange((itemName: CheckboxGroupResult) => {
console.info("TextPicker::dialogResult is" + JSON.stringify(itemName))
console.info("checkbox group content" + JSON.stringify(itemName))
})
Text('select all').fontSize(20)
Text('Select All').fontSize(14).lineHeight(20).fontColor('#182431').fontWeight(500)
}
// Option 1
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Checkbox({ name: 'checkbox1', group: 'checkboxGroup' })
.select(true)
.selectedColor(0x39a2db)
.selectedColor('#007DFF')
.onChange((value: boolean) => {
console.info('Checkbox1 change is' + value)
})
Text('Checkbox1').fontSize(20)
}
Text('Checkbox1').fontSize(14).lineHeight(20).fontColor('#182431').fontWeight(500)
}.margin({ left: 36 })
// Option 2
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Checkbox({ name: 'checkbox2', group: 'checkboxGroup' })
.select(false)
.selectedColor(0x39a2db)
.selectedColor('#007DFF')
.onChange((value: boolean) => {
console.info('Checkbox2 change is' + value)
})
Text('Checkbox2').fontSize(20)
}
Text('Checkbox2').fontSize(14).lineHeight(20).fontColor('#182431').fontWeight(500)
}.margin({ left: 36 })
// Option 3
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Checkbox({ name: 'checkbox3', group: 'checkboxGroup' })
.select(true)
.selectedColor(0x39a2db)
.selectedColor('#007DFF')
.onChange((value: boolean) => {
console.info('Checkbox3 change is' + value)
})
Text('Checkbox3').fontSize(20)
}
Text('Checkbox3').fontSize(14).lineHeight(20).fontColor('#182431').fontWeight(500)
}.margin({ left: 36 })
}
}
}
}
```
![](figures/checkboxgroup.gif)
![checkboxGroup](figures/checkboxGroup.gif)
......@@ -22,15 +22,15 @@ DataPanel(options:{values: number[], max?: number, type?: DataPanelType})
| Name | Type | Mandatory | Description|
| ----------------- | -------- | ----- | -------- |
| values | number[] | Yes | Value list. A maximum of nine values are supported.|
| values | number[] | Yes | Data value list. A maximum of nine values are supported. If more than nine values are set, only the first nine ones are used. If the value is less than 0, the value 0 is used.|
| max | number | No | - When set to a value greater than 0, this parameter indicates the maximum value in the **values** list.<br>- When set to a value equal to or smaller than 0, this parameter indicates the sum of values in the **values** list. The values are displayed in proportion.<br>Default value: **100**|
| type<sup>8+</sup> | DataPanelType | No| Type of the data panel.<br>Default value: **DataPanelType.Circle**|
| type<sup>8+</sup> | [DataPanelType](#datapaneltype) | No| Type of the data panel.<br>Default value: **DataPanelType.Circle**|
## DataPanelType enums
| Name| Description|
## DataPanelType
| Name| Description|
| -------| ------------ |
| Line | Line data panel.|
| Line | Line data panel.|
| Circle | Circle data panel.|
......@@ -41,18 +41,46 @@ DataPanel(options:{values: number[], max?: number, type?: DataPanelType})
@Entry
@Component
struct DataPanelExample {
public values1: number[] = [10, 10, 10, 10, 10, 10, 10, 10, 10]
public valueArr: number[] = [10, 10, 10, 10, 10, 10, 10, 10, 10]
build() {
Column({ space: 5 }) {
Text('Circle').fontSize(9).fontColor(0xCCCCCC).margin({ top: 20, right: '80%' })
DataPanel({ values: this.values1, max: 100, type: DataPanelType.Circle }).width(200).height(200)
Text('Line').fontSize(9).fontColor(0xCCCCCC).margin({ bottom: 20, right: '80%' })
DataPanel({ values: this.values1, max: 100, type: DataPanelType.Line }).width(300).height(10)
Row() {
Stack() {
DataPanel({ values: [25], max: 100, type: DataPanelType.Circle }).width(168).height(168)
Column() {
Text('30').fontSize(35).fontColor('#182431')
Text('1.0.0').fontSize(9.33).lineHeight(12.83).fontWeight(500).opacity(0.6)
}
Text('%')
.fontSize(9.33)
.lineHeight(12.83)
.fontWeight(500)
.opacity(0.6)
.position({ x: 104.42, y: 78.17 })
}.margin({ right: 44 })
Stack() {
DataPanel({ values: [50, 12, 8, 5], max: 100, type: DataPanelType.Circle }).width(168).height(168)
Column() {
Text('75').fontSize(35).fontColor('#182431')
Text('Used: 98 GB/128 GB') .fontSize(8.17).lineHeight(11.08).fontWeight(500).opacity(0.6)
}
Text('%')
.fontSize(9.33)
.lineHeight(12.83)
.fontWeight(500)
.opacity(0.6)
.position({ x: 104.42, y: 78.17 })
}
}.margin({ bottom: 59 })
DataPanel({ values: this.valueArr, max: 100, type: DataPanelType.Line }).width(300).height(10)
}.width('100%').margin({ top: 5 })
}
}
```
![en-us_image_0000001211898476](figures/en-us_image_0000001211898476.jpg)
![dataPanel](figures/dataPanel.PNG)
......@@ -27,7 +27,7 @@ Obtains an image from the specified source for subsequent rendering and display.
| Name| Type | Mandatory| Description |
| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| src | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.<br>When using an image referenced using a relative path, for example, `Image("common/test.jpg")`, the **\<Image>** component cannot be called across bundles or modules. Therefore, you are advised to use `$r` to reference image resources that need to be used globally.<br>- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.<br>\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.<br/>\- Strings with the **datashare://path** prefix are supported, which are used to access the image path provided by a data ability.<br>\- Strings with the `file:///data/storage` prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the application. Ensure that the files in the directory package path have the read permission.|
| src | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.<br>When using an image referenced using a relative path, for example, **Image("common/test.jpg")**, the **\<Image>** component cannot be called across bundles or modules. Therefore, you are advised to use **$r** to reference image resources that need to be used globally.<br>- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.<br>\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.<br/>\- Strings with the **datashare://path** prefix are supported, which are used to access the image path provided by a data ability.<br>\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the application. Ensure that the files in the directory package path have the read permission. |
## Attributes
......@@ -37,7 +37,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| --------------------- | ------------------------------------------------------- | ------------------------------------------------------------ |
| alt | string \| [Resource](ts-types.md#resource)| Placeholder image displayed during loading. Local images are supported. |
| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale mode.<br>Default value: **ImageFit.Cover** |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Whether the image is repeated.<br>Default value: **NoRepeat**<br>**NOTE**<br>This attribute is not applicable to SVG images.|
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Whether the image is repeated.<br>Default value: **ImageRepeat.NoRepeat**<br>**NOTE**<br>This attribute is not applicable to SVG images.|
| interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.<br>Default value: **ImageInterpolation.None**<br>**NOTE**<br>This attribute is not applicable to SVG images and **PixelMap** objects. |
| renderMode | [ImageRenderMode](#imagerendermode) | Rendering mode of the image.<br>Default value: **ImageRenderMode.Original**<br>**NOTE**<br>This attribute is not applicable to SVG images.|
| sourceSize | {<br>width: number,<br>height: number<br>} | Size of the decoded image. The original image is decoded into a **pixelMap** of the specified size, in px.<br>**NOTE**<br>This attribute is not applicable to **PixelMap** objects.|
......@@ -218,7 +218,7 @@ struct Index {
> **NOTE**
>
> For details about the request mode, timeout, and additional request parameters for loading online images, see [`request()`](../../reference/apis/js-apis-http.md) in the HTTP module.
> For details about the request mode, timeout, and additional request parameters for loading online images, see [request()](../../reference/apis/js-apis-http.md) in the HTTP module.
### Setting Attributes
......@@ -356,6 +356,7 @@ struct ImageExample3 {
```ts
import fileio from '@ohos.fileio'
import fs from '@ohos.file.fs';
import context from '@ohos.application.context'
@Entry
......@@ -376,7 +377,7 @@ struct LoadImageExample {
.onClick(() => {
this.sandboxPath = this.context.getApplicationContext().filesDir + '/icon.png'
console.log(`Read the sandbox image=========>${this.sandboxPath}`)
let fd = fileio.openSync(this.sandboxPath, 0o100, 0o666)
let fd = fs.openSync(this.sandboxPath, 0o100)
console.log(`create file========>${fd}`)
let srcPath = this.context.bundleCodeDir + '/entry/resources/base/media/icon.png'
console.log('mySrcpath' + srcPath)
......
......@@ -51,10 +51,10 @@ Marquee(value: { start: boolean, step?: number, loop?: number, fromStart?: boole
@Component
struct MarqueeExample {
@State start: boolean = false
@State fromStart: boolean = true
@State step: number = 50
@State loop: number = 3
@State src: string = "Running Marquee starts rolling"
private fromStart: boolean = true
private step: number = 50
private loop: number = Infinity
private src: string = "Running Marquee starts rolling"
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -65,29 +65,31 @@ struct MarqueeExample {
fromStart: this.fromStart,
src: this.src
})
.width(400)
.fontColor(Color.White)
.fontSize(50)
.allowScale(false)
.fontWeight(FontWeight.Bold)
.backgroundColor(Color.Black)
.margin({bottom:40})
.width(360)
.height(80)
.fontColor('#FFFFFF')
.fontSize(48)
.fontWeight(700)
.backgroundColor('#182431')
.margin({ bottom: 40 })
.onStart(() => {
console.log('Marquee animation complete onStart')
console.info('Marquee animation complete onStart')
})
.onBounce(() => {
console.log('Marquee animation complete onBounce')
console.info('Marquee animation complete onBounce')
})
.onFinish(() => {
console.log('Marquee animation complete onFinish')
console.info('Marquee animation complete onFinish')
})
Button('start')
.onClick(() => {
this.start = true
})
.width(200)
.height(60)
.margin({bottom:20})
Button('Start')
.onClick(() => {
this.start = true
})
.width(120)
.height(40)
.fontSize(16)
.fontWeight(500)
.backgroundColor('#007DFF')
}
.width('100%')
.height('100%')
......@@ -95,4 +97,4 @@ struct MarqueeExample {
}
```
![en-us_image_0000001193499234](figures/en-us_image_0000001193499234.gif)
![marquee](figures/marquee.gif)
......@@ -108,10 +108,10 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
## Events
| Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| onTitleModeChange(callback: (titleMode: NavigationTitleMode) =&gt; void) | Triggered when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls. |
| onNavBarStateChange(callback: (isVisible: boolean) =&gt; void) | Triggered when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite. |
| Name | Description |
| ---------------------------------------- | ---------------------------------------- |
| onTitleModeChange(callback: (titleMode: NavigationTitleMode) =&gt; void) | Triggered when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.|
| onNavBarStateChange(callback: (isVisible: boolean) =&gt; void) | Triggered when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.|
## Example
......@@ -232,4 +232,4 @@ struct NavigationExample {
}
```
![en-us_image_0000001212058484](figures/en-us_image_0000001212058484.gif)
![en-us_image_0000001192655288](figures/en-us_image_0000001192655288.gif)
......@@ -21,7 +21,7 @@ Rating(options?: { rating: number, indicator?: boolean })
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| rating | number | Yes| Value to rate.<br>Default value: **0**|
| indicator | boolean | No| Used only as an indicator and cannot be operated.<br>Default value: **false**|
| indicator | boolean | No| Whether the component is used only as an indicator and cannot be operated.<br>Default value: **false**|
## Attributes
......@@ -47,21 +47,51 @@ Rating(options?: { rating: number, indicator?: boolean })
@Entry
@Component
struct RatingExample {
@State rating: number = 1
@State indicator: boolean = false
@State rating: number = 3.5
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Text('current score is ' + this.rating).fontSize(20)
Rating({ rating: this.rating, indicator: this.indicator })
.stars(5)
.stepSize(0.5)
.onChange((value: number) => {
this.rating = value
})
}.width(350).height(200).padding(35)
Column() {
Column() {
Rating({ rating: this.rating, indicator: false })
.stars(5)
.stepSize(0.5)
.margin({ top: 24 })
.onChange((value: number) => {
this.rating = value
})
Text('current score is ' + this.rating)
.fontSize(16)
.fontColor('rgba(24,36,49,0.60)')
.margin({ top: 16 })
}.width(360).height(113).backgroundColor('#FFFFFF').margin({ top: 68 })
Row() {
Image('common/testImage.jpg')
.width(40)
.height(40)
.borderRadius(20)
.margin({ left: 24 })
Column() {
Text('Yue')
.fontSize(16)
.fontColor('#182431')
.fontWeight(500)
Row() {
Rating({ rating: 3.5, indicator: true }).margin({ top: 1, right: 8 })
Text('2021/06/02')
.fontSize(10)
.fontColor('#182431')
}
}.margin({ left: 12 }).alignItems(HorizontalAlign.Start)
Text('1st Floor')
.fontSize(10)
.fontColor('#182431')
.position({ x: 295, y: 8 })
}.width(360).height(56).backgroundColor('#FFFFFF').margin({ top: 64 })
}.width('100%').height('100%').backgroundColor('#F1F3F5')
}
}
```
![en-us_image_0000001257058423](figures/en-us_image_0000001257058423.gif)
![rating](figures/rating.gif)
......@@ -3,7 +3,7 @@
The **\<Stepper>** component provides a step navigator.
> **NOTE**
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
......@@ -45,6 +45,22 @@ None
```ts
// xxx.ets
@Styles function itemStyle () {
.width(336)
.height(621)
.margin({ top: 48, left: 12 })
.borderRadius(24)
.backgroundColor('#FFFFFF')
}
@Extend(Text) function itemTextStyle () {
.fontColor('#182431')
.fontSize(36)
.fontWeight(500)
.opacity(0.4)
.margin({ top: 82, bottom: 40 })
}
@Entry
@Component
struct StepperExample {
......@@ -61,15 +77,13 @@ struct StepperExample {
StepperItem() {
Column() {
Text('Page One')
.fontSize(35)
.fontColor(Color.Blue)
.lineHeight(50)
.margin({ top: 250, bottom: 50 })
.itemTextStyle()
Button('change status:' + this.firstState)
.backgroundColor('#007dFF')
.onClick(() => {
this.firstState = this.firstState === ItemState.Skip ? ItemState.Normal : ItemState.Skip
})
}.width('100%')
}.itemStyle()
}
.nextLabel('Next')
.status(this.firstState)
......@@ -77,15 +91,13 @@ struct StepperExample {
StepperItem() {
Column() {
Text('Page Two')
.fontSize(35)
.fontColor(Color.Blue)
.lineHeight(50)
.margin({ top: 250, bottom: 50 })
.itemTextStyle()
Button('change status:' + this.secondState)
.backgroundColor('#007dFF')
.onClick(() => {
this.secondState = this.secondState === ItemState.Disabled ? ItemState.Normal : ItemState.Disabled
})
}.width('100%')
}.itemStyle()
}
.nextLabel('Next')
.prevLabel('Previous')
......@@ -94,29 +106,25 @@ struct StepperExample {
StepperItem() {
Column() {
Text('Page Three')
.fontSize(35)
.fontColor(Color.Blue)
.lineHeight(50)
.margin({ top: 250, bottom: 50 })
.itemTextStyle()
Button('change status:' + this.thirdState)
.backgroundColor('#007dFF')
.onClick(() => {
this.thirdState = this.thirdState === ItemState.Waiting ? ItemState.Normal : ItemState.Waiting
})
}.width('100%')
}.itemStyle()
}
.status(this.thirdState)
// Fourth step page
StepperItem() {
Text('Page four')
.fontSize(35)
.fontColor(Color.Blue)
.width('100%')
.textAlign(TextAlign.Center)
.lineHeight(50)
.margin({ top: 250 })
Column() {
Text('Page Four')
.itemTextStyle()
}.itemStyle()
}
.nextLabel('Finish')
}
.backgroundColor('#F1F3F5')
.onFinish(() => {
// Define the processing logic for when Finish on the last page is clicked, for example, redirection.
console.info('onFinish')
......@@ -133,4 +141,4 @@ struct StepperExample {
```
![en-us_image_0000001250678457](figures/en-us_image_0000001250678457.gif)
![stepper](figures/stepper.gif)
......@@ -85,23 +85,29 @@ struct TextAreaExample {
build() {
Column() {
TextArea({ placeholder: 'The text area can hold an unlimited amount of text. input your word', controller: this.controller })
.placeholderFont({ size: 14, weight: 400 })
.width(400)
.height(50)
TextArea({
placeholder: 'The text area can hold an unlimited amount of text. input your word...',
controller: this.controller
})
.placeholderFont({ size: 16, weight: 400 })
.width(336)
.height(56)
.margin(20)
.fontSize(14)
.fontSize(16)
.fontColor('#182431')
.backgroundColor('#FFFFFF')
.onChange((value: string) => {
this.text = value
})
Text(this.text)
Button('Set caretPosition 1')
.backgroundColor('#007DFF')
.margin(15)
.onClick(() => {
// Move the caret to after the first entered character.
this.controller.caretPosition(1)
})
}.width('100%')
}.width('100%').height('100%').backgroundColor('#F1F3F5')
}
}
```
......
......@@ -4,13 +4,7 @@ The **\<Toggle>** component provides a clickable element in the check box, butto
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
......@@ -21,27 +15,28 @@ This component can contain child components only when **ToggleType** is set to *
Toggle(options: { type: ToggleType, isOn?: boolean })
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | ToggleType | Yes| Type of the toggle.|
| isOn | boolean | No| Whether the toggle is turned on. The value **true** means that the toggle is turned on, and **false** means the opposite.<br/>Default value: **false** |
**Parameters**
| Name| Type| Mandatory | Description |
| ---- | ---------- | -----| -------------- |
| type | [ToggleType](#toggletype) | Yes | Type of the toggle.|
| isOn | boolean | No | Whether the toggle is turned on. The value **true** means that the toggle is turned on, and **false** means the opposite.<br>Default value: **false**|
- ToggleType enums
| Name| Description|
| -------- | -------- |
| Checkbox | Check box type.<br>> **NOTE**<br>> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 14 vp,<br> right: 6 vp,<br> bottom: 14 vp,<br> left: 6 vp<br> } |
| Button | Button type. The set string, if any, will be displayed inside the button. |
| Switch | Switch type.<br>> **NOTE**<br>> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 12 vp,<br> right: 12 vp,<br> bottom: 12 vp,<br> left: 12 vp<br> } |
## ToggleType
| Name | Description |
| -------- | ---------------- |
| Checkbox | Check box type.<br>> **NOTE**<br>> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 14 vp,<br> right: 6 vp,<br> bottom: 14 vp,<br> left: 6 vp<br> } |
| Button | Button type. The set string, if any, will be displayed inside the button. |
| Switch | Switch type.<br>> **NOTE**<br>> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 12 vp,<br> right: 12 vp,<br> bottom: 12 vp,<br> left: 12 vp<br> } |
## Attributes
| Name| Parameter| Default Value| Description|
| -------- | -------- | -------- | -------- |
| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | - | Background color of the component when it is turned on.|
| switchPointColor | [ResourceColor](ts-types.md#resourcecolor) | - | Color of the circular slider when the component is of the **Switch** type.<br>> **NOTE**<br>> This attribute is valid only when **type** is set to **ToggleType.Switch**.|
| Name | Parameter | Description |
| ---------------- | --------------------------- | ---------------------- |
| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component when it is turned on.|
| switchPointColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the circular slider when the component is of the **Switch** type.<br>> **NOTE**<br>> This attribute is valid only when **type** is set to **ToggleType.Switch**.|
## Events
......@@ -58,21 +53,20 @@ Toggle(options: { type: ToggleType, isOn?: boolean })
@Entry
@Component
struct ToggleExample {
build() {
Column({ space: 10 }) {
Text('type: Switch').fontSize(12).fontColor(0xcccccc).width('90%')
Flex({ justifyContent: FlexAlign.SpaceEvenly, alignItems: ItemAlign.Center }) {
Toggle({ type: ToggleType.Switch, isOn: false })
.selectedColor(0xed6f21)
.switchPointColor(0xe5ffffff)
.selectedColor('#007DFF')
.switchPointColor('#FFFFFF')
.onChange((isOn: boolean) => {
console.info('Component status:' + isOn)
})
Toggle({ type: ToggleType.Switch, isOn: true })
.selectedColor(0x39a2db)
.switchPointColor(0xe5ffffff)
.selectedColor('#007DFF')
.switchPointColor('#FFFFFF')
.onChange((isOn: boolean) => {
console.info('Component status:' + isOn)
})
......@@ -81,15 +75,15 @@ struct ToggleExample {
Text('type: Checkbox').fontSize(12).fontColor(0xcccccc).width('90%')
Flex({ justifyContent: FlexAlign.SpaceEvenly, alignItems: ItemAlign.Center }) {
Toggle({ type: ToggleType.Checkbox, isOn: false })
.size({ width: 28, height: 28 })
.selectedColor(0xed6f21)
.size({ width: 20, height: 20 })
.selectedColor('#007DFF')
.onChange((isOn: boolean) => {
console.info('Component status:' + isOn)
})
Toggle({ type: ToggleType.Checkbox, isOn: true })
.size({ width: 28, height: 28 })
.selectedColor(0x39a2db)
.size({ width: 20, height: 20 })
.selectedColor('#007DFF')
.onChange((isOn: boolean) => {
console.info('Component status:' + isOn)
})
......@@ -98,17 +92,17 @@ struct ToggleExample {
Text('type: Button').fontSize(12).fontColor(0xcccccc).width('90%')
Flex({ justifyContent: FlexAlign.SpaceEvenly, alignItems: ItemAlign.Center }) {
Toggle({ type: ToggleType.Button, isOn: false }) {
Text('status button').padding({ left: 12, right: 12 })
}
.selectedColor(0xed6f21)
Text('status button').fontColor('#182431').fontSize(12)
}.width(106)
.selectedColor('rgba(0,125,255,0.20)')
.onChange((isOn: boolean) => {
console.info('Component status:' + isOn)
})
Toggle({ type: ToggleType.Button, isOn: true }) {
Text('status button').padding({ left: 12, right: 12 })
}
.selectedColor(0x39a2db)
Text('status button').fontColor('#182431').fontSize(12)
}.width(106)
.selectedColor('rgba(0,125,255,0.20)')
.onChange((isOn: boolean) => {
console.info('Component status:' + isOn)
})
......@@ -118,4 +112,4 @@ struct ToggleExample {
}
```
![en-us_image_0000001211898522](figures/en-us_image_0000001211898522.gif)
![toggle](figures/toggle.gif)
......@@ -17,40 +17,41 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | --------- | ---------------------------- |
| offset | number | Yes | 0 | Relative position of the gradient stop along the gradient vector. The value ranges from 0 to 1.|
| color | string | Yes | '#ffffff' | Gradient color to set. |
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | --------- | ---------------------------- |
| offset | number | Yes | 0 | Relative position of the gradient stop along the gradient vector. The value ranges from 0 to 1.|
| color | string | Yes | '#ffffff' | Gradient color to set. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct Page45 {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
var grad = this.context.createLinearGradient(50,0, 300,100)
grad.addColorStop(0.0, 'red')
grad.addColorStop(0.5, 'white')
grad.addColorStop(1.0, 'green')
this.context.fillStyle = grad
this.context.fillRect(0, 0, 500, 500)
})
}
.width('100%')
.height('100%')
}}
// xxx.ets
@Entry
@Component
struct Page45 {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() => {
var grad = this.context.createLinearGradient(50, 0, 300, 100)
grad.addColorStop(0.0, 'red')
grad.addColorStop(0.5, 'white')
grad.addColorStop(1.0, 'green')
this.context.fillStyle = grad
this.context.fillRect(0, 0, 500, 500)
})
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_0000001256858381](figures/en-us_image_0000001256858381.png)
......
......@@ -133,17 +133,18 @@ onBreakpointChange(callback: (breakpoints: string) => void)
struct GridRowExample {
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown]
@State currentBp: string = 'unknown'
build() {
Column() {
GridRow({
columns: 5,
gutter: {x:5, y:10},
breakpoints: {value:["400vp", "600vp", "800vp"],
reference: BreakpointsReference.WindowSize},
gutter: { x: 5, y: 10 },
breakpoints: { value: ["400vp", "600vp", "800vp"],
reference: BreakpointsReference.WindowSize },
direction: GridRowDirection.Row
}) {
ForEach(this.bgColors, (color)=>{
GridCol({ span: {xs:1, sm:2, md:3, lg:4}}) {
ForEach(this.bgColors, (color) => {
GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }) {
Row().width("100%").height("20vp")
}.borderColor(color).borderWidth(2)
})
......@@ -151,8 +152,8 @@ struct GridRowExample {
.onBreakpointChange((breakpoint) => {
this.currentBp = breakpoint
})
}.width('80%').margin({ left: 10,top: 5, bottom:5 }).height(200)
.border({color:Color.Blue, width:2})
}.width('80%').margin({ left: 10, top: 5, bottom: 5 }).height(200)
.border({ color: '#880606', width: 2 })
}
}
```
......
......@@ -10,7 +10,7 @@ The **\<list>** component provides a list container that presents a series of li
## Child Components
This component supports the [\<ListItem>](ts-container-listitem.md) and [\<ListItemGroup>](ts-container-listitemgroup.md) child components.
This component supports the **[\<ListItem>](ts-container-listitem.md)** and **[\<ListItemGroup>](ts-container-listitemgroup.md)** child components.
## APIs
......@@ -34,14 +34,14 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.<br>Default value: **Axis.Vertical**|
| divider | {<br>strokeWidth: [Length](ts-types.md#length),<br>color?:[ResourceColor](ts-types.md),<br>startMargin?: Length,<br>endMargin?: Length<br>} \| null | Style of the divider for the list items. By default, there is no divider.<br>- **strokeWidth**: stroke width of the divider.<br>- **color**: color of the divider.<br>- **startMargin**: distance between the divider and the start edge of the list.<br>- **endMargin**: distance between the divider and the end edge of the list.|
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off**|
| cachedCount | number | Number of list items to be preloaded. For details, see [Minimizing White Blocks During Swiping](../../ui/ui-ts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).<br>Default value: **1**|
| editMode | boolean | Whether to enter editing mode.<br>Default value: **false**|
| cachedCount | number | Number of list items or list item groups to be preloaded. A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/ui-ts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).<br>Default value: **1**|
| editMode<sup>(deprecated)</sup> | boolean | Whether to enter editing mode.<br>This API is deprecated since API version 9.<br>Default value: **false**|
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect.<br>Default value: **EdgeEffect.Spring**|
| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.<br>Default value: **false**<br>- **false**: No chained animations are displayed.<br>- **true**: Chained animations are displayed.|
| multiSelectable<sup>8+</sup> | boolean | Whether to enable mouse frame selection.<br>Default value: **false**<br>- **false**: The mouse frame selection is disabled.<br>- **true**: The mouse frame selection is enabled.|
| lanes<sup>9+</sup> | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:<br>Number of columns in which the list items are arranged along the cross axis.<br>Default value: **1**<br>The rules are as follows:<br>- If the value is set to a number, the column width is determined based on the specified number and the cross-axis width of the **\<List>** component.<br>- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\<List>** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized. For example, if **lanes** is set to **{minLength: 40vp, maxLength: 60vp}** and the width of the **\<List>** component is 70 vp, the list items are arranged in one column with their alignment compliant with the **alignListItem** settings. If the width of the **\<List>** component is changed to 80 vp, which is twice the value of **minLength**, the list items are arranged in two columns.|
| alignListItem<sup>9+</sup> | ListItemAlign | Alignment mode of list items along the cross axis when: Cross-axis width of the **\<List>** component > Cross-axis width of list items x Value of **lanes**.<br>Default value: **ListItemAlign.Start**|
| sticky<sup>9+</sup> | StickyStyle | Whether to pin the header to the top or the footer to the bottom in the **\<ListItemGroup>** component. This attribute is used together with the **\<ListItemGroup>** component.<br>Default value: **StickyStyle.None**<br>**NOTE**<br>The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.|
| sticky<sup>9+</sup> | StickyStyle | Whether to pin the header to the top or the footer to the bottom in the **\<ListItemGroup>** component. This attribute is used together with the **[\<ListItemGroup>](ts-container-listitemgroup.md)** component.<br>Default value: **StickyStyle.None**<br>**NOTE**<br>The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.|
## ListItemAlign<sup>9+</sup>
......@@ -65,13 +65,13 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Description|
| -------- | -------- |
| onItemDelete(event: (index: number) => boolean) | Triggered when a list item is deleted.<br>- **index**: index of the deleted list item.|
| onItemDelete<sup>(deprecated)</sup>(event: (index: number) => boolean) | Triggered when a list item is deleted.<br>This API is deprecated since API version 9.<br>- **index**: index of the deleted list item.|
| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.<br>- **scrollOffset**: scroll offset.<br>- **[scrollState](#scrollstate)**: current scroll state.|
| onScrollIndex(event: (start: number, end: number) => void) | Triggered when scrolling starts.<br>When calculating the index value, the **\<ListItemGroup>** accounts for one index value as a whole, and the index values of the list items within are not calculated.<br>- **start**: index of the scroll start position.<br>- **end**: index of the scroll end position.|
| onReachStart(event: () => void) | Triggered when the list reaches the start position.|
| onReachEnd(event: () => void) | Triggered when the list reaches the end position.|
| onScrollBegin<sup>9+</sup>(event: (dx: number, dy: number) => { dxRemain: number, dyRemain: number }) | Triggered when the list starts to scroll.<br>- **dx**: amount by which the list will scroll in the horizontal direction.<br>- **dy**: amount by which the list will scroll in the vertical direction.<br>- **dxRemain**: remaining amount by which the list can scroll in the horizontal direction.<br>- **dyRemain**: remaining amount by which the list can scroll in the vertical direction.|
| onScrollStop(event: () => void) | Triggered when the list stops scrolling.|
| onScrollBegin<sup>9+</sup>(event: (dx: number, dy: number) => { dxRemain: number, dyRemain: number }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.<br>- **dx**: amount by which the list will scroll in the horizontal direction.<br>- **dy**: amount by which the list will scroll in the horizontal direction.<br>- **dxRemain**: amount by which the list actually scrolls in the horizontal direction.<br>- **dyRemain**: amount by which the list actually scrolls in the vertical direction.|
| onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event will not be triggered if the scrolling is initiated by using [Scroller](ts-container-scroll.md#scroller).|
| onItemMove(event: (from: number, to: number) => boolean) | Triggered when a list item moves.<br>- **from**: index of the item before moving.<br>- **to**: index of the item after moving.|
| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => ((() => any) \| void) | Triggered when a list element starts to be dragged.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).<br>- **itemIndex**: index of the dragged list element.|
| onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the list.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).|
......@@ -84,12 +84,12 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Description |
| ------ | ------------------------- |
| Idle | Not scrolling. |
| Scroll | Inertial scrolling. |
| Fling | Finger dragging. |
| Scroll | Finger dragging. |
| Fling | Inertial scrolling. |
> **NOTE**
>
> To enable the editable mode for a list, the following conditions must be met:
> To enable the editable mode for a list, the following conditions must be met: (This feature is deprecated since API version 9.)
>
> - **editMode** is set to **true**.
>
......@@ -99,7 +99,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
>
> To enable dragging for a list item, the following conditions must be met:
>
> - **editMode** is set to **true**.
> - **editMode** is set to **true**. (This is not required since API version 9.)
>
> - The list item is bound to the **onDragStart** event and the event returns a floating UI during event callback.
......@@ -112,43 +112,31 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
@Component
struct ListExample {
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@State editFlag: boolean = false
build() {
Stack({ alignContent: Alignment.TopStart }) {
Column() {
List({ space: 20, initialIndex: 0 }) {
ForEach(this.arr, (item) => {
ListItem() {
Text('' + item)
.width('100%').height(100).fontSize(16)
.textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF)
}.editable(true)
}, item => item)
}
.listDirection(Axis.Vertical) // Arrangement direction
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Divider
.edgeEffect(EdgeEffect.None) // No effect when the list scrolls to the edge.
.chainAnimation(false) // Chained animations are disabled.
.onScrollIndex((firstIndex: number, lastIndex: number) => {
console.info('first' + firstIndex)
console.info('last' + lastIndex)
})
.editMode(this.editFlag)
.onItemDelete((index: number) => {
console.info(this.arr[index] + 'Delete')
this.arr.splice(index, 1)
console.info(JSON.stringify(this.arr))
this.editFlag = false
return true
}).width('90%')
}.width('100%')
Button('edit list')
.onClick(() => {
this.editFlag = !this.editFlag
}).margin({ top: 5, left: 20 })
}.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 })
Column() {
List({ space: 20, initialIndex: 0 }) {
ForEach(this.arr, (item) => {
ListItem() {
Text('' + item)
.width('100%').height(100).fontSize(16)
.textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF)
}
}, item => item)
}
.listDirection(Axis.Vertical) // Arrangement direction
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Divider
.edgeEffect(EdgeEffect.Spring) // No effect when the list scrolls to the edge.
.onScrollIndex((firstIndex: number, lastIndex: number) => {
console.info('first' + firstIndex)
console.info('last' + lastIndex)
})
.width('90%')
}
.width('100%')
.height('100%')
.backgroundColor(0xDCDCDC)
.padding({ top: 5 })
}
}
```
......
......@@ -236,17 +236,21 @@ struct ScrollExample {
struct NestedScroll {
@State listPosition: number = 0; // 0 indicates scrolling to the top of the list, 1 indicates scrolling to the middle 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()
private scrollerForScroll: Scroller = new Scroller()
private scrollerForList: Scroller = new Scroller()
build() {
Flex() {
Scroll(this.scroller) {
Scroll(this.scrollerForScroll) {
Column() {
Text("Scroll Area")
.width("100%").height("40%").backgroundColor(0X330000FF)
.fontSize(16).textAlign(TextAlign.Center)
.onClick(() => {
this.scrollerForList.scrollToIndex(5)
})
List({ space: 20 }) {
List({ space: 20, scroller: this.scrollerForList }) {
ForEach(this.arr, (item) => {
ListItem() {
Text("ListItem" + item)
......@@ -255,7 +259,9 @@ struct NestedScroll {
}.width("100%").height(100)
}, item => item)
}
.width("100%").height("50%").edgeEffect(EdgeEffect.None)
.width("100%")
.height("50%")
.edgeEffect(EdgeEffect.None)
.onReachStart(() => {
this.listPosition = 0
})
......@@ -264,7 +270,7 @@ struct NestedScroll {
})
.onScrollBegin((dx: number, dy: number) => {
if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) {
this.scroller.scrollBy(0, -dy)
this.scrollerForScroll.scrollBy(0, -dy)
return { dxRemain: dx, dyRemain: 0 }
}
this.listPosition = 1
......
......@@ -39,4 +39,4 @@ struct StackExample {
}
```
![en-us_image_0000001212378400](figures/en-us_image_0000001212378400.jpg)
![en-us_image_0000001219982699](figures/en-us_image_0000001219982699.PNG)
......@@ -23,7 +23,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Description|
| -------- | -------- | -------- |
| tabBar | string \| Resource \| {<br>icon?: string \| Resource,<br>text?: string \| Resource<br>}<br>\| [CustomBuilder](ts-types.md)<sup>8+</sup> | Content displayed on the tab bar.<br>**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).<br>**NOTE**<br>If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image. |
| tabBar | string \| Resource \| {<br>icon?: string \| Resource,<br>text?: string \| Resource<br>}<br>\| [CustomBuilder](ts-types.md)<sup>8+</sup> | Content displayed on the tab bar.<br>**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).<br>> **NOTE**<br>If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image.|
> **NOTE**
> - The **\<TabContent>** component does not support setting of the common width attribute. By default, its width is the same as that of the parent **\<Tabs>** component.
......@@ -33,82 +33,164 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
## Example
Example 1:
```ts
// xxx.ets
@Entry
@Component
struct TabContentExample {
@State fontColor: string = 'rgba(0, 0, 0, 0.4)'
@State selectedFontColor: string = 'rgba(10, 30, 255, 1)'
struct TabContentExample {
@State fontColor: string = '#182431'
@State selectedFontColor: string = '#007DFF'
@State currentIndex: number = 0
private controller: TabsController = new TabsController()
@Builder TabBuilder(index: number) {
Column() {
Image(this.currentIndex === index ? '/resources/ic_public_contacts_filled_selected.png' : '/resources/ic_public_contacts_filled.png')
.width(10)
.height(10)
.opacity(this.currentIndex === index ? 1 : 0.4)
Image(this.currentIndex === index ? '/common/public_icon_on.svg' : '/common/public_icon_off.svg')
.width(24)
.height(24)
.margin({ bottom: 4 })
.objectFit(ImageFit.Contain)
Text(`Tab${(index > 2 ? (index - 1) : index) + 1}`)
Text(`Tab${index + 1}`)
.fontColor(this.currentIndex === index ? this.selectedFontColor : this.fontColor)
.fontSize(10)
.margin({top: 2})
}
}
@Builder AddBuilder() {
Column() {
Image(this.currentIndex === 2 ? '/resources/ic_public_add_norm_filled_selected.png' : '/resources/ic_public_add_norm_filled.png')
.width(this.currentIndex === 2 ? 26 : 24)
.height(this.currentIndex === 2 ? 26 : 24)
.opacity(this.currentIndex === 2 ? 1 : 0.4)
.objectFit(ImageFit.Contain)
.animation({duration: 200})
}
.fontWeight(500)
.lineHeight(14)
}.width('100%')
}
build() {
Column() {
Tabs({ barPosition: BarPosition.End, controller: this.controller }) {
TabContent() {
Flex({justifyContent: FlexAlign.Center}) {
Text('Tab1').fontSize(32)
}
Column() {
Text('Tab1')
.fontSize(36)
.fontColor('#182431')
.fontWeight(500)
.opacity(0.4)
.margin({ top: 30, bottom: 56.5 })
Divider()
.strokeWidth(0.5)
.color('#182431')
.opacity(0.05)
}.width('100%')
}.tabBar(this.TabBuilder(0))
TabContent() {
Flex({justifyContent: FlexAlign.Center}) {
Text('Tab2').fontSize(32)
}
Column() {
Text('Tab2')
.fontSize(36)
.fontColor('#182431')
.fontWeight(500)
.opacity(0.4)
.margin({ top: 30, bottom: 56.5 })
Divider()
.strokeWidth(0.5)
.color('#182431')
.opacity(0.05)
}.width('100%')
}.tabBar(this.TabBuilder(1))
TabContent() {
Flex({justifyContent: FlexAlign.Center}) {
Text('Add').fontSize(32)
}
}.tabBar(this.AddBuilder())
Column() {
Text('Tab3')
.fontSize(36)
.fontColor('#182431')
.fontWeight(500)
.opacity(0.4)
.margin({ top: 30, bottom: 56.5 })
Divider()
.strokeWidth(0.5)
.color('#182431')
.opacity(0.05)
}.width('100%')
}.tabBar(this.TabBuilder(2))
TabContent() {
Flex({justifyContent: FlexAlign.Center}) {
Text('Tab3').fontSize(32)
}
Column() {
Text('Tab4')
.fontSize(36)
.fontColor('#182431')
.fontWeight(500)
.opacity(0.4)
.margin({ top: 30, bottom: 56.5 })
Divider()
.strokeWidth(0.5)
.color('#182431')
.opacity(0.05)
}.width('100%')
}.tabBar(this.TabBuilder(3))
TabContent() {
Flex({justifyContent: FlexAlign.Center}) {
Text('Tab4').fontSize(32)
}
}.tabBar(this.TabBuilder(4))
}
.vertical(false)
.barWidth(300).barHeight(56)
.barHeight(56)
.onChange((index: number) => {
this.currentIndex = index
})
.width(360)
.height(190)
.backgroundColor('#F1F3F5')
.margin({ top: 38 })
}.width('100%')
}
}
```
![tabContent](figures/tabContent1.gif)
Example 2:
```ts
// xxx.ets
@Entry
@Component
struct TabContentExample {
@State fontColor: string = '#182431'
@State selectedFontColor: string = '#007DFF'
@State currentIndex: number = 0
private controller: TabsController = new TabsController()
@Builder TabBuilder(index: number) {
Column() {
Image(this.currentIndex === index ? '/common/public_icon_on.svg' : '/common/public_icon_off.svg')
.width(24)
.height(24)
.margin({ bottom: 4 })
.objectFit(ImageFit.Contain)
Text('Tab')
.fontColor(this.currentIndex === index ? this.selectedFontColor : this.fontColor)
.fontSize(10)
.fontWeight(500)
.lineHeight(14)
}.width('100%').height('100%').justifyContent(FlexAlign.Center)
}
build() {
Column() {
Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
TabContent()
.tabBar(this.TabBuilder(0))
TabContent()
.tabBar(this.TabBuilder(1))
TabContent()
.tabBar(this.TabBuilder(2))
TabContent()
.tabBar(this.TabBuilder(3))
}
.vertical(true)
.barWidth(96)
.barHeight(414)
.onChange((index: number) => {
this.currentIndex = index
})
.width('90%').backgroundColor('rgba(241, 243, 245, 0.95)')
}.width('100%').height(200).margin({ top: 5 })
.width(96)
.height(414)
.backgroundColor('#F1F3F5')
.margin({ top: 52 })
}.width('100%')
}
}
```
![en-us_image_0000001256978331](figures/en-us_image_0000001256978331.gif)
![tabContent](figures/tabContent2.gif)
......@@ -2,14 +2,14 @@
The **\<Tabs>** component is a container component that allows users to switch between content views through tabs. Each tab page corresponds to a content view.
> **NOTE**
> **NOTE**<br>
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
This component can contain multiple [\<TabContent>](ts-container-tabcontent.md) components.
Only the [\<TabContent>](ts-container-tabcontent.md) child component is supported.
## APIs
......@@ -20,7 +20,7 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| barPosition | BarPosition | No| Tab bar position for creating the **\<Tabs>** container component.<br>Default value: **BarPosition.Start**|
| barPosition | BarPosition | No| Position of the **\<Tabs>** component.<br>Default value: **BarPosition.Start**|
| index | number | No| Initial tab index.<br>Default value: **0**|
| controller | [TabsController](#tabscontroller) | No| Tab controller.|
......@@ -49,8 +49,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Description|
| -------- | -------- |
| Scrollable | The width of each tab is defined by its label length. The tabs are scrollable when the total width exceeds the tab bar width.|
| Fixed | The width of each tab is fixed, determined by evenly allocating the tab bar width among the tabs.|
| Scrollable | The width of each tab is determined by the actual layout. The tabs are scrollable in the following case: In horizontal layout, the total width exceeds the tab bar width; in horizontal layout, the total height exceeds the tab bar height.|
| Fixed | The width of each tab is determined by equally dividing the number of tabs by the bar width (or the bar height in vertical layout).|
## Events
......@@ -62,7 +62,7 @@ In addition to the [universal events](ts-universal-events-click.md), the followi
## TabsController
Defines a tab controller, which is used to control switching of tabs.
Defines a tab controller, which is used to control switching of tabs. One **TabsController** cannot control multiple **\<Tabs>** components.
### Objects to Import
......@@ -91,36 +91,60 @@ Switches to the specified tab.
@Entry
@Component
struct TabsExample {
@State fontColor: string = '#182431'
@State selectedFontColor: string = '#007DFF'
@State currentIndex: number = 0
private controller: TabsController = new TabsController()
@Builder TabBuilder(index: number, name: string) {
Column() {
Text(name)
.fontColor(this.currentIndex === index ? this.selectedFontColor : this.fontColor)
.fontSize(16)
.fontWeight(this.currentIndex === index ? 500 : 400)
.lineHeight(22)
.margin({ top: 17, bottom: 7 })
Divider()
.strokeWidth(2)
.color('#007DFF')
.opacity(this.currentIndex === index ? 1 : 0)
}.width('100%')
}
build() {
Column() {
Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
TabContent() {
Column().width('100%').height('100%').backgroundColor(Color.Pink)
}.tabBar('pink')
Column().width('100%').height('100%').backgroundColor('#00CB87')
}.tabBar(this.TabBuilder(0, 'green'))
TabContent() {
Column().width('100%').height('100%').backgroundColor(Color.Yellow)
}.tabBar('yellow')
Column().width('100%').height('100%').backgroundColor('#007DFF')
}.tabBar(this.TabBuilder(1, 'blue'))
TabContent() {
Column().width('100%').height('100%').backgroundColor(Color.Blue)
}.tabBar('blue')
Column().width('100%').height('100%').backgroundColor('#FFBF00')
}.tabBar(this.TabBuilder(2, 'yellow'))
TabContent() {
Column().width('100%').height('100%').backgroundColor(Color.Green)
}.tabBar('green')
Column().width('100%').height('100%').backgroundColor('#E67C92')
}.tabBar(this.TabBuilder(3, 'pink'))
}
.vertical(true).scrollable(true).barMode(BarMode.Fixed)
.barWidth(70).barHeight(150).animationDuration(400)
.vertical(false)
.barMode(BarMode.Fixed)
.barWidth(360)
.barHeight(56)
.animationDuration(400)
.onChange((index: number) => {
console.info(index.toString())
this.currentIndex = index
})
.width('90%').backgroundColor(0xF5F5F5)
}.width('100%').height(150).margin({ top: 5 })
.width(360)
.height(296)
.margin({ top: 52 })
.backgroundColor('#F1F3F5')
}.width('100%')
}
}
```
![en-us_image_0000001212218430](figures/en-us_image_0000001212218430.gif)
![tabs2](figures/tabs2.gif)
......@@ -23,25 +23,25 @@ OffscreenCanvasRenderingContext2D(width: number, height: number, setting: Render
## Attributes
| Name | Type | Description |
| ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.<br>- When the type is **string**, this attribute indicates the color of the filling area.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. |
| [lineWidth](#linewidth) | number | Line width. |
| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.<br>- When the type is **\<color>**, this parameter indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. |
| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:<br>- **butt**: The endpoints of the line are squared off.<br>- **round**: The endpoints of the line are rounded.<br>- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.<br>- Default value: **'butt'** |
| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:<br>- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.<br>- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.<br>- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.<br>- Default value: **'miter'** |
| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.<br>- Default value: **10** |
| [font](#font) | string | Font style.<br>Syntax: ctx.font='font-size font-family'<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>(Optional) **font-family**: font family.<br>Syntax: ctx.font='font-style font-weight font-size font-family'<br>- (Optional) **font-style**: font style. Available values are **normal** and **italic**.<br>- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.<br>Default value: **'normal normal 14px sans-serif'** |
| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:<br>- **left**: The text is left-aligned.<br>- **right**: The text is right-aligned.<br>- **center**: The text is center-aligned.<br>- **start**: The text is aligned with the start bound.<br>- **end**: The text is aligned with the end bound.<br>**NOTE**<br>In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.<br>- Default value: **'left'** |
| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:<br>- **alphabetic**: The text baseline is the normal alphabetic baseline.<br>- **top**: The text baseline is on the top of the text bounding box.<br>- **hanging**: The text baseline is a hanging baseline over the text.<br>- **middle**: The text baseline is in the middle of the text bounding box.<br>**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br>- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.<br>- Default value: **'alphabetic'** |
| [globalAlpha](#globalalpha) | number | Opacity.<br>**0.0**: completely transparent.<br>**1.0**: completely opaque. |
| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.<br>- Default value: **0.0** |
| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.<br>- Default value: **'source-over'** |
| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.<br>- Default value: **0.0** |
| [shadowColor](#shadowcolor) | string | Shadow color. |
| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. |
| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. |
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.<br>- Default value: **true** |
| Name | Type | Description |
| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.<br>- When the type is **string**, this attribute indicates the color of the filling area.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.|
| [lineWidth](#linewidth) | number | Line width. |
| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.<br>- When the type is **\<color>**, this parameter indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.|
| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:<br>- **butt**: The endpoints of the line are squared off.<br>- **round**: The endpoints of the line are rounded.<br>- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.<br>- Default value: **'butt'**|
| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:<br>- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.<br>- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.<br>- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.<br>- Default value: **'miter'**|
| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.<br>- Default value: **10**|
| [font](#font) | string | Font style.<br>Syntax: ctx.font='font-size font-family'<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>(Optional) **font-family**: font family.<br>Syntax: ctx.font='font-style font-weight font-size font-family'<br>- (Optional) **font-style**: font style. Available values are **normal** and **italic**.<br>- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.<br>Default value: **'normal normal 14px sans-serif'**|
| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:<br>- **left**: The text is left-aligned.<br>- **right**: The text is right-aligned.<br>- **center**: The text is center-aligned.<br>- **start**: The text is aligned with the start bound.<br>- **end**: The text is aligned with the end bound.<br>**NOTE**<br>In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.<br>- Default value: **'left'**|
| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:<br>- **alphabetic**: The text baseline is the normal alphabetic baseline.<br>- **top**: The text baseline is on the top of the text bounding box.<br>- **hanging**: The text baseline is a hanging baseline over the text.<br>- **middle**: The text baseline is in the middle of the text bounding box.<br>**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br>- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.<br>- Default value: **'alphabetic'**|
| [globalAlpha](#globalalpha) | number | Opacity.<br>**0.0**: completely transparent.<br>**1.0**: completely opaque. |
| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.<br>- Default value: **0.0**|
| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.<br>- Default value: **'source-over'**|
| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.<br>- Default value: **0.0**|
| [shadowColor](#shadowcolor) | string | Shadow color. |
| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. |
| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. |
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.<br>- Default value: **true**|
> **NOTE**
>
......@@ -78,7 +78,7 @@ struct FillStyleExample {
}
```
![en-us_image_0000001211898510](figures/en-us_image_0000001211898510.png)
![en-us_image_0000001193872516](figures/en-us_image_0000001193872516.png)
### lineWidth
......@@ -111,7 +111,7 @@ struct LineWidthExample {
}
```
![en-us_image_0000001257058439](figures/en-us_image_0000001257058439.png)
![en-us_image_0000001238832403](figures/en-us_image_0000001238832403.png)
### strokeStyle
......@@ -145,7 +145,7 @@ struct StrokeStyleExample {
}
```
![en-us_image_0000001257058429](figures/en-us_image_0000001257058429.png)
![en-us_image_0000001238712437](figures/en-us_image_0000001238712437.png)
### lineCap
......@@ -182,7 +182,7 @@ struct LineCapExample {
}
```
![en-us_image_0000001256858427](figures/en-us_image_0000001256858427.png)
![en-us_image_0000001194192454](figures/en-us_image_0000001194192454.PNG)
### lineJoin
......@@ -220,7 +220,7 @@ struct LineJoinExample {
}
```
![en-us_image_0000001256858429](figures/en-us_image_0000001256858429.png)
![en-us_image_0000001194352450](figures/en-us_image_0000001194352450.png)
### miterLimit
......@@ -258,7 +258,7 @@ struct MiterLimit {
}
```
![en-us_image_0000001212218472](figures/en-us_image_0000001212218472.png)
![en-us_image_0000001238952397](figures/en-us_image_0000001238952397.png)
### font
......@@ -291,7 +291,7 @@ struct Fonts {
}
```
![en-us_image_0000001211898508](figures/en-us_image_0000001211898508.png)
![en-us_image_0000001194032476](figures/en-us_image_0000001194032476.png)
### textAlign
......@@ -339,7 +339,7 @@ struct CanvasExample {
}
```
![en-us_image_0000001257138377](figures/en-us_image_0000001257138377.png)
![en-us_image_0000001239032423](figures/en-us_image_0000001239032423.png)
### textBaseline
......@@ -387,7 +387,7 @@ struct TextBaseline {
}
```
![en-us_image_0000001256978375](figures/en-us_image_0000001256978375.png)
![en-us_image_0000001193872518](figures/en-us_image_0000001193872518.png)
### globalAlpha
......@@ -423,7 +423,7 @@ struct GlobalAlpha {
}
```
![en-us_image_0000001211898506](figures/en-us_image_0000001211898506.png)
![en-us_image_0000001238832405](figures/en-us_image_0000001238832405.png)
### lineDashOffset
......@@ -458,7 +458,7 @@ struct LineDashOffset {
}
```
![en-us_image_0000001212058506](figures/en-us_image_0000001212058506.png)
![en-us_image_0000001238712439](figures/en-us_image_0000001238712439.png)
### globalCompositeOperation
......@@ -513,7 +513,7 @@ struct GlobalCompositeOperation {
}
```
![en-us_image_0000001212218474](figures/en-us_image_0000001212218474.png)
![en-us_image_0000001194192456](figures/en-us_image_0000001194192456.png)
### shadowBlur
......@@ -548,7 +548,7 @@ struct ShadowBlur {
}
```
![en-us_image_0000001211898514](figures/en-us_image_0000001211898514.png)
![en-us_image_0000001194352452](figures/en-us_image_0000001194352452.png)
### shadowColor
......@@ -583,7 +583,7 @@ struct ShadowColor {
}
```
![en-us_image_0000001212058502](figures/en-us_image_0000001212058502.png)
![en-us_image_0000001238952399](figures/en-us_image_0000001238952399.png)
### shadowOffsetX
......@@ -619,7 +619,7 @@ struct ShadowOffsetX {
}
```
![en-us_image_0000001257138379](figures/en-us_image_0000001257138379.png)
![en-us_image_0000001194032478](figures/en-us_image_0000001194032478.png)
### shadowOffsetY
......@@ -655,7 +655,7 @@ struct ShadowOffsetY {
}
```
![en-us_image_0000001257058427](figures/en-us_image_0000001257058427.png)
![en-us_image_0000001239032425](figures/en-us_image_0000001239032425.png)
### imageSmoothingEnabled
......@@ -689,7 +689,7 @@ struct ImageSmoothingEnabled {
}
```
![en-us_image_0000001257138385](figures/en-us_image_0000001257138385.png)
![en-us_image_0000001193872520](figures/en-us_image_0000001193872520.png)
## Methods
......@@ -703,7 +703,7 @@ Fills a rectangle on the canvas.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ------------- |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.|
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.|
......@@ -739,7 +739,7 @@ Fills a rectangle on the canvas.
}
```
![en-us_image_0000001257138375](figures/en-us_image_0000001257138375.png)
![en-us_image_0000001194192436](figures/en-us_image_0000001194192436.png)
### strokeRect
......@@ -748,16 +748,16 @@ strokeRect(x: number, y: number, w: number, h: number): void
Draws an outlined rectangle on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ------------ |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.|
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.|
| width | number | Yes | 0 | Width of the rectangle. |
| height | number | Yes | 0 | Height of the rectangle. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -786,7 +786,7 @@ Draws an outlined rectangle on the canvas.
}
```
![en-us_image_0000001212378436](figures/en-us_image_0000001212378436.png)
![en-us_image_0000001194352436](figures/en-us_image_0000001194352436.png)
### clearRect
......@@ -795,16 +795,16 @@ clearRect(x: number, y: number, w: number, h: number): void
Clears the content in a rectangle on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ------------- |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.|
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.|
| width | number | Yes | 0 | Width of the rectangle. |
| height | number | Yes | 0 | Height of the rectangle. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -835,7 +835,7 @@ Clears the content in a rectangle on the canvas.
}
```
![en-us_image_0000001212058500](figures/en-us_image_0000001212058500.png)
![en-us_image_0000001238952377](figures/en-us_image_0000001238952377.png)
### fillText
......@@ -846,14 +846,14 @@ Draws filled text on the canvas.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | ---- | ---- | --------------- |
| text | string | Yes | "" | Text to draw. |
| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.|
| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.|
| maxWidth | number | No | - | Maximum width allowed for the text. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -883,7 +883,7 @@ Draws filled text on the canvas.
}
```
![en-us_image_0000001257058437](figures/en-us_image_0000001257058437.png)
![en-us_image_0000001194032458](figures/en-us_image_0000001194032458.png)
### strokeText
......@@ -894,14 +894,14 @@ Draws a text stroke on the canvas.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | ---- | ---- | --------------- |
| text | string | Yes | "" | Text to draw. |
| x | number | Yes | 0 | X-coordinate of the lower left corner of the text.|
| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.|
| maxWidth | number | No | - | Maximum width of the text to be drawn. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -931,7 +931,7 @@ Draws a text stroke on the canvas.
}
```
![en-us_image_0000001212218466](figures/en-us_image_0000001212218466.png)
![en-us_image_0000001238952401](figures/en-us_image_0000001238952401.png)
### measureText
......@@ -940,13 +940,13 @@ measureText(text: string): TextMetrics
Returns a **TextMetrics** object used to obtain the width of specified text.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ---------- |
| text | string | Yes | "" | Text to be measured.|
**Return value**
**Return value**
| Type | Description |
| ----------- | ------- |
......@@ -970,7 +970,7 @@ Returns a **TextMetrics** object used to obtain the width of specified text.
| hangingBaseline | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the hanging baseline of the line box. The current value is **0**.|
| ideographicBaseline | number | Distance from the horizontal line indicated by the **CanvasRenderingContext2D.textBaseline** attribute to the ideographic baseline of the line box. The current value is **0**.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1001,7 +1001,7 @@ Returns a **TextMetrics** object used to obtain the width of specified text.
}
```
![en-us_image_0000001256858431](figures/en-us_image_0000001256858431.png)
![en-us_image_0000001194032480](figures/en-us_image_0000001194032480.png)
### stroke
......@@ -1010,13 +1010,13 @@ stroke(path?: Path2D): void
Strokes a path.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ---------------------------------------- | ---- | ---- | ------------ |
| path | [Path2D](ts-components-canvas-path2d.md) | No | null | A **Path2D** path to draw.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1050,7 +1050,7 @@ Strokes a path.
}
```
![en-us_image_0000001257138373](figures/en-us_image_0000001257138373.png)
![en-us_image_0000001238832389](figures/en-us_image_0000001238832389.png)
### beginPath
......@@ -1059,7 +1059,7 @@ beginPath(): void
Creates a drawing path.
**Example**
**Example**
```ts
// xxx.ets
......@@ -1093,7 +1093,7 @@ Creates a drawing path.
}
```
![en-us_image_0000001212378440](figures/en-us_image_0000001212378440.png)
![en-us_image_0000001193872522](figures/en-us_image_0000001193872522.png)
### moveTo
......@@ -1102,14 +1102,14 @@ moveTo(x: number, y: number): void
Moves a drawing path to a target position on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------- |
| x | number | Yes | 0 | X-coordinate of the target position.|
| y | number | Yes | 0 | Y-coordinate of the target position.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1141,7 +1141,7 @@ Moves a drawing path to a target position on the canvas.
}
```
![en-us_image_0000001212058498](figures/en-us_image_0000001212058498.png)
![en-us_image_0000001238832409](figures/en-us_image_0000001238832409.png)
### lineTo
......@@ -1150,14 +1150,14 @@ lineTo(x: number, y: number): void
Connects the current point to a target position using a straight line.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------- |
| x | number | Yes | 0 | X-coordinate of the target position.|
| y | number | Yes | 0 | Y-coordinate of the target position.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1189,7 +1189,7 @@ Connects the current point to a target position using a straight line.
}
```
![en-us_image_0000001257058435](figures/en-us_image_0000001257058435.png)
![en-us_image_0000001238712443](figures/en-us_image_0000001238712443.png)
### closePath
......@@ -1198,7 +1198,7 @@ closePath(): void
Draws a closed path.
**Example**
**Example**
```ts
// xxx.ets
......@@ -1232,7 +1232,7 @@ Draws a closed path.
}
```
![en-us_image_0000001257058431](figures/en-us_image_0000001257058431.png)
![en-us_image_0000001194192460](figures/en-us_image_0000001194192460.png)
### createPattern
......@@ -1243,7 +1243,7 @@ Creates a pattern for image filling based on a specified source image and repeti
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) | Yes | null | Source image. For details, see **ImageBitmap**. |
| repetition | string | Yes | "" | Repetition mode. The value can be **"repeat"**, **"repeat-x"**, **"repeat-y"**, or **"no-repeat"**.|
......@@ -1254,7 +1254,7 @@ Creates a pattern for image filling based on a specified source image and repeti
| ------------------------------- | ----------------------- |
| [CanvasPattern](#canvaspattern) | Created pattern for image filling based on a specified source image and repetition mode.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1286,7 +1286,7 @@ Creates a pattern for image filling based on a specified source image and repeti
}
```
![en-us_image_0000001257138387](figures/en-us_image_0000001257138387.png)
![en-us_image_0000001194352456](figures/en-us_image_0000001194352456.png)
### bezierCurveTo
......@@ -1295,9 +1295,9 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
Draws a cubic bezier curve on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | -------------- |
| cp1x | number | Yes | 0 | X-coordinate of the first parameter of the bezier curve.|
| cp1y | number | Yes | 0 | Y-coordinate of the first parameter of the bezier curve.|
......@@ -1306,7 +1306,7 @@ Draws a cubic bezier curve on the canvas.
| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. |
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -1338,7 +1338,7 @@ Draws a cubic bezier curve on the canvas.
}
```
![en-us_image_0000001212378442](figures/en-us_image_0000001212378442.png)
![en-us_image_0000001238952403](figures/en-us_image_0000001238952403.png)
### quadraticCurveTo
......@@ -1347,16 +1347,16 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
Draws a quadratic curve on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------- |
| cpx | number | Yes | 0 | X-coordinate of the bezier curve parameter.|
| cpy | number | Yes | 0 | Y-coordinate of the bezier curve parameter.|
| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve.|
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1388,7 +1388,7 @@ Draws a quadratic curve on the canvas.
}
```
![en-us_image_0000001256978383](figures/en-us_image_0000001256978383.png)
![en-us_image_0000001194032482](figures/en-us_image_0000001194032482.png)
### arc
......@@ -1397,9 +1397,9 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number,
Draws an arc on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---------------- | ------- | ---- | ----- | ---------- |
| x | number | Yes | 0 | X-coordinate of the center point of the arc.|
| y | number | Yes | 0 | Y-coordinate of the center point of the arc.|
......@@ -1408,7 +1408,7 @@ Draws an arc on the canvas.
| endAngle | number | Yes | 0 | End radian of the arc. |
| counterclockwise | boolean | No | false | Whether to draw the arc counterclockwise.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1439,7 +1439,7 @@ Draws an arc on the canvas.
}
```
![en-us_image_0000001212378430](figures/en-us_image_0000001212378430.png)
![en-us_image_0000001239032429](figures/en-us_image_0000001239032429.png)
### arcTo
......@@ -1448,9 +1448,9 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
Draws an arc based on the radius and points on the arc.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | --------------- |
| x1 | number | Yes | 0 | X-coordinate of the first point on the arc.|
| y1 | number | Yes | 0 | Y-coordinate of the first point on the arc.|
......@@ -1458,7 +1458,7 @@ Draws an arc based on the radius and points on the arc.
| y2 | number | Yes | 0 | Y-coordinate of the second point on the arc.|
| radius | number | Yes | 0 | Radius of the arc. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -1489,7 +1489,7 @@ Draws an arc based on the radius and points on the arc.
}
```
![en-us_image_0000001257138383](figures/en-us_image_0000001257138383.png)
![en-us_image_0000001193872524](figures/en-us_image_0000001193872524.png)
### ellipse
......@@ -1498,9 +1498,9 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number
Draws an ellipse in the specified rectangular region on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---------------- | ------- | ---- | ----- | ----------------- |
| x | number | Yes | 0 | X-coordinate of the ellipse center. |
| y | number | Yes | 0 | Y-coordinate of the ellipse center. |
......@@ -1511,7 +1511,7 @@ Draws an ellipse in the specified rectangular region on the canvas.
| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.|
| counterclockwise | boolean | No | false | Whether to draw the ellipse counterclockwise.<br>**true**: Draw the ellipse counterclockwise.<br>**false**: Draw the ellipse clockwise. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -1541,7 +1541,7 @@ Draws an ellipse in the specified rectangular region on the canvas.
}
```
![en-us_image_0000001256858423](figures/en-us_image_0000001256858423.png)
![en-us_image_0000001194192440](figures/en-us_image_0000001194192440.png)
### rect
......@@ -1550,16 +1550,16 @@ rect(x: number, y: number, w: number, h: number): void
Creates a rectangle on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ------------- |
| x | number | Yes | 0 | X-coordinate of the upper left corner of the rectangle.|
| y | number | Yes | 0 | Y-coordinate of the upper left corner of the rectangle.|
| w | number | Yes | 0 | Width of the rectangle. |
| h | number | Yes | 0 | Height of the rectangle. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -1589,7 +1589,7 @@ Creates a rectangle on the canvas.
}
```
![en-us_image_0000001257138381](figures/en-us_image_0000001257138381.png)
![en-us_image_0000001238712445](figures/en-us_image_0000001238712445.png)
### fill
......@@ -1600,7 +1600,7 @@ Fills the area inside a closed path on the canvas.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------------- | ---- | --------- | ---------------------------------------- |
| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to fill.<br>The options are **"nonzero"** and **"evenodd"**.|
......@@ -1632,7 +1632,7 @@ Fills the area inside a closed path on the canvas.
}
```
![en-us_image_0000001256858421](figures/en-us_image_0000001256858421.png)
![en-us_image_0000001194192462](figures/en-us_image_0000001194192462.png)
fill(path: Path2D, fillRule?: CanvasFillRule): void
......@@ -1641,7 +1641,7 @@ Fills the area inside a closed path on the canvas.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------------- | ---- | --------- | ---------------------------------------- |
| path | Path2D | Yes | | A **Path2D** path to fill. |
| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to fill.<br>The options are **"nonzero"** and **"evenodd"**.|
......@@ -1698,11 +1698,11 @@ Sets the current path to a clipping path.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------------- | ---- | --------- | ---------------------------------------- |
| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to clip.<br>The options are **"nonzero"** and **"evenodd"**.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1735,7 +1735,7 @@ Sets the current path to a clipping path.
}
```
![en-us_image_0000001257058441](figures/en-us_image_0000001257058441.png)
![en-us_image_0000001194032462](figures/en-us_image_0000001194032462.png)
clip(path:Path2D, fillRule?: CanvasFillRule): void
......@@ -1744,12 +1744,12 @@ Sets a closed path to a clipping path.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------------- | ---- | --------- | ---------------------------------------- |
| path | Path2D | Yes | | A **Path2D** path to clip.|
| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to clip.<br>The options are **"nonzero"** and **"evenodd"**.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1795,7 +1795,7 @@ Sets a filter for the image on the canvas. This API is a void API.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ------------ |
| filter | string | Yes | - | Functions that accept various filter effects.|
......@@ -1827,13 +1827,13 @@ rotate(angle: number): void
Rotates a canvas clockwise around its coordinate axes.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ---------------------------------------- |
| angle | number | Yes | 0 | Clockwise rotation angle. You can use **Math.PI / 180** to convert the angle to a radian.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1851,7 +1851,7 @@ Rotates a canvas clockwise around its coordinate axes.
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.rotate(45 * Math.PI / 180) // Rotate the rectangle 45 degrees
this.offContext.rotate(45 * Math.PI / 180)
this.offContext.fillRect(70, 20, 50, 50)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
......@@ -1863,7 +1863,7 @@ Rotates a canvas clockwise around its coordinate axes.
}
```
![en-us_image_0000001212218478](figures/en-us_image_0000001212218478.png)
![en-us_image_0000001238952405](figures/en-us_image_0000001238952405.png)
### scale
......@@ -1872,14 +1872,14 @@ scale(x: number, y: number): void
Scales the canvas based on scale factors.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------- |
| x | number | Yes | 0 | Horizontal scale factor.|
| y | number | Yes | 0 | Vertical scale factor.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1911,7 +1911,7 @@ Scales the canvas based on scale factors.
}
```
![en-us_image_0000001211898516](figures/en-us_image_0000001211898516.png)
![en-us_image_0000001193872498](figures/en-us_image_0000001193872498.png)
### transform
......@@ -1939,7 +1939,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para
| e | number | Yes | 0 | X-axis translation.|
| f | number | Yes | 0 | Y-axis translation.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1975,7 +1975,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para
}
```
![en-us_image_0000001212378438](figures/en-us_image_0000001212378438.png)
![en-us_image_0000001239032431](figures/en-us_image_0000001239032431.png)
### setTransform
......@@ -1986,7 +1986,7 @@ Resets the existing transformation matrix and creates a new transformation matri
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | -------------------- |
| a | number | Yes | 0 | X-axis scale. |
| b | number | Yes | 0 | X-axis skew. |
......@@ -1995,7 +1995,7 @@ Resets the existing transformation matrix and creates a new transformation matri
| e | number | Yes | 0 | X-axis translation.|
| f | number | Yes | 0 | Y-axis translation.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -2037,14 +2037,14 @@ translate(x: number, y: number): void
Moves the origin of the coordinate system.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | -------- |
| x | number | Yes | 0 | X-axis translation.|
| y | number | Yes | 0 | Y-axis translation.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -2088,9 +2088,9 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh:
Draws an image on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ----- | ---------------------------------------- | ---- | ---- | ----------------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7)| Yes | null | Image resource. For details, see **ImageBitmap** or **PixelMap**.|
| sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image. |
......@@ -2102,8 +2102,7 @@ Draws an image on the canvas.
| dw | number | No | 0 | Width of the drawing area. |
| dh | number | No | 0 | Height of the drawing area. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -2132,7 +2131,7 @@ Draws an image on the canvas.
}
```
![en-us_image_0000001256978377](figures/en-us_image_0000001256978377.png)
![en-us_image_0000001238712447](figures/en-us_image_0000001238712447.png)
### createImageData
......@@ -2141,9 +2140,9 @@ createImageData(sw: number, sh: number): ImageData
Creates an **[ImageData](ts-components-canvas-imagedata.md)** object with the specified dimensions.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ------------- |
| sw | number | Yes | 0 | Width of the **ImageData** object.|
| sh | number | Yes | 0 | Height of the **ImageData** object.|
......@@ -2153,9 +2152,9 @@ createImageData(imageData: ImageData): ImageData
Creates an **[ImageData](ts-components-canvas-imagedata.md)** object by copying an existing **ImageData** object.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| --------- | ---------------------------------------- | ---- | ---- | ---------------- |
| imagedata | [ImageData](ts-components-canvas-imagedata.md) | Yes | null | **ImageData** object to copy.|
......@@ -2171,9 +2170,9 @@ getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap
Obtains the **[PixelMap](../apis/js-apis-image.md#pixelmap7)** object created with the pixels within the specified area on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------------- |
| sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.|
| sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.|
......@@ -2193,9 +2192,9 @@ getImageData(sx: number, sy: number, sw: number, sh: number): ImageData
Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created with the pixels within the specified area on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------------- |
| sx | number | Yes | 0 | X-coordinate of the upper left corner of the output area.|
| sy | number | Yes | 0 | Y-coordinate of the upper left corner of the output area.|
......@@ -2208,7 +2207,6 @@ Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created wi
| ---------------------------------------- | ------------- |
| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.|
**Example**
```ts
......@@ -2252,9 +2250,9 @@ putImageData(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY:
Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectangular area on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ----------- | ------ | ---- | ------------ | ----------------------------- |
| imagedata | Object | Yes | null | **ImageData** object with pixels to put onto the canvas. |
| dx | number | Yes | 0 | X-axis offset of the rectangular area on the canvas. |
......@@ -2264,7 +2262,7 @@ Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectang
| dirtyWidth | number | No | Width of the **ImageData** object| Width of the rectangular area to crop the source image. |
| dirtyHeight | number | No | Height of the **ImageData** object| Height of the rectangular area to crop the source image. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -2299,7 +2297,7 @@ Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectang
}
```
![en-us_image_0000001212058496](figures/en-us_image_0000001212058496.png)
![en-us_image_0000001194192464](figures/en-us_image_0000001194192464.png)
### setLineDash
......@@ -2309,7 +2307,7 @@ Sets the dash line style.
**Parameters**
| Name | Type | Description |
| Name | Type | Description |
| -------- | -------- | ------------------- |
| segments | number[] | An array of numbers that specify distances to alternately draw a line and a gap.|
......@@ -2455,9 +2453,9 @@ imageSmoothingQuality(quality: imageSmoothingQuality)
Sets the quality of image smoothing. This API is a void API.
**Parameters**
**Parameters**
| Name | Type | Description |
| Name | Type | Description |
| ------- | --------------------- | ---------------------------------------- |
| quality | imageSmoothingQuality | Quality of image smoothing. The value can be **'low'**, **'medium'**,or **'high'**.|
......@@ -2474,8 +2472,7 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O
| ---------------------------------------- | --------------- |
| [ImageBitmap](ts-components-canvas-imagebitmap.md) | Pixel data rendered on the **OffscreenCanvas**.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -2518,7 +2515,7 @@ restore(): void
Restores the saved drawing context.
**Example**
**Example**
```ts
// xxx.ets
......@@ -2559,7 +2556,7 @@ save(): void
Saves the current drawing context.
**Example**
**Example**
```ts
// xxx.ets
......@@ -2600,16 +2597,16 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void
Creates a linear gradient.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | -------- |
| x0 | number | Yes | 0 | X-coordinate of the start point.|
| y0 | number | Yes | 0 | Y-coordinate of the start point.|
| x1 | number | Yes | 0 | X-coordinate of the end point.|
| y1 | number | Yes | 0 | Y-coordinate of the end point.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -2643,7 +2640,7 @@ Creates a linear gradient.
}
```
![en-us_image_0000001212378434](figures/en-us_image_0000001212378434.png)
![en-us_image_0000001194352460](figures/en-us_image_0000001194352460.png)
### createRadialGradient
......@@ -2652,9 +2649,9 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number,
Creates a linear gradient.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------------- |
| x0 | number | Yes | 0 | X-coordinate of the center of the start circle. |
| y0 | number | Yes | 0 | Y-coordinate of the center of the start circle. |
......@@ -2663,7 +2660,7 @@ Creates a linear gradient.
| y1 | number | Yes | 0 | Y-coordinate of the center of the end circle. |
| r1 | number | Yes | 0 | Radius of the end circle, which must be a non-negative finite number.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -2697,7 +2694,7 @@ Creates a linear gradient.
}
```
![en-us_image_0000001212218480](figures/en-us_image_0000001212218480.png)
![en-us_image_0000001238952407](figures/en-us_image_0000001238952407.png)
## CanvasPattern
......
......@@ -20,46 +20,44 @@ Configure the component transition animations for when a component is inserted o
| -------- | -------- | -------- | -------- |
| type | [TransitionType](ts-appendix-enums.md#transitiontype) | No| Transition type, which includes component addition and deletion by default.<br>Default value: **TransitionType.All**<br>**NOTE**<br>If **type** is not specified, insertion and deletion use the same transition type.|
| opacity | number | No| Opacity of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>Default value: **1**|
| translate | {<br>x? : number,<br>y? : number,<br>z? : number<br>} | No| Translation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>-**x**: distance to translate along the x-axis.<br>-**y**: distance to translate along the y-axis.<br>-**z**: distance to translate along the z-axis.|
| scale | {<br>x? : number,<br>y? : number,<br>z? : number,<br>centerX? : number,<br>centerY? : number<br>} | No| Scaling of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: scale factor along the x-axis.<br>- **y**: scale factor along the y-axis.<br>- **z**: scale factor along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the scale center, respectively.<br>- If the center point is 0, it indicates the upper left corner of the component.<br>|
| rotate | {<br>x?: number,<br>y?: number,<br>z?: number,<br>angle?: Angle,<br>centerX?: Length,<br>centerY?: Length<br>} | No| Rotation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: rotation vector along the x-axis.<br>- **y**: rotation vector along the y-axis.<br>- **z**: rotation vector along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the rotation center, respectively.<br>- If the center point is (0, 0), it indicates the upper left corner of the component.|
| translate | {<br>x? : number \| string,<br>y? : number \| string,<br>z? : number \| string<br>} | No| Translation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>-**x**: distance to translate along the x-axis.<br>-**y**: distance to translate along the y-axis.<br>-**z**: distance to translate along the z-axis.|
| scale | {<br>x? : number,<br>y? : number,<br>z? : number,<br>centerX? : number \| string,<br>centerY? : number \| string<br>} | No| Scaling of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: scale factor along the x-axis.<br>- **y**: scale factor along the y-axis.<br>- **z**: scale factor along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the scale center, respectively. The default values are both **"50%"**.<br>- If the center point is 0, it indicates the upper left corner of the component.<br>|
| rotate | {<br>x?: number,<br>y?: number,<br>z?: number,<br>angle?: number \| string,<br>centerX?: number \| string,<br>centerY?: number \| string<br>} | No| Rotation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: rotation vector along the x-axis.<br>- **y**: rotation vector along the y-axis.<br>- **z**: rotation vector along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the rotation center, respectively. The default values are both **"50%"**.<br>- If the center point is (0, 0), it indicates the upper left corner of the component.|
## Example
The following example shows how to use a button to control the appearance and disappearance of another button, and how to configure the required transition animations.
```ts
// xxx.ets
@Entry
@Component
struct TransitionExample {
@State btn: boolean = false
@State show: string = "show"
@State flag: boolean = true
@State show: string = 'show'
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center,}) {
Button(this.show).width(80).height(30).backgroundColor(0x317aff).margin({bottom:50})
Column() {
Button(this.show).width(80).height(30).margin(30)
.onClick(() => {
// Click the button to show or hide the image.
animateTo({ duration: 1000 }, () => {
this.btn = !this.btn
if(this.btn){
this.show = "hide"
}else{
this.show = "show"
if (this.flag) {
this.show = 'hide'
} else {
this.show = 'show'
}
this.flag = !this.flag
})
})
if (this.btn) {
// The insertion and deletion have different transition effects.
Button() {
Image($r('app.media.bg1')).width("80%").height(300)
}.transition({ type: TransitionType.Insert, scale : {x:0,y:1.0} })
.transition({ type: TransitionType.Delete, scale: { x: 1.0, y: 0.0 } })
if (this.flag) {
// Apply different transition effects to the appearance and disappearance of the image.
Image($r('app.media.testImg')).width(300).height(300)
.transition({ type: TransitionType.Insert, scale: { x: 0, y: 1.0 } })
.transition({ type: TransitionType.Delete, rotate: { angle: 180 } })
}
}.height(400).width("100%").padding({top:100})
}.width('100%')
}
}
```
![en-us_image_0000001211898498](figures/en-us_image_0000001211898498.gif)
![animateTo](figures/animateTo.gif)
......@@ -18,6 +18,10 @@ You can use `$r` or `$rawfile` to create a **Resource** object, but its attribut
**filename**: name of the file in the **resources/rawfile** directory of the project.
> **NOTE**
>
> When referencing resources of the **Resource** type, make sure the data type is the same as that of the attribute method. For example, if an attribute method supports the **string | Resource** types, the data type of the **Resource** type must be string.
## Length
The **Length** type is used to represent a size unit.
......@@ -212,4 +216,4 @@ The **CustomBuilder** type is used to define custom UI descriptions in component
| Name | Type | Description |
| ------------- | ---------------------- | ---------------------------------------- |
| CustomBuilder | ()&nbsp;=&gt;&nbsp;any | Must be decorated by **@Builder**. For details, see [@Builder](../../quick-start/arkts-dynamic-ui-elememt-building.md#builder).|
| CustomBuilder | () =&gt; any | Must be decorated by **@Builder**. For details, see [@Builder](../../quick-start/arkts-dynamic-ui-elememt-building.md#builder).|
......@@ -85,7 +85,7 @@ struct Index {
build() {
Row() {
Column() {
Text('This is gradient color.').textAlign(TextAlign.Center)
Text('This is gradient color.').textAlign(TextAlign.Center).width(68)
.borderImage({
source: {
angle: 90,
......
......@@ -17,7 +17,7 @@ The size attributes set the width, height, and margin of a component.
| size | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} | Size of the component. |
| padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | Padding of the component.<br>When the parameter is of the **Length** type, the four paddings take effect.<br>Default value: **0**<br>When **padding** is set to a percentage, the width of the parent container is used as the basic value.|
| margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | Margin of the component.<br>When the parameter is of the **Length** type, the four margins take effect.<br>Default value: **0**<br>When **margin** is set to a percentage, the width of the parent container is used as the basic value.|
| constraintSize | {<br>minWidth?: [Length](ts-types.md#length),<br>maxWidth?: [Length](ts-types.md#length),<br>minHeight?: [Length](ts-types.md#length),<br>maxHeight?: [Length](ts-types.md#length)<br>} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**.<br>Default value:<br>{<br>minWidth: 0,<br>maxWidth: Infinity,<br>minHeight: 0,<br>maxHeight: Infinity<br>} |
| constraintSize | {<br>minWidth?: [Length](ts-types.md#length),<br>maxWidth?: [Length](ts-types.md#length),<br>minHeight?: [Length](ts-types.md#length),<br>maxHeight?: [Length](ts-types.md#length)<br>} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**. If the value of **minWidth** is greater than that of **maxWidth**, only the value of **minWidth** takes effect. The same rule applies to **minHeight** and **maxHeight**.<br>Default value:<br>{<br>minWidth: 0,<br>maxWidth: Infinity,<br>minHeight: 0,<br>maxHeight: Infinity<br>} |
| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts.|
......
......@@ -89,6 +89,19 @@ Service configuration allows you to configure services on demand to create diffe
"secon" : "u:r:distributedsche:s0" // SELinux tag setting for service processes. In this example, u:r:distributedsche:s0 is the SELinux tag.
}
```
- SELinux tag
To enable the SELinux policy for a service, add the SELinux tag to the service in the **secon** field. For example, to add the SELinux tag to watchdog_service, use the following code snippet:
```
"services" : [{
"name" : "watchdog_service",
"secon" : "u:r:watchdog_service:s0"
}]
```
Note that you need to define the tag in SELinux. For details, see the appropriate SELinux guide.
- init service FD proxy (for standard system or higher)
FD proxy is an extended mechanism for on-demand startup. It can ensure that the FD state handle is not lost before the service process exits. Specifically, a service process sends the FD to the init process before it exits, and then reclaims the FD from the init process when it is started again.
......@@ -150,7 +163,7 @@ By parsing the <strong>*.cfg</strong> file, you can obtain **service** fields, a
| API | Function| Description |
| ---------- | ---------- |--------|
| int *ServiceGetFd(const char *serviceName, size_t *outfdCount) | Obtains the proxy FD from the init process.| Return value: Returns the pointer to the fd array if the operation is successful; returns **NULL** otherwise. (Note: Manual release is required.)<br>Arguments:<br> **serviceName**: service name.<br>**outfdCount**: length of the returned FD array.|
| int ServiceSaveFd(const char *serviceName, int *fds, int fdCount) | Requests the init process for FD proxy.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br> **serviceName**: service name.<br> **fds**: pointer to the FD array for FD proxy.<br>**fdCount**: length of the FD array
| int ServiceSaveFd(const char *serviceName, int *fds, int fdCount) | Requests the init process for FD proxy.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br> **serviceName**: service name.<br> **fds**: pointer to the FD array for FD proxy.<br>**fdCount**: length of the FD array.
| int ServiceSaveFdWithPoll(const char *serviceName, int *fds, int fdCount) | Requests FD proxy in poll mode.| Return value: Returns **0** if the operation is successful; returns **-1** otherwise.<br> Arguments:<br> **serviceName**: service name.<br> **fds**: pointer to the FD array.<br> **fdCount**: length of the FD array.
**Table 4** Service control APIs
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册