提交 f8e684f9 编写于 作者: A Annie_wang

Merge branch 'master' of gitee.com:Annie_wang/docs_2

...@@ -16,3 +16,4 @@ ...@@ -16,3 +16,4 @@
OpenHarmony_Icons.zip filter=lfs diff=lfs merge=lfs -text OpenHarmony_Icons.zip filter=lfs diff=lfs merge=lfs -text
zip filter=lfs diff=lfs merge=lfs -text zip filter=lfs diff=lfs merge=lfs -text
figures/OpenHarmony_Icons.zip filter=lfs diff=lfs merge=lfs -text figures/OpenHarmony_Icons.zip filter=lfs diff=lfs merge=lfs -text
figures/OpenHarmony应用图标模版.zip filter=lfs diff=lfs merge=lfs -text
...@@ -53,6 +53,8 @@ Widget-related configuration includes **FormExtensionAbility** configuration and ...@@ -53,6 +53,8 @@ Widget-related configuration includes **FormExtensionAbility** configuration and
| formConfigAbility | Link to a specific page of the application. The value is a URI.| String| Yes (initial value: left empty)| | formConfigAbility | Link to a specific page of the application. The value is a URI.| String| Yes (initial value: left empty)|
| formVisibleNotify | Whether the widget is allowed to use the widget visibility notification.| String| Yes (initial value: left empty)| | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification.| String| Yes (initial value: left empty)|
| metadata | Metadata of the widget. This field contains the array of the **customizeData** field.| Object| Yes (initial value: left empty)| | metadata | Metadata of the widget. This field contains the array of the **customizeData** field.| Object| Yes (initial value: left empty)|
| dataProxyEnabled | Whether the widget supports the [update-through-proxy](./arkts-ui-widget-update-by-proxy.md) feature.<br>- **true**: The widget supports the update-through-proxy feature.<br>- **false**: The widget does not support the update-through-proxy feature.<br>If this tag is set to **true**, the settings for the scheduled update time will still take effect, but the settings for the update interval and next update time will not.| Boolean| Yes (initial value: **false**)|
| isDynamic | Whether the widget is a dynamic widget. This tag only applies to ArkTS widgets.<br>- **true**: The widget is a dynamic widget.<br>- **false**: The widget is a static widget. In this case, the widget is displayed as a static image after being added.| Boolean| Yes (initial value: **true**)|
Example configuration: Example configuration:
......
# Applying Custom Drawing in the Widget # Applying Custom Drawing in the Widget
You can apply custom drawing in your ArkTS widget to create a more vibrant experience. Use the [Canvas](../reference/arkui-ts/ts-components-canvas-canvas.md) component to create a canvas on the widget, and then use the [CanvasRenderingContext2D](../reference/arkui-ts/ts-canvasrenderingcontext2d.md) object to draw custom graphics on the canvas. The following code snippet draws a smiling face in the center of a canvas. You can apply custom drawing in your ArkTS widget to create a more vibrant experience. Use the [\<Canvas>](../reference/arkui-ts/ts-components-canvas-canvas.md) component to create a canvas on the widget, and then use the [CanvasRenderingContext2D](../reference/arkui-ts/ts-canvasrenderingcontext2d.md) object to draw custom graphics on the canvas. The following code snippet draws a smiling face in the center of a canvas.
```ts ```ts
@Entry @Entry
@Component @Component
struct Card { struct WidgetCard {
private canvasWidth: number = 0; private canvasWidth: number = 0;
private canvasHeight: number = 0; private canvasHeight: number = 0;
// Initialize CanvasRenderingContext2D and RenderingContextSettings. // Initialize CanvasRenderingContext2D and RenderingContextSettings.
...@@ -26,9 +26,9 @@ struct Card { ...@@ -26,9 +26,9 @@ struct Card {
this.canvasWidth = this.context.width; this.canvasWidth = this.context.width;
this.canvasHeight = this.context.height; this.canvasHeight = this.context.height;
// Draw the background of the canvas. // Draw the background of the canvas.
this.context.fillStyle = 'rgba(203, 154, 126, 1.00)'; this.context.fillStyle = '#EEF0FF';
this.context.fillRect(0, 0, this.canvasWidth, this.canvasHeight); this.context.fillRect(0, 0, this.canvasWidth, this.canvasHeight);
// Draw a red circle in the center of the canvas. // Draw a circle in the center of the canvas.
this.context.beginPath(); this.context.beginPath();
let radius = this.context.width / 3; let radius = this.context.width / 3;
let circleX = this.context.width / 2; let circleX = this.context.width / 2;
...@@ -36,35 +36,48 @@ struct Card { ...@@ -36,35 +36,48 @@ struct Card {
this.context.moveTo(circleX - radius, circleY); this.context.moveTo(circleX - radius, circleY);
this.context.arc(circleX, circleY, radius, 2 * Math.PI, 0, true); this.context.arc(circleX, circleY, radius, 2 * Math.PI, 0, true);
this.context.closePath(); this.context.closePath();
this.context.fillStyle = 'red'; this.context.fillStyle = '#5A5FFF';
this.context.fill(); this.context.fill();
// Draw the left eye of the smiling face. // Draw the left eye of the smiling face.
let leftR = radius / 4; let leftR = radius / 13;
let leftX = circleX - (radius / 2); let leftX = circleX - (radius / 2.3);
let leftY = circleY - (radius / 3.5); let leftY = circleY - (radius / 4.5);
this.context.beginPath(); this.context.beginPath();
this.context.arc(leftX, leftY, leftR, 0, Math.PI, true); this.context.arc(leftX, leftY, leftR, 0, 2 * Math.PI, true);
this.context.strokeStyle = '#ffff00'; this.context.strokeStyle = '#FFFFFF';
this.context.lineWidth = 10; this.context.lineWidth = 15;
this.context.stroke(); this.context.stroke();
// Draw the right eye of the smiling face. // Draw the right eye of the smiling face.
let rightR = radius / 4; let rightR = radius / 13;
let rightX = circleX + (radius / 2); let rightX = circleX + (radius / 2.3);
let rightY = circleY - (radius / 3.5); let rightY = circleY - (radius / 4.5);
this.context.beginPath(); this.context.beginPath();
this.context.arc(rightX, rightY, rightR, 0, Math.PI, true); this.context.arc(rightX, rightY, rightR, 0, 2 * Math.PI, true);
this.context.strokeStyle = '#ffff00'; this.context.strokeStyle = '#FFFFFF';
this.context.lineWidth = 10; this.context.lineWidth = 15;
this.context.stroke();
// Draw the nose of the smiling face.
let startX = circleX;
let startY = circleY - 20;
this.context.beginPath();
this.context.moveTo(startX, startY);
this.context.lineTo(startX - 8, startY + 40);
this.context.lineTo(startX + 8, startY + 40);
this.context.strokeStyle = '#FFFFFF';
this.context.lineWidth = 15;
this.context.lineCap = 'round'
this.context.lineJoin = 'round'
this.context.stroke(); this.context.stroke();
// Draw the mouth of the smiling face. // Draw the mouth of the smiling face.
let mouthR = radius / 2.5; let mouthR = radius / 2;
let mouthX = circleX; let mouthX = circleX;
let mouthY = circleY + (radius / 3); let mouthY = circleY + 10;
this.context.beginPath(); this.context.beginPath();
this.context.arc(mouthX, mouthY, mouthR, Math.PI, 0, true); this.context.arc(mouthX, mouthY, mouthR, Math.PI / 1.4, Math.PI / 3.4, true);
this.context.strokeStyle = '#ffff00'; this.context.strokeStyle = '#FFFFFF';
this.context.lineWidth = 10; this.context.lineWidth = 15;
this.context.stroke(); this.context.stroke();
this.context.closePath();
}) })
} }
}.height('100%').width('100%') }.height('100%').width('100%')
...@@ -74,4 +87,4 @@ struct Card { ...@@ -74,4 +87,4 @@ struct Card {
The figure below shows the effect. The figure below shows the effect.
![WidgetCanvasDemo](figures/WidgetCanvasDemo.png) ![WidgetCanvasDemo](figures/WidgetCanvasDemo.jpeg)
\ No newline at end of file \ No newline at end of file
...@@ -22,7 +22,7 @@ Processing flow of the widget provider (indicated by the blue arrows in the figu ...@@ -22,7 +22,7 @@ Processing flow of the widget provider (indicated by the blue arrows in the figu
2. In the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) callback, the widget provider returns the **key** + **subscriberId** combination defined by the data provider to the Widget Manager. 2. In the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) callback, the widget provider returns the **key** + **subscriberId** combination defined by the data provider to the Widget Manager.
3. Widget Manager parses the subscription information of the widget provider and registers a subscription instance with the data management service. 3. The Widget Manager parses the subscription information of the widget provider and registers a subscription instance with the data management service.
Processing flow of the widget update proxy (indicated by the red arrows in the figure): Processing flow of the widget update proxy (indicated by the red arrows in the figure):
...@@ -67,7 +67,7 @@ The update-through-proxy configuration varies by the type of shared data. ...@@ -67,7 +67,7 @@ The update-through-proxy configuration varies by the type of shared data.
} }
``` ```
- Configure the subscription information [proxies](../reference/apis/js-apis-app-form-formBindingData.md#proxydata) in the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) callback and return the information to the Widget Manager through [formBinding](../reference/apis/js-apis-app-form-formBindingData.md#formbindingdata). In this example, **key** is set to **detail** and **subscriberId** is set to **11**. - Configure the subscription information [proxyData](../reference/apis/js-apis-app-form-formBindingData.md#proxydata10) in the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) callback and return the information to the Widget Manager through [formBinding](../reference/apis/js-apis-app-form-formBindingData.md#formbindingdata). In this example, **key** is set to **detail** and **subscriberId** is set to **11**.
> **NOTE** > **NOTE**
> >
> The value of **key** can be a URI or a simple string. The default value of **subscriberId** is the value of **formId**. The actual value depends on the definition of the data provider. > The value of **key** can be a URI or a simple string. The default value of **subscriberId** is the value of **formId**. The actual value depends on the definition of the data provider.
...@@ -89,7 +89,7 @@ The update-through-proxy configuration varies by the type of shared data. ...@@ -89,7 +89,7 @@ The update-through-proxy configuration varies by the type of shared data.
} }
``` ```
- In the widget page code file **widgets.abc**, use the variable in LocalStorage to obtain the subscribed data. In this example, the subscribed data is obtained through **'detail'** and displayed in the **\<Text>** component. - In the widget page code file **widgets.abc**, use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In this example, the subscribed data is obtained through **'detail'** and displayed in the **\<Text>** component.
```ts ```ts
let storage = new LocalStorage(); let storage = new LocalStorage();
@Entry(storage) @Entry(storage)
...@@ -139,7 +139,7 @@ The update-through-proxy configuration varies by the type of shared data. ...@@ -139,7 +139,7 @@ The update-through-proxy configuration varies by the type of shared data.
} }
``` ```
- Add a subscription template ([addTemplate]([../reference/apis/js-apis-data-dataShare.md#addtemplate10)) to the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) callback and use the template predicates to notify the database of the subscribed data conditions. Then, configure the subscription information [proxies](../reference/apis/js-apis-app-form-formBindingData.md#proxydata) and return it to the Widget Manager through [formBinding](../reference/apis/js-apis-app-form-formBindingData.md#formbindingdata). In the example, the predicate is set to **"list": "select type from TBL00 limit 0,1"**, indicating that the first data record in the **type** column is obtained from the **TBL00** database. The data is returned to the widget page code file **widgets.abc** in {"list":[{"type":"value0"}]} format. - Add a subscription template ([addTemplate](../reference/apis/js-apis-data-dataShare.md#addtemplate10)) to the [onAddForm](../reference/apis/js-apis-app-form-formExtensionAbility.md#onaddform) callback and use the template predicates to notify the database of the subscribed data conditions. Then, configure the subscription information [proxyData](../reference/apis/js-apis-app-form-formBindingData.md#proxydata10) and return it to the Widget Manager through [formBinding](../reference/apis/js-apis-app-form-formBindingData.md#formbindingdata). In the example, the predicate is set to **"list": "select type from TBL00 limit 0,1"**, indicating that the first data record in the **type** column is obtained from the **TBL00** database. The data is returned to the widget page code file **widgets.abc** in {"list":[{"type":"value0"}]} format.
> **NOTE** > **NOTE**
> >
...@@ -178,7 +178,7 @@ The update-through-proxy configuration varies by the type of shared data. ...@@ -178,7 +178,7 @@ The update-through-proxy configuration varies by the type of shared data.
} }
``` ```
- In the widget page code file **widgets.abc**, use the variable in LocalStorage to obtain the subscribed data. In the example, the subscribed data is obtained through **'list'**, and the value of the first element is displayed on the **\<Text>** component. - In the widget page code file (generally the .ets file in the **pages** folder under the widget directory of the project), use the variable in LocalStorage to obtain the subscribed data. The variable in LocalStorage is bound to a string and updates the subscribed data in the key:value pair format. The key must be the same as that subscribed to by the widget provider. In the example, the subscribed data is obtained through **'list'**, and the value of the first element is displayed on the **\<Text>** component.
```ts ```ts
let storage = new LocalStorage(); let storage = new LocalStorage();
@Entry(storage) @Entry(storage)
...@@ -216,4 +216,3 @@ The update-through-proxy configuration varies by the type of shared data. ...@@ -216,4 +216,3 @@ The update-through-proxy configuration varies by the type of shared data.
## Data Provider Development ## Data Provider Development
For details, see [Data Management](../database/data-mgmt-overview.md). For details, see [Data Management](../database/data-mgmt-overview.md).
<!--no_check-->
\ No newline at end of file
...@@ -95,3 +95,4 @@ When periodic update is triggered, the system calls the [onUpdateForm()](../refe ...@@ -95,3 +95,4 @@ When periodic update is triggered, the system calls the [onUpdateForm()](../refe
> - Each widget can be updated at the specified interval for a maximum of 50 times every day, including updates triggered by setting [updateDuration](arkts-ui-widget-configuration.md) or calling [setFormNextRefreshTime()](../reference/apis/js-apis-app-form-formProvider.md#setformnextrefreshtime). When the limit is reached, the widget cannot be updated in this mode again. The number of update times is reset at 00:00 every day. > - Each widget can be updated at the specified interval for a maximum of 50 times every day, including updates triggered by setting [updateDuration](arkts-ui-widget-configuration.md) or calling [setFormNextRefreshTime()](../reference/apis/js-apis-app-form-formProvider.md#setformnextrefreshtime). When the limit is reached, the widget cannot be updated in this mode again. The number of update times is reset at 00:00 every day.
>- A single timer is used for timing updates at the specified interval. Therefore, if a widget is configured to update at scheduled intervals, the first scheduled update may have a maximum deviation of 30 minutes. For example, if widget A (updated every half an hour) is added at 03:20 and widget B (also updated every half an hour) is added at 03:40, the first update of widget B has a deviation of 10 minutes to the expected time: The timer starts at 03:20 when widget A is added, triggers an update for widget A at 03:50, and triggers another update for widget B at 04:20 (instead of 04:10 as expected). >- A single timer is used for timing updates at the specified interval. Therefore, if a widget is configured to update at scheduled intervals, the first scheduled update may have a maximum deviation of 30 minutes. For example, if widget A (updated every half an hour) is added at 03:20 and widget B (also updated every half an hour) is added at 03:40, the first update of widget B has a deviation of 10 minutes to the expected time: The timer starts at 03:20 when widget A is added, triggers an update for widget A at 03:50, and triggers another update for widget B at 04:20 (instead of 04:10 as expected).
> - Updates at the specified interval and updates at the scheduled time are triggered only when the screen is on. The update action is merely recorded when the screen is off and is performed once the screen is on. > - Updates at the specified interval and updates at the scheduled time are triggered only when the screen is on. The update action is merely recorded when the screen is off and is performed once the screen is on.
>- If the [update-through-proxy](./arkts-ui-widget-update-by-proxy.md) feature is enabled, the settings for the update interval and next update time will not take effect.
# DriverExtensionAbility
[DriverExtensionAbility](../reference/apis/js-apis-app-ability-driverExtensionAbility.md) is an ExtensionAbility of the driver type that provides driver-related extension framework. If the capabilities of a device can be expanded by inserting an external hardware module, you can install the driver of the hardware module through an application. DriverExtensionAbility can be used to develop such applications.
The [DriverExtensionAbility](../reference/apis/js-apis-app-ability-driverExtensionAbility.md) can be bound to an application through the DriverExtensionManager and process related transactions in the background based on the application request information.
Each type of ExtensionAbility has its own context. The DriverExtensionAbility provides related capabilities through the [DriverExtensionContext](../reference/apis/js-apis-inner-application-driverExtensionContext.md).
This topic describes how to use DriverExtensionAbility in the following scenarios:
- [DriverExtensionAbility](#driverextensionability)
- [How to Develop](#how-to-develop)
## How to Develop
To implement a driver, create a DriverExtensionAbility in the DevEco Studio project. The procedure is as follows:
1. In the **ets** directory of a module in the project, right-click and choose **New > Directory** to create a directory named **driverextability**.
2. In the **driverextability** directory, right-click and choose **New > TypeScript File** to create a file named **DriverExtAbility.ts**.
3. Open the **DriverExtAbility.ts** file, import the [RPC module](../reference/apis/js-apis-rpc.md), and overload the **onRemoteMessageRequest()** method to receive messages from the application and return the processing result to the application. **REQUEST_VALUE** is used to verify the service request code sent by the application.
```ts
import rpc from '@ohos.rpc';
const REQUEST_CODE = 99;
class StubTest extends rpc.RemoteObject {
constructor(des) {
super(des);
}
// Receive the message sent from the application and return the processing result to the application.
onRemoteMessageRequest(code, data, reply, option) {
if (code === REQUEST_CODE) {
// Receive the data sent from the application.
// When the application calls data.writeInt() multiple times to write data, the driver can receive the corresponding data by calling data.readInt() for multiple times.
let optFir = data.readInt();
let optSec = data.readInt();
// The driver returns the data processing result to the application.
// In the example, two pieces of data are received, and the sum of the two pieces of data is returned to the application.
reply.writeInt(optFir + optSec);
}
return true;
}
}
```
4. In the **DriverExtAbility.ts** file, import the dependency package [DriverExtensionAbility](../reference/apis/js-apis-app-ability-driverExtensionAbility.md), which provides the **onInit()**, **onRelease()**, **onConnect()**, and **onDisconnect()** lifecycle callbacks. Then, customize a class to inherit from [DriverExtensionAbility](../reference/apis/js-apis-app-ability-driverExtensionAbility.md) and override the lifecycle callbacks as required.
```ts
import DriverExtensionAbility from '@ohos.app.ability.DriverExtensionAbility';
import rpc from '@ohos.rpc';
const TAG: string = '[Example].[Entry].[DriverExtAbility]';
const REQUEST_CODE = 99;
class StubTest extends rpc.RemoteObject {
// ...
}
export default class DriverExtAbility extends DriverExtensionAbility {
onInit(want) {
console.info(TAG, `onInit, want: ${want.abilityName}`);
}
onRelease() {
console.info(TAG, `onRelease, want: ${want.abilityName}`);
}
onConnect(want) {
console.info(TAG, `onConnect, want: ${want.abilityName}`);
return new StubTest("test");
}
onDisconnect(want) {
console.info(TAG, `onDisconnect, want: ${want.abilityName}`);
}
onDump() {
console.info(TAG, `onDump, params:` + JSON.stringify(params));
return ['params'];
}
}
```
5. Register the DriverExtensionAbility in the [**module.json5** file](../quick-start/module-configuration-file.md) of the module in the project. Set **type** to **service** and **srcEntry** to the code path of the DriverExtensionAbility component.
```json
{
"module": {
// ...
"extensionAbilities": [
{
"name": "DriverExtAbility",
"icon": "$media:icon",
"description": "driver",
"type": "driver",
"exported": true,
"srcEntry": "./ets/driverextability/DriverExtAbility.ts",
"metadata": [
{
"name": "bus", // The bus is mandatory.
"value": "USB",
},
{
"name": "desc", // Description of the driver, which is mandatory.
"value": "the sample of driverExtensionAbility",
},
{
"name": "vendor", // Driver vendor name, which is mandatory.
"value": "string",
},
{
"name": "vid", // List of supported USB vendor IDs, separated by commas (,). The value cannot be empty.
"value": "string, string",
},
{
"name": "pid", // List of supported USB product IDs, separated by commas (,). The value cannot be empty.
"value": "string, string",
}
]
}
]
}
}
```
...@@ -35,7 +35,7 @@ As shown above, the **app.json5** file contains several tags. ...@@ -35,7 +35,7 @@ As shown above, the **app.json5** file contains several tags.
| Name| Description| Data Type| Initial Value Allowed| | Name| Description| Data Type| Initial Value Allowed|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| bundleName | Bundle name, which uniquely identifies an application. The value must comply with the following rules:<br>- Consists of letters, digits, underscores (_), and periods (.).<br>- Starts with a letter.<br>- Contains 7 to 127 bytes.<br>You are advised to use the reverse domain name notation, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.<br>If an application is built with the system source code, you are advised to name it in *com.ohos.demo* notation, where **ohos** signifies that the application is an OpenHarmony system application.| String| No| | bundleName | Bundle name, which uniquely identifies an application. The value must comply with the following rules:<br>- Consists of letters, digits, underscores (_), and periods (.).<br>- Starts with a letter.<br>- Contains 7 to 127 bytes.<br>You are advised to use the reverse domain name notation, for example, *com.example.demo*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.<br>If an application is built with the system source code, you are advised to name it in *com.ohos.demo* notation, where **ohos** signifies that the application is an OpenHarmony system application.| String| No|
| bundleType| Bundle type, which is used to distinguish applications and atomic services. <br>- **app**: The bundle is a common application.<br>- **atomicService**: The bundle is an atomic service.<br>- **shared**: The bundle is a shared object application.| String| Yes (initial value: **"app"**)| | bundleType| Bundle type, which is used to distinguish applications and atomic services.<br>- **app**: The bundle is a common application.<br>- **atomicService**: The bundle is an atomic service.<br>- **shared**: The bundle is a shared object application.| String| Yes (initial value: **"app"**)|
| debug | Whether the application can be debugged. This tag is generated during compilation and building in DevEco Studio.<br>- **true**: The application can be debugged.<br>- **false**: The application cannot be debugged.| Boolean| Yes (initial value: **false**)| | debug | Whether the application can be debugged. This tag is generated during compilation and building in DevEco Studio.<br>- **true**: The application can be debugged.<br>- **false**: The application cannot be debugged.| Boolean| Yes (initial value: **false**)|
| icon | [Icon of the application](../application-models/application-component-configuration-stage.md). The value is an icon resource index.| String| No| | icon | [Icon of the application](../application-models/application-component-configuration-stage.md). The value is an icon resource index.| String| No|
| label | [Name of the application](../application-models/application-component-configuration-stage.md). The value is a string resource index.| String| No| | label | [Name of the application](../application-models/application-component-configuration-stage.md). The value is a string resource index.| String| No|
......
...@@ -12,7 +12,7 @@ This topic describes only the AppStorage application scenarios and related decor ...@@ -12,7 +12,7 @@ This topic describes only the AppStorage application scenarios and related decor
## Overview ## Overview
AppStorage is a singleton LocalStorage object that is created by the UI framework at application startup. Its purpose is to provide the central storage for mutable application UI state attributes. AppStorage retains all those attributes and their values as long as the application remains running. Attributes are accessed using a unique key string value. AppStorage is a singleton object that is created at application startup. Its purpose is to provide the central storage for mutable application UI state attributes. AppStorage retains all those attributes and their values as long as the application remains running. Attributes are accessed using a unique key string value.
UI components synchronize application state attributes with the AppStorage. Implementation of application business logic can access AppStorage as well. UI components synchronize application state attributes with the AppStorage. Implementation of application business logic can access AppStorage as well.
...@@ -21,7 +21,7 @@ Selected state attributes of AppStorage can be synced with different data source ...@@ -21,7 +21,7 @@ Selected state attributes of AppStorage can be synced with different data source
## \@StorageProp ## \@StorageProp
As mentioned above, if you want to establish a binding between AppStorage and a custom component, you need to use the \@StorageProp and \@StorageLink decorators. Use \@StorageProp(key) or \@StorageLink(key) to decorate variables in the component. **key** identifies the attribute in AppStorage. As mentioned above, if you want to establish a binding between AppStorage and a custom component, you'll need the \@StorageProp and \@StorageLink decorators. Use \@StorageProp(key) or \@StorageLink(key) to decorate variables in the component, where **key** identifies the attribute in AppStorage.
When a custom component is initialized, the \@StorageProp(key)/\@StorageLink(key) decorated variable is initialized with the value of the attribute with the given key in AppStorage. Local initialization is mandatory. If an attribute with the given key is missing from AppStorage, it will be added with the stated initializing value. (Whether the attribute with the given key exists in AppStorage depends on the application logic.) When a custom component is initialized, the \@StorageProp(key)/\@StorageLink(key) decorated variable is initialized with the value of the attribute with the given key in AppStorage. Local initialization is mandatory. If an attribute with the given key is missing from AppStorage, it will be added with the stated initializing value. (Whether the attribute with the given key exists in AppStorage depends on the application logic.)
...@@ -34,7 +34,7 @@ By decorating a variable with \@StorageProp(key), a one-way data synchronization ...@@ -34,7 +34,7 @@ By decorating a variable with \@StorageProp(key), a one-way data synchronization
| \@StorageProp Decorator| Description | | \@StorageProp Decorator| Description |
| ------------------ | ---------------------------------------- | | ------------------ | ---------------------------------------- |
| Decorator parameters | **key**: constant string, mandatory (note, the string is quoted) | | Decorator parameters | **key**: constant string, mandatory (note, the string is quoted) |
| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).<br>The type must be specified and must be the same as the corresponding attribute in LocalStorage. **any** is not supported. The **undefined** and **null** values are not allowed.| | Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).<br>The type must be specified. Whenever possible, use the same type as that of the corresponding attribute in AppStorage. Otherwise, implicit type conversion occurs, causing application behavior exceptions. **any** is not supported. The **undefined** and **null** values are not allowed.|
| Synchronization type | One-way: from the attribute in AppStorage to the component variable.<br>The component variable can be changed locally, but an update from AppStorage will overwrite local changes.| | Synchronization type | One-way: from the attribute in AppStorage to the component variable.<br>The component variable can be changed locally, but an update from AppStorage will overwrite local changes.|
| Initial value for the decorated variable | Mandatory. It is used as the default value for initialization if the attribute does not exist in AppStorage.| | Initial value for the decorated variable | Mandatory. It is used as the default value for initialization if the attribute does not exist in AppStorage.|
...@@ -44,7 +44,7 @@ By decorating a variable with \@StorageProp(key), a one-way data synchronization ...@@ -44,7 +44,7 @@ By decorating a variable with \@StorageProp(key), a one-way data synchronization
| Transfer/Access | Description | | Transfer/Access | Description |
| ---------- | ---------------------------------------- | | ---------- | ---------------------------------------- |
| Initialization and update from the parent component| Forbidden.| | Initialization and update from the parent component| Forbidden.|
| Subnode initialization | Supported; can be used to initialize a n \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.| | Subnode initialization | Supported; can be used to initialize an \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.|
| Access | None. | | Access | None. |
...@@ -92,7 +92,7 @@ By decorating a variable with \@StorageProp(key), a one-way data synchronization ...@@ -92,7 +92,7 @@ By decorating a variable with \@StorageProp(key), a one-way data synchronization
| \@StorageLink Decorator| Description | | \@StorageLink Decorator| Description |
| ------------------ | ---------------------------------------- | | ------------------ | ---------------------------------------- |
| Decorator parameters | **key**: constant string, mandatory (note, the string is quoted) | | Decorator parameters | **key**: constant string, mandatory (note, the string is quoted) |
| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).<br>The type must be specified and must be the same as the corresponding attribute in AppStorage. **any** is not supported. The **undefined** and **null** values are not allowed.| | Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).<br>The type must be specified. Whenever possible, use the same type as that of the corresponding attribute in AppStorage. Otherwise, implicit type conversion occurs, causing application behavior exceptions. **any** is not supported. The **undefined** and **null** values are not allowed.|
| Synchronization type | Two-way: from the attribute in AppStorage to the custom component variable and back| | Synchronization type | Two-way: from the attribute in AppStorage to the custom component variable and back|
| Initial value for the decorated variable | Mandatory. It is used as the default value for initialization if the attribute does not exist in AppStorage.| | Initial value for the decorated variable | Mandatory. It is used as the default value for initialization if the attribute does not exist in AppStorage.|
...@@ -193,6 +193,181 @@ struct CompA { ...@@ -193,6 +193,181 @@ struct CompA {
} }
``` ```
### Persistent Subscription and Callback
The persistent subscription and callback can help reduce overhead and enhance code readability.
```ts
// xxx.ets
import emitter from '@ohos.events.emitter';
let NextID: number = 0;
class ViewData {
title: string;
uri: Resource;
color: Color = Color.Black;
id: number;
constructor(title: string, uri: Resource) {
this.title = title;
this.uri = uri
this.id = NextID++;
}
}
@Entry
@Component
struct Gallery2 {
dataList: Array<ViewData> = [new ViewData('flower', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon'))]
scroller: Scroller = new Scroller()
private preIndex: number = -1
build() {
Column() {
Grid(this.scroller) {
ForEach(this.dataList, (item: ViewData) => {
GridItem() {
TapImage({
uri: item.uri,
index: item.id
})
}.aspectRatio(1)
.onClick(() => {
if (this.preIndex === item.id) {
return
}
var innerEvent = { eventId: item.id }
// Selected: from black to red
var eventData = {
data: {
"colorTag": 1
}
}
emitter.emit(innerEvent, eventData)
if (this.preIndex != -1) {
console.info(`preIndex: ${this.preIndex}, index: ${item.id}, black`)
var innerEvent = { eventId: this.preIndex }
// Deselected: from red to black
var eventData = {
data: {
"colorTag": 0
}
}
emitter.emit(innerEvent, eventData)
}
this.preIndex = item.id
})
}, (item: ViewData) => JSON.stringify(item))
}.columnsTemplate('1fr 1fr')
}
}
}
@Component
export struct TapImage {
@State tapColor: Color = Color.Black;
private index: number;
private uri: Resource;
onTapIndexChange(colorTag: emitter.EventData) {
this.tapColor = colorTag.data.colorTag ? Color.Red : Color.Black
}
aboutToAppear() {
// Define the event ID.
var innerEvent = { eventId: this.index }
emitter.on(innerEvent, this.onTapIndexChange.bind(this))
}
build() {
Column() {
Image(this.uri)
.objectFit(ImageFit.Cover)
.border({ width: 5, style: BorderStyle.Dotted, color: this.tapColor })
}
}
}
```
The following example uses the message mechanism to subscribe to events. Because this mechanism can result in a large number of nodes to listen for and a long implementation time, it is not recommended.
```ts
// xxx.ets
class ViewData {
title: string;
uri: Resource;
color: Color = Color.Black;
constructor(title: string, uri: Resource) {
this.title = title;
this.uri = uri
}
}
@Entry
@Component
struct Gallery2 {
dataList: Array<ViewData> = [new ViewData('flower', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon'))]
scroller: Scroller = new Scroller()
build() {
Column() {
Grid(this.scroller) {
ForEach(this.dataList, (item: ViewData, index?: number) => {
GridItem() {
TapImage({
uri: item.uri,
index: index
})
}.aspectRatio(1)
}, (item: ViewData, index?: number) => {
return JSON.stringify(item) + index;
})
}.columnsTemplate('1fr 1fr')
}
}
}
@Component
export struct TapImage {
@StorageLink('tapIndex') @Watch('onTapIndexChange') tapIndex: number = -1;
@State tapColor: Color = Color.Black;
private index: number;
private uri: Resource;
// Check whether the component is selected.
onTapIndexChange() {
if (this.tapIndex >= 0 && this.index === this.tapIndex) {
console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, red`)
this.tapColor = Color.Red;
} else {
console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, black`)
this.tapColor = Color.Black;
}
}
build() {
Column() {
Image(this.uri)
.objectFit(ImageFit.Cover)
.onClick(() => {
this.tapIndex = this.index;
})
.border({ width: 5, style: BorderStyle.Dotted, color: this.tapColor })
}
}
}
```
## Restrictions ## Restrictions
...@@ -201,4 +376,6 @@ When using AppStorage together with [PersistentStorage](arkts-persiststorage.md) ...@@ -201,4 +376,6 @@ When using AppStorage together with [PersistentStorage](arkts-persiststorage.md)
- A call to **PersistentStorage.PersistProp()** after creating the attribute in AppStorage uses the type and value in AppStorage and overwrites any attribute with the same name in PersistentStorage. In light of this, the opposite order of calls is recommended. For an example of incorrect usage, see [Accessing Attribute in AppStorage Before PersistentStorage](arkts-persiststorage.md#accessing-attribute-in-appstorage-before-persistentstorage). - A call to **PersistentStorage.PersistProp()** after creating the attribute in AppStorage uses the type and value in AppStorage and overwrites any attribute with the same name in PersistentStorage. In light of this, the opposite order of calls is recommended. For an example of incorrect usage, see [Accessing Attribute in AppStorage Before PersistentStorage](arkts-persiststorage.md#accessing-attribute-in-appstorage-before-persistentstorage).
- A call to **Environment.EnvProp()** after creating the attribute in AppStorage will fail. This is because AppStorage already has an attribute with the same name, and the environment variable will not be written into AppStorage. Therefore, you are advised not to use the preset environment variable name in AppStorage. - A call to **Environment.EnvProp()** after creating the attribute in AppStorage will fail. This is because AppStorage already has an attribute with the same name, and the environment variable will not be written into AppStorage. Therefore, you are advised not to use the preset environment variable name in AppStorage.
- Changes to the variables decorated by state decorators will cause UI re-render. If the changes are for message communication, rather than for UI re-render, the emitter mode is recommended. For the example, see [Persistent Subscription and Callback](#persistent-subscription-and-callback).
<!--no_check--> <!--no_check-->
...@@ -20,7 +20,7 @@ An \@Link decorated variable in a child component shares the same value with a v ...@@ -20,7 +20,7 @@ An \@Link decorated variable in a child component shares the same value with a v
| ----------- | ---------------------------------------- | | ----------- | ---------------------------------------- |
| Decorator parameters | None. | | Decorator parameters | None. |
| Synchronization type | Two-way:<br>from an \@State, \@StorageLink, or \@Link decorated variable in the parent component to this variable; and the other way around.| | Synchronization type | Two-way:<br>from an \@State, \@StorageLink, or \@Link decorated variable in the parent component to this variable; and the other way around.|
| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested types, see [Observed Changes](#observed-changes).<br>The type must be specified and must be the same as that of the counterpart variable of the parent component.<br>**any** is not supported. A combination of simple and complex types is not supported. The **undefined** and **null** values are not allowed.<br>**NOTE**<br>The Length, ResourceStr, and ResourceColor types are a combination of simple and complex types and therefore not supported.| | Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.<br>Date type. For details about the scenarios of supported types, see [Observed Changes](#observed-changes).<br>The type must be specified and must be the same as that of the counterpart variable of the parent component.<br>**any** is not supported. A combination of simple and complex types is not supported. The **undefined** and **null** values are not allowed.<br>**NOTE**<br>The Length, ResourceStr, and ResourceColor types are a combination of simple and complex types and therefore not supported.|
| Initial value for the decorated variable | Forbidden. | | Initial value for the decorated variable | Forbidden. |
...@@ -28,7 +28,7 @@ An \@Link decorated variable in a child component shares the same value with a v ...@@ -28,7 +28,7 @@ An \@Link decorated variable in a child component shares the same value with a v
| Transfer/Access | Description | | Transfer/Access | Description |
| ---------- | ---------------------------------------- | | ---------- | ---------------------------------------- |
| Initialization and update from the parent component| Mandatory. A two-way synchronization relationship can be established with the @State, @StorageLink, or \@Link decorated variable in the parent component. An \@Link decorated variable can be initialized from an \@State, \@Link, \@Prop, \@Provide, \@Consume, \@ObjectLink, \@StorageLink, \@StorageProp, \@LocalStorageLink, or \@LocalStorageProp decorated variable in the parent component.<br>Since API version 9, the syntax is **Comp({&nbsp;aLink:&nbsp;this.aState&nbsp;})** for initializing an \@Link decorated variable in the child component from an @State decorated variable in its parent component. The **Comp({aLink:&nbsp;$aState})** syntax is also supported| | Initialization and update from the parent component| Mandatory. A two-way synchronization relationship can be established with the @State, @StorageLink, or \@Link decorated variable in the parent component. An \@Link decorated variable can be initialized from an \@State, \@Link, \@Prop, \@Provide, \@Consume, \@ObjectLink, \@StorageLink, \@StorageProp, \@LocalStorageLink, or \@LocalStorageProp decorated variable in the parent component.<br>Since API version 9, the syntax is **Comp({ aLink: this.aState })** for initializing an \@Link decorated variable in the child component from an @State decorated variable in its parent component. The **Comp({aLink: $aState})** syntax is also supported.|
| Subnode initialization | Supported; can be used to initialize a regular variable or \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.| | Subnode initialization | Supported; can be used to initialize a regular variable or \@State, \@Link, \@Prop, or \@Provide decorated variable in the child component.|
| Access | Private, accessible only within the component. | | Access | Private, accessible only within the component. |
...@@ -48,6 +48,61 @@ An \@Link decorated variable in a child component shares the same value with a v ...@@ -48,6 +48,61 @@ An \@Link decorated variable in a child component shares the same value with a v
- When the decorated variable is of the array type, the addition, deletion, and updates of array items can be observed. For details, see [Array Type \@Link](#array-type-link). - When the decorated variable is of the array type, the addition, deletion, and updates of array items can be observed. For details, see [Array Type \@Link](#array-type-link).
- When the decorated variable is of the Date type, the overall value assignment of the Date object can be observed, and the following APIs can be called to update Date attributes: **setFullYear**, **setMonth**, **setDate**, **setHours**, **setMinutes**, **setSeconds**, **setMilliseconds**, **setTime**, **setUTCFullYear**, **setUTCMonth**, **setUTCDate**, **setUTCHours**, **setUTCMinutes**, **setUTCSeconds**, and **setUTCMilliseconds**.
```ts
@Component
struct DateComponent {
@Link selectedDate: Date;
build() {
Column() {
Button(`child increase the year by 1`).onClick(() => {
this.selectedDate.setFullYear(this.selectedDate.getFullYear() + 1)
})
Button('child update the new date')
.margin(10)
.onClick(() => {
this.selectedDate = new Date('2023-09-09')
})
DatePicker({
start: new Date('1970-1-1'),
end: new Date('2100-1-1'),
selected: this.selectedDate
})
}
}
}
@Entry
@Component
struct ParentComponent {
@State parentSelectedDate: Date = new Date('2021-08-08');
build() {
Column() {
Button('parent increase the month by 1')
.margin(10)
.onClick(() => {
this.parentSelectedDate.setMonth(this.parentSelectedDate.getMonth() + 1)
})
Button('parent update the new date')
.margin(10)
.onClick(() => {
this.parentSelectedDate = new Date('2023-07-07')
})
DatePicker({
start: new Date('1970-1-1'),
end: new Date('2100-1-1'),
selected: this.parentSelectedDate
})
DateComponent({selectedDate:this.parentSelectedDate})
}
}
}
```
### Framework Behavior ### Framework Behavior
...@@ -184,4 +239,5 @@ struct Parent { ...@@ -184,4 +239,5 @@ struct Parent {
As described above, the ArkUI framework can observe the addition, deletion, and replacement of array items. It should be noted that, in the preceding example, the type of the \@Link and \@State decorated variables is the same: number[]. It is not allowed to define the \@Link decorated variable in the child component as type number (**\@Link item: number**), and create child components for each array item in the \@State decorated array in the parent component. [\@Prop](arkts-prop.md) or \@Observed should be used depending on application semantics. As described above, the ArkUI framework can observe the addition, deletion, and replacement of array items. It should be noted that, in the preceding example, the type of the \@Link and \@State decorated variables is the same: number[]. It is not allowed to define the \@Link decorated variable in the child component as type number (**\@Link item: number**), and create child components for each array item in the \@State decorated array in the parent component. [\@Prop](arkts-prop.md) or \@Observed should be used depending on application semantics.
<!--no_check--> <!--no_check-->
...@@ -60,7 +60,7 @@ By decorating a variable with \@LocalStorageProp(key), a one-way data synchroniz ...@@ -60,7 +60,7 @@ By decorating a variable with \@LocalStorageProp(key), a one-way data synchroniz
| \@LocalStorageProp Decorator| Description | | \@LocalStorageProp Decorator| Description |
| ----------------------- | ---------------------------------------- | | ----------------------- | ---------------------------------------- |
| Decorator parameters | **key**: constant string, mandatory (note, the string is quoted) | | Decorator parameters | **key**: constant string, mandatory (note, the string is quoted) |
| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).<br>The type must be specified and must be the same as the corresponding attribute in LocalStorage. **any** is not supported. The **undefined** and **null** values are not allowed.| | Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).<br>The type must be specified. Whenever possible, use the same type as that of the corresponding attribute in LocalStorage. Otherwise, implicit type conversion occurs, causing application behavior exceptions. **any** is not supported. The **undefined** and **null** values are not allowed.|
| Synchronization type | One-way: from the attribute in LocalStorage to the component variable. The component variable can be changed locally, but an update from LocalStorage will overwrite local changes.| | Synchronization type | One-way: from the attribute in LocalStorage to the component variable. The component variable can be changed locally, but an update from LocalStorage will overwrite local changes.|
| Initial value for the decorated variable | Mandatory. It is used as the default value for initialization if the attribute does not exist in LocalStorage.| | Initial value for the decorated variable | Mandatory. It is used as the default value for initialization if the attribute does not exist in LocalStorage.|
...@@ -118,7 +118,7 @@ By decorating a variable with \@LocalStorageProp(key), a one-way data synchroniz ...@@ -118,7 +118,7 @@ By decorating a variable with \@LocalStorageProp(key), a one-way data synchroniz
| \@LocalStorageLink Decorator| Description | | \@LocalStorageLink Decorator| Description |
| ----------------------- | ---------------------------------------- | | ----------------------- | ---------------------------------------- |
| Decorator parameters | **key**: constant string, mandatory (note, the string is quoted) | | Decorator parameters | **key**: constant string, mandatory (note, the string is quoted) |
| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).<br>The type must be specified and must be the same as the corresponding attribute in LocalStorage. **any** is not supported. The **undefined** and **null** values are not allowed.| | Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested objects, see [Observed Changes and Behavior](#observed-changes-and-behavior).<br>The type must be specified. Whenever possible, use the same type as that of the corresponding attribute in LocalStorage. Otherwise, implicit type conversion occurs, causing application behavior exceptions. **any** is not supported. The **undefined** and **null** values are not allowed.|
| Synchronization type | Two-way: from the attribute in LocalStorage to the custom component variable and back| | Synchronization type | Two-way: from the attribute in LocalStorage to the custom component variable and back|
| Initial value for the decorated variable | Mandatory. It is used as the default value for initialization if the attribute does not exist in LocalStorage.| | Initial value for the decorated variable | Mandatory. It is used as the default value for initialization if the attribute does not exist in LocalStorage.|
...@@ -292,7 +292,7 @@ struct CompA { ...@@ -292,7 +292,7 @@ struct CompA {
.onClick(() => this.storLink += 1) .onClick(() => this.storLink += 1)
// You are not advised to use the global variable linkToPropA.get() in the component because errors may occur due to different life cycles. // Avoid using the global variable linkToPropA.get() in the component. Doing so may cause errors due to different lifecycles.
Text(`@LocalStorageLink: ${this.storLink} - linkToPropA: ${linkToPropA.get()}`) Text(`@LocalStorageLink: ${this.storLink} - linkToPropA: ${linkToPropA.get()}`)
} }
} }
...@@ -306,7 +306,7 @@ This example shows how to use \@LocalStorageLink to create a two-way synchroniza ...@@ -306,7 +306,7 @@ This example shows how to use \@LocalStorageLink to create a two-way synchroniza
Check the changes in the **Parent** custom component. Check the changes in the **Parent** custom component.
1. Clicking **countStorage ${this.playCount} incr by 1** decreases the value of **this.playCount** by 1. This change is synchronized to LocalStorage and to the components bound to **playCountLink** in the **Child** component. 1. Clicking **playCount ${this.playCount} dec by 1** decreases the value of **this.playCount** by 1. This change is synchronized to LocalStorage and to the components bound to **playCountLink** in the **Child** component.
2. Click **countStorage ${this.playCount} incr by 1** to call the **set** API in LocalStorage to update the attributes corresponding to **countStorage** in LocalStorage. The components bound to** playCountLink** in the **Child** component are updated synchronously. 2. Click **countStorage ${this.playCount} incr by 1** to call the **set** API in LocalStorage to update the attributes corresponding to **countStorage** in LocalStorage. The components bound to** playCountLink** in the **Child** component are updated synchronously.
...@@ -379,7 +379,7 @@ Changes in the **Child** custom component: ...@@ -379,7 +379,7 @@ Changes in the **Child** custom component:
### Sharing a LocalStorage Instance from UIAbility to One or More Pages ### Sharing a LocalStorage Instance from UIAbility to One or More Pages
In the preceding examples, the LocalStorage instance is shared only in an \@Entry decorated component and its owning child component (a page). To enable a LocalStorage instance to be shared across pages, you can create a LocalStorage instance in the owning UIAbility and call windowStage.[loadContent](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-window.md#loadcontent9). In the preceding examples, the LocalStorage instance is shared only in an \@Entry decorated component and its owning child component (a page). To enable a LocalStorage instance to be shared across pages, you can create a LocalStorage instance in the owning UIAbility and call windowStage.[loadContent](../reference/apis/js-apis-window.md#loadcontent9).
```ts ```ts
...@@ -420,7 +420,6 @@ struct CompA { ...@@ -420,7 +420,6 @@ struct CompA {
} }
``` ```
> **NOTE** > **NOTE**
> >
> It is good practice to always create a LocalStorage instance with meaningful default values, which serve as a backup when execution exceptions occur and are also useful for unit testing of pages. > It is good practice to always create a LocalStorage instance with meaningful default values, which serve as a backup when execution exceptions occur and are also useful for unit testing of pages.
......
...@@ -15,7 +15,7 @@ The decorators described above can observe only the changes of the first layer. ...@@ -15,7 +15,7 @@ The decorators described above can observe only the changes of the first layer.
- Regarding classes decorated by \@Observed, the attribute changes can be observed. - Regarding classes decorated by \@Observed, the attribute changes can be observed.
- The \@ObjectLink decorated state variable in the child component is used to accept the instance of the \@Observed decorated class and establish two-way data binding with the corresponding state variable in the parent component. The instance can be an \@Observed decorated item in the array or an \@Observeddecorated attribute in the class object. - The \@ObjectLink decorated state variable in the child component is used to accept the instance of the \@Observed decorated class and establish two-way data binding with the corresponding state variable in the parent component. The instance can be an \@Observed decorated item in the array or an \@Observed decorated attribute in the class object.
- Using \@Observed alone has no effect. Combined use with \@ObjectLink for two-way synchronization or with [\@Prop](arkts-prop.md) for one-way synchronization is required. - Using \@Observed alone has no effect. Combined use with \@ObjectLink for two-way synchronization or with [\@Prop](arkts-prop.md) for one-way synchronization is required.
...@@ -54,7 +54,7 @@ this.objLink= ... ...@@ -54,7 +54,7 @@ this.objLink= ...
> >
> - \@Prop creates a one-way synchronization from the data source to the decorated variable. It takes a copy of its source tp enable changes to remain local. When \@Prop observes a change to its source, the local value of the \@Prop decorated variable is overwritten. > - \@Prop creates a one-way synchronization from the data source to the decorated variable. It takes a copy of its source tp enable changes to remain local. When \@Prop observes a change to its source, the local value of the \@Prop decorated variable is overwritten.
> >
> - \@ObjectLink creates a two-way synchronization between the data source and the decorated variable. An \@ObjectLink decorated variable can be considered as a pointer to the source object inside the parent component. If value assignment of an \@ObjectLink decorated variable occurs, the synchronization chain is interrupted. > - \@ObjectLink creates a two-way synchronization between the data source and the decorated variable. An \@ObjectLink decorated variable can be considered as a pointer to the source object inside the parent component. Do not assign values to \@ObjectLink decorated variables, as doing so will interrupt the synchronization chain. \@ObjectLink decorated variables are initialized through data source (Object) references. Assigning a value to them is equivalent to updating the array item or class attribute in the parent component, which is not supported in TypeScript/JavaScript and will result in a runtime error.
## Variable Transfer/Access Rules ## Variable Transfer/Access Rules
...@@ -216,13 +216,13 @@ Event handlers in **ViewB**: ...@@ -216,13 +216,13 @@ Event handlers in **ViewB**:
- this.b.a = new ClassA(0) and this.b = new ClassB(new ClassA(0)): Change to the \@State decorated variable **b** and its attributes. - this.b.a = new ClassA(0) and this.b = new ClassB(new ClassA(0)): Change to the \@State decorated variable **b** and its attributes.
- this.b.a.c = ... : Second change. [@State](arkts-state.md#observed-changes) cannot observe the change of the second layer, but ClassA is decorated by \@Observed, and therefore the change of its attribute c can be observed by \@ObjectLink. - this.b.a.c = ... : Change at the second layer. Though [@State](arkts-state.md#observed-changes) cannot observe the change at the second layer, the change of an attribute of \@Observed decorated ClassA, which is attribute **c** in this example, can be observed by \@ObjectLink.
Event handlers in **ViewA**: Event handlers in **ViewA**:
- this.a.c += 1: Changes to the \@ObjectLink decorated variable which cause the button label to be updated. Unlike \@Prop, \@ObjectLink does not have a copy of its source. Instead, \@ObjectLink creates a reference to its source. - this.a.c += 1: Changes to the \@ObjectLink decorated variable cause the button label to be updated. Unlike \@Prop, \@ObjectLink does not have a copy of its source. Instead, \@ObjectLink creates a reference to its source.
- The \@ObjectLink decorated variable is read-only. Assigning **this.a = new ClassA(...)** is not allowed. Once value assignment occurs, the reference to the data source is reset and the synchronization is interrupted. - The \@ObjectLink decorated variable is read-only. Assigning **this.a = new ClassA(...)** is not allowed. Once value assignment occurs, the reference to the data source is reset and the synchronization is interrupted.
...@@ -300,7 +300,7 @@ struct ViewB { ...@@ -300,7 +300,7 @@ struct ViewB {
1. ForEach: The newly added Class A object is unknown to the **ForEach** [itemGenerator](arkts-rendering-control-foreach.md#api-description). The item builder of **ForEach** will be executed to create a **View A** component instance. 1. ForEach: The newly added Class A object is unknown to the **ForEach** [itemGenerator](arkts-rendering-control-foreach.md#api-description). The item builder of **ForEach** will be executed to create a **View A** component instance.
2. ViewA({ label: ViewA this.arrA[last], a: this.arrA[this.arrA.length-1] }): The last item of the array is changed. As a result, the second **View A** component instance is changed. For **ViewA({ label: ViewA this.arrA[first], a: this.arrA[0] })**, a change to the array does not trigger a change to the array item, so the first **View A** component instance is not refreshed. 2. ViewA({ label: ViewA this.arrA[last], a: this.arrA[this.arrA.length-1] }): The last item of the array is changed. As a result, the second **View A** component instance is changed. For **ViewA({ label: ViewA this.arrA[first], a: this.arrA[0] })**, a change to the array does not trigger a change to the array item, so the first **View A** component instance is not refreshed.
- this.arrA[Math.floor (this.arrA.length/2)].c: [@State](arkts-state.md#observed-changes) cannot observe changes in the second layer. However, as **ClassA** is decorated by \@Observed, the change of its attributes will be observed by \@ObjectLink. - this.arrA[Math.floor (this.arrA.length/2)].c: [@State](arkts-state.md#observed-changes) cannot observe changes at the second layer. However, as **ClassA** is decorated by \@Observed, the change of its attributes will be observed by \@ObjectLink.
### Two-Dimensional Array ### Two-Dimensional Array
......
...@@ -20,12 +20,12 @@ For an \@Prop decorated variable, the value synchronization is uni-directional f ...@@ -20,12 +20,12 @@ For an \@Prop decorated variable, the value synchronization is uni-directional f
## Rules of Use ## Rules of Use
| \@Prop Decorator | Description | | \@Prop Decorator| Description |
| ------------------ | ------------------------------------------------------------ | | ----------- | ---------------------------------------- |
| Decorator parameters | None. | | Decorator parameters | None. |
| Synchronization type | One-way: from the data source provided by the parent component to the @Prop decorated variable. For details about the scenarios of nested types, see [Observed Changes](#observed-changes).| | Synchronization type | One-way: from the data source provided by the parent component to the @Prop decorated variable. For details about the scenarios of nested types, see [Observed Changes](#observed-changes).|
| Allowed variable types| Object, class, string, number, Boolean, enum, and array of these types.<br>**any** is not supported. A combination of simple and complex types is not supported. The **undefined** and **null** values are not allowed.<br>The type must be specified.<br>**NOTE**<br>The Length, ResourceStr, and ResourceColor types are a combination of simple and complex types and therefore not supported.<br>Negative examples:<br>CompA&nbsp;({&nbsp;aProp:&nbsp;undefined&nbsp;})<br>CompA&nbsp;({&nbsp;aProp:&nbsp;null&nbsp;})<br>The type must be the same as that of the [data source](arkts-state-management-overview.md#basic-concepts). There are three cases:<br>- Synchronizing the \@Prop decorated variable from an \@State or other decorated variable. Example: [Simple Type @Prop Synced from @State in Parent Component](#simple-type-prop-synced-from-state-in-parent-component).<br>- Synchronizing the \@Prop decorated variable from the item of an \@State or other decorated array. Example: [Simple Type @Prop Synced from @State Array Item in Parent Component](#simple-type-prop-synced-from-state-array-item-in-parent-component).<br>- Synchronizing the \@Prop decorated variable from a state attribute of the Object or class type in the parent component. Example: [Class Object Type @Prop Synced from @State Class Object Attribute in Parent Component](#class-object-type-prop-synced-from-state-class-object-attribute-in-parent-component).| | Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.<br>**any** is not supported. A combination of simple and complex types is not supported. The **undefined** and **null** values are not allowed.<br>Date type.<br>For details about the scenarios of supported types, see [Observed Changes](#observed-changes).<br>The type must be specified.<br>**NOTE**<br>The Length, ResourceStr, and ResourceColor types are a combination of simple and complex types and therefore not supported.<br>Negative examples:<br>CompA ({ aProp: undefined })<br>CompA ({ aProp: null })<br>The type must be the same as that of the [data source](arkts-state-management-overview.md#basic-concepts). There are three cases:<br>- Synchronizing the \@Prop decorated variable from an \@State or other decorated variable. Example: [Simple Type @Prop Synced from @State in Parent Component](#simple-type-prop-synced-from-state-in-parent-component).<br>- Synchronizing the \@Prop decorated variable from the item of an \@State or other decorated array. Example: [Simple Type @Prop Synced from @State Array Item in Parent Component](#simple-type-prop-synced-from-state-array-item-in-parent-component).<br>- Synchronizing the \@Prop decorated variable from a state attribute of the Object or class type in the parent component. Example: [Class Object Type @Prop Synced from @State Class Object Attribute in Parent Component](#class-object-type-prop-synced-from-state-class-object-attribute-in-parent-component).|
| Initial value for the decorated variable| Local initialization is allowed. | | Initial value for the decorated variable | Local initialization is allowed. |
## Variable Transfer/Access Rules ## Variable Transfer/Access Rules
...@@ -134,6 +134,61 @@ For synchronization between \@State and \@Prop decorated variables: ...@@ -134,6 +134,61 @@ For synchronization between \@State and \@Prop decorated variables:
- In addition to \@State, the source can also be decorated with \@Link or \@Prop, where the mechanisms for syncing the \@Prop would be the same. - In addition to \@State, the source can also be decorated with \@Link or \@Prop, where the mechanisms for syncing the \@Prop would be the same.
- The source and \@Prop decorated variable must be of the same type. The \@Prop decorated variable can be of simple and class types. - The source and \@Prop decorated variable must be of the same type. The \@Prop decorated variable can be of simple and class types.
- When the decorated variable is of the Date type, the overall value assignment of the Date object can be observed, and the following APIs can be called to update Date attributes: **setFullYear**, **setMonth**, **setDate**, **setHours**, **setMinutes**, **setSeconds**, **setMilliseconds**, **setTime**, **setUTCFullYear**, **setUTCMonth**, **setUTCDate**, **setUTCHours**, **setUTCMinutes**, **setUTCSeconds**, and **setUTCMilliseconds**.
```ts
@Component
struct DateComponent {
@Prop selectedDate: Date;
build() {
Column() {
Button('child update the new date')
.margin(10)
.onClick(() => {
this.selectedDate = new Date('2023-09-09')
})
Button(`child increase the year by 1`).onClick(() => {
this.selectedDate.setFullYear(this.selectedDate.getFullYear() + 1)
})
DatePicker({
start: new Date('1970-1-1'),
end: new Date('2100-1-1'),
selected: this.selectedDate
})
}
}
}
@Entry
@Component
struct ParentComponent {
@State parentSelectedDate: Date = new Date('2021-08-08');
build() {
Column() {
Button('parent update the new date')
.margin(10)
.onClick(() => {
this.parentSelectedDate = new Date('2023-07-07')
})
Button('parent increase the day by 1')
.margin(10)
.onClick(() => {
this.parentSelectedDate.setDate(this.parentSelectedDate.getDate() + 1)
})
DatePicker({
start: new Date('1970-1-1'),
end: new Date('2100-1-1'),
selected: this.parentSelectedDate
})
DateComponent({selectedDate:this.parentSelectedDate})
}
}
}
```
### Framework Behavior ### Framework Behavior
......
...@@ -18,9 +18,9 @@ An \@Provide decorated state variable exists in the ancestor component and is sa ...@@ -18,9 +18,9 @@ An \@Provide decorated state variable exists in the ancestor component and is sa
- An \@Provide decorated state variable becomes available to all descendent components of the providing component automatically. The variable is said to be "provided" to other components. This means that you do not need to pass a variable from component to component multiple times. - An \@Provide decorated state variable becomes available to all descendent components of the providing component automatically. The variable is said to be "provided" to other components. This means that you do not need to pass a variable from component to component multiple times.
- A descendent component gains access to the provided state variable by decorating a variable with \@Consume. This establishes a two-way data synchronization between the provided and the consumed variable. This synchronization works the same as a combination of \@State and \@Link does. The only difference is that the former allows transfer across multiple levels of the UI parent-child hierarchy. - A descendent component gains access to the provided state variable by decorating a variable with \@Consume. This establishes a two-way data synchronization between the provided and the consumed variable. This synchronization works in the same manner as a combination of \@State and \@Link does. The only difference is that the former allows transfer across multiple levels of the UI parent-child hierarchy.
- \@Provide and \@Consume can be bound using the same variable name or variable alias. The variable types must be the same. - \@Provide and \@Consume can be bound using the same variable name or variable alias. Whenever possible, use the same variable types to prevent implicit type conversion and consequently application behavior exceptions.
```ts ```ts
...@@ -34,7 +34,7 @@ An \@Provide decorated state variable exists in the ancestor component and is sa ...@@ -34,7 +34,7 @@ An \@Provide decorated state variable exists in the ancestor component and is sa
``` ```
When \@Provide and \@Consume are bound through the same variable name or variable alias, the variables decorated by \@Provide and \@Consume are in a one-to-many relationship. A custom component, including its child components, cannot contain multiple \@Provide decorated variables under the same name or alias. When \@Provide and \@Consume are bound through the same variable name or variable alias, the variables decorated by \@Provide and \@Consume are in a one-to-many relationship. A custom component, including its child components, cannot contain multiple \@Provide decorated variables under the same name or alias. Otherwise, a runtime error will occur.
## Decorator Description ## Decorator Description
...@@ -45,14 +45,14 @@ The rules of \@State also apply to \@Provide. The difference is that \@Provide a ...@@ -45,14 +45,14 @@ The rules of \@State also apply to \@Provide. The difference is that \@Provide a
| -------------- | ---------------------------------------- | | -------------- | ---------------------------------------- |
| Decorator parameters | Alias: constant string, optional.<br>If the alias is specified, the variable is provided under the alias name only. If the alias is not specified, the variable is provided under the variable name.| | Decorator parameters | Alias: constant string, optional.<br>If the alias is specified, the variable is provided under the alias name only. If the alias is not specified, the variable is provided under the variable name.|
| Synchronization type | Two-way:<br>from the \@Provide decorated variable to all \@Consume decorated variables; and the other way around. The two-way synchronization behaviour is the same as that of the combination of \@State and \@Link.| | Synchronization type | Two-way:<br>from the \@Provide decorated variable to all \@Consume decorated variables; and the other way around. The two-way synchronization behaviour is the same as that of the combination of \@State and \@Link.|
| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested types, see [Observed Changes](#observed-changes).<br>**any** is not supported. A combination of simple and complex types is not supported. The **undefined** and **null** values are not allowed.<br>The type must be specified. The type of the provided and the consumed variables must be the same.<br>**NOTE**<br>The Length, ResourceStr, and ResourceColor types are a combination of simple and complex types and therefore not supported.| | Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.<br>Date type.<br>For details about the scenarios of supported types, see [Observed Changes](#observed-changes).<br>**any** is not supported. A combination of simple and complex types is not supported. The **undefined** and **null** values are not allowed.<br>The type must be specified. The type of the provided and the consumed variables must be the same.<br>**NOTE**<br>The Length, ResourceStr, and ResourceColor types are a combination of simple and complex types and therefore not supported.|
| Initial value for the decorated variable | Mandatory. | | Initial value for the decorated variable | Mandatory. |
| \@Consume Decorator| Description | | \@Consume Decorator| Description |
| -------------- | ---------------------------------------- | | -------------- | ---------------------------------------- |
| Decorator parameters | Alias: constant string, optional.<br>If the alias is specified, the alias name is used for matching with the \@Provide decorated variable. Otherwise, the variable name is used.| | Decorator parameters | Alias: constant string, optional.<br>If the alias is specified, the alias name is used for matching with the \@Provide decorated variable. Otherwise, the variable name is used.|
| Synchronization type | from the \@Provide decorated variable to all \@Consume decorated variables; and the other way around. The two-way synchronization behaviour is the same as that of the combination of \@State and \@Link.| | Synchronization type | from the \@Provide decorated variable to all \@Consume decorated variables; and the other way around. The two-way synchronization behaviour is the same as that of the combination of \@State and \@Link.|
| Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types. For details about the scenarios of nested types, see [Observed Changes](#observed-changes).<br>**any** is not supported. The **undefined** and **null** values are not allowed.<br>The type must be specified. The type of the provided and the consumed variables must be the same.<br>**NOTE**<br>An \@Consume decorated variable must have a matching \@Provide decorated variable with the corresponding attribute and alias on its parent or ancestor node.| | Allowed variable types | Object, class, string, number, Boolean, enum, and array of these types.<br>Date type.<br>For details about the scenarios of supported types, see [Observed Changes](#observed-changes).<br>**any** is not supported. The **undefined** and **null** values are not allowed.<br>The type must be specified. The type of the provided and the consumed variables must be the same.<br>**NOTE**<br>An \@Consume decorated variable must have a matching \@Provide decorated variable with the corresponding attribute and alias on its parent or ancestor node.|
| Initial value for the decorated variable | Forbidden. | | Initial value for the decorated variable | Forbidden. |
...@@ -99,6 +99,62 @@ The rules of \@State also apply to \@Provide. The difference is that \@Provide a ...@@ -99,6 +99,62 @@ The rules of \@State also apply to \@Provide. The difference is that \@Provide a
- When the decorated variable is of the array type, the addition, deletion, and updates of array items can be observed. - When the decorated variable is of the array type, the addition, deletion, and updates of array items can be observed.
- When the decorated variable is of the Date type, the overall value assignment of the Date object can be observed, and the following APIs can be called to update Date attributes: **setFullYear**, **setMonth**, **setDate**, **setHours**, **setMinutes**, **setSeconds**, **setMilliseconds**, **setTime**, **setUTCFullYear**, **setUTCMonth**, **setUTCDate**, **setUTCHours**, **setUTCMinutes**, **setUTCSeconds**, and **setUTCMilliseconds**.
```ts
@Component
struct CompD {
@Consume selectedDate: Date;
build() {
Column() {
Button(`child increase the day by 1`)
.onClick(() => {
this.selectedDate.setDate(this.selectedDate.getDate() + 1)
})
Button('child update the new date')
.margin(10)
.onClick(() => {
this.selectedDate = new Date('2023-09-09')
})
DatePicker({
start: new Date('1970-1-1'),
end: new Date('2100-1-1'),
selected: this.selectedDate
})
}
}
}
@Entry
@Component
struct CompA {
@Provide selectedDate: Date = new Date('2021-08-08')
build() {
Column() {
Button('parent increase the day by 1')
.margin(10)
.onClick(() => {
this.selectedDate.setDate(this.selectedDate.getDate() + 1)
})
Button('parent update the new date')
.margin(10)
.onClick(() => {
this.selectedDate = new Date('2023-07-07')
})
DatePicker({
start: new Date('1970-1-1'),
end: new Date('2100-1-1'),
selected: this.selectedDate
})
CompD()
}
}
}
```
### Framework Behavior ### Framework Behavior
......
# stateStyles Decorator: Polymorphic Style # stateStyles: Polymorphic Style
Unlike \@Styles and \@Extend, which are used to reuse styles only on static pages, stateStyles enables you to set state-specific styles. Unlike \@Styles and \@Extend, which are used to reuse styles only on static pages, stateStyles enables you to set state-specific styles.
...@@ -16,6 +16,8 @@ stateStyles is an attribute method that sets the style based on the internal sta ...@@ -16,6 +16,8 @@ stateStyles is an attribute method that sets the style based on the internal sta
- disabled - disabled
- selected<sup>10+</sup>
## Application Scenarios ## Application Scenarios
......
# \@Watch: Getting Notified of State Variable Changes # \@Watch Decorator: Getting Notified of State Variable Changes
\@Watch is used to listen for state variables. If your application needs watch for value changes of a state variable, you can decorate the variable with \@Watch. \@Watch is used to listen for state variables. If your application needs watch for value changes of a state variable, you can decorate the variable with \@Watch.
...@@ -27,7 +27,7 @@ An application can request to be notified whenever the value of the \@Watch deco ...@@ -27,7 +27,7 @@ An application can request to be notified whenever the value of the \@Watch deco
| Type | Description | | Type | Description |
| ---------------------------------------- | ---------------------------------------- | | ---------------------------------------- | ---------------------------------------- |
| (changedPropertyName?&nbsp;:&nbsp;string)&nbsp;=&gt;&nbsp;void | This function is a member function of the custom component. **changedPropertyName** indicates the name of the watched attribute.<br>It is useful when you use the same function as a callback to several watched attributes.<br>It takes the attribute name as a string input parameter and returns nothing.| | (changedPropertyName? : string) =&gt; void | This function is a member function of the custom component. **changedPropertyName** indicates the name of the watched attribute.<br>It is useful when you use the same function as a callback to several watched attributes.<br>It takes the attribute name as a string input parameter and returns nothing.|
## Observed Changes and Behavior ## Observed Changes and Behavior
...@@ -131,7 +131,7 @@ The processing procedure is as follows: ...@@ -131,7 +131,7 @@ The processing procedure is as follows:
### \@Watch and Custom Component Update ### \@Watch and Custom Component Update
This example is used to clarify the processing steps of custom component updates and \@Watch. Note that **count** is @State decorated in both components. This example is used to clarify the processing steps of custom component updates and \@Watch. **count** is decorated by \@State in **CountModifier** and \@Prop in **TotalView**.
```ts ```ts
......
...@@ -146,7 +146,7 @@ struct Index { ...@@ -146,7 +146,7 @@ struct Index {
} }
``` ```
### Redirecting to a Page in Another Bundle ### Redirecting to a Page
If you want to add a button in the **entry** module to jump to the menu page (**library/src/main/ets/pages/menu.ets**) in the **library** module, you can write the following code in the **entry/src/main/ets/MainAbility/Index.ets** file of the **entry** module: If you want to add a button in the **entry** module to jump to the menu page (**library/src/main/ets/pages/menu.ets**) in the **library** module, you can write the following code in the **entry/src/main/ets/MainAbility/Index.ets** file of the **entry** module:
```ts ```ts
......
...@@ -6,7 +6,7 @@ The **Animator** module provides APIs for applying animation effects, including ...@@ -6,7 +6,7 @@ The **Animator** module provides APIs for applying animation effects, including
> >
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> >
> This module can be used only after a component instance is created, and it cannot be used in the [UIAbility](./js-apis-app-ability-uiAbility.md). > This module cannot be used in the file declaration of the [UIAbility](./js-apis-app-ability-uiAbility.md). In other words, the APIs of this module can be used only after a component instance is created; they cannot be called in the lifecycle of the UIAbility.
> >
> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext). > The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext).
> >
...@@ -40,7 +40,9 @@ Creates an **Animator** object. ...@@ -40,7 +40,9 @@ Creates an **Animator** object.
**Example** **Example**
```js ```js
let options = { import animator, { AnimatorOptions } from '@ohos.animator';
let options: AnimatorOptions = { // The explicit type AnimatorOptions does not need to be emphasized in the xxx.js file.
duration: 1500, duration: 1500,
easing: "friction", easing: "friction",
delay: 0, delay: 0,
...@@ -49,8 +51,8 @@ Creates an **Animator** object. ...@@ -49,8 +51,8 @@ Creates an **Animator** object.
iterations: 3, iterations: 3,
begin: 200.0, begin: 200.0,
end: 400.0 end: 400.0
}; };
animator.create(options); animator.create(options);
``` ```
## AnimatorResult ## AnimatorResult
...@@ -83,7 +85,7 @@ For details about the error codes, see [Animator Error Codes](../errorcodes/erro ...@@ -83,7 +85,7 @@ For details about the error codes, see [Animator Error Codes](../errorcodes/erro
**Example** **Example**
```js ```js
let options = { let options: AnimatorOptions = { // The explicit type AnimatorOptions does not need to be emphasized in the xxx.js file.
duration: 1500, duration: 1500,
easing: "friction", easing: "friction",
delay: 0, delay: 0,
...@@ -516,7 +518,7 @@ This API is deprecated since API version 9. You are advised to use [create<sup>9 ...@@ -516,7 +518,7 @@ This API is deprecated since API version 9. You are advised to use [create<sup>9
**Example** **Example**
```js ```js
let options = { let options: AnimatorOptions = { // The explicit type AnimatorOptions does not need to be emphasized in the xxx.js file.
duration: 1500, duration: 1500,
easing: "friction", easing: "friction",
delay: 0, delay: 0,
......
# @ohos.app.ability.DriverExtensionAbility (DriverExtensionAbility)
The **DriverExtensionAbility** module provides the ExtensionAbility related to drivers. It provides lifecycle callbacks to be invoked when a driver is created, destroyed, connected, or disconnected.
> **NOTE**
>
> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
## Modules to Import
```ts
import DriverExtension from '@ohos.app.ability.DriverExtensionAbility';
```
## Required Permissions
None.
## Attributes
**System capability**: SystemCapability.Driver.ExternalDevice
**System API**: This is a system API and cannot be called by third-party applications.
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| context | [DriverExtensionContext](js-apis-inner-application-driverExtensionContext.md) | Yes| No| Context of the **DriverExtension**. This context is inherited from **ExtensionContext**.|
## DriverExtensionAbility.onInit
onInit(want: Want): void;
Called when a DriverExtensionAbility is created to initialize the service logic.
**System capability**: SystemCapability.Driver.ExternalDevice
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this DriverExtensionAbility, including the ability name and bundle name.|
**Example**
```ts
class DriverExt extends DriverExtension {
onInit(want) {
console.log('onInit, want: ${want.abilityName}');
}
}
```
## DriverExtensionAbility.onRelease
onRelease(): void;
Called when this DriverExtensionAbility is destroyed to clear resources.
**System capability**: SystemCapability.Driver.ExternalDevice
**System API**: This is a system API and cannot be called by third-party applications.
**Example**
```ts
class DriverExt extends DriverExtension {
onRelease() {
console.log('onRelease');
}
}
```
## DriverExtensionAbility.onConnect
onConnect(want: Want): rpc.RemoteObject | Promise<rpc.RemoteObject>;
Called following **onCreate()** when a DriverExtensionAbility is started by calling **connectAbility()**. A **RemoteObject** object is returned for communication between the server and client.
**System capability**: SystemCapability.Driver.ExternalDevice
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-app-ability-want.md)| Yes| Want information related to this DriverExtensionAbility, including the ability name and bundle name.|
**Return value**
| Type| Description|
| -------- | -------- |
| rpc.RemoteObject | A **RemoteObject** object used for communication between the server and client.|
**Example**
```ts
import rpc from '@ohos.rpc';
class StubTest extends rpc.RemoteObject{
constructor(des) {
super(des);
}
onRemoteRequest(code, data, reply, option) {
}
}
class DriverExt extends DriverExtension {
onConnect(want) {
console.log('onConnect , want: ${want.abilityName}');
return new StubTest('test');
}
}
```
If the returned **RemoteObject** object depends on an asynchronous API, you can use the asynchronous lifecycle.
```ts
import rpc from '@ohos.rpc';
class StubTest extends rpc.RemoteObject{
constructor(des) {
super(des);
}
onRemoteRequest(code, data, reply, option) {
}
}
async function getDescriptor() {
// Call the asynchronous function.
return "asyncTest"
}
class DriverExt extends DriverExtension {
async onConnect(want) {
console.log(`onConnect , want: ${want.abilityName}`);
let descriptor = await getDescriptor();
return new StubTest(descriptor);
}
}
```
## DriverExtensionAbility.onDisconnect
onDisconnect(want: Want): void | Promise\<void>;
Called when a client is disconnected from this DriverExtensionAbility.
**System capability**: SystemCapability.Driver.ExternalDevice
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this DriverExtensionAbility, including the ability name and bundle name.|
**Example**
```ts
class DriverExt extends DriverExtension {
onDisconnect(want) {
console.log('onDisconnect, want: ${want.abilityName}');
}
}
```
After the **onDisconnect** lifecycle callback is executed, the application may exit. As a result, the asynchronous function in **onDisconnect** may fail to be executed correctly, for example, asynchronously writing data to the database. The asynchronous lifecycle can be used to ensure that the subsequent lifecycle continues after the asynchronous **onDisconnect** is complete.
```ts
class DriverExt extends DriverExtension {
async onDisconnect(want) {
console.log('onDisconnect, want: ${want.abilityName}');
// Call the asynchronous function.
}
}
```
## DriverExtensionAbility.onDump
onDump(params: Array\<string>): Array\<string>;
Dumps client information.
**System capability**: SystemCapability.Driver.ExternalDevice
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| params | Array\<string> | Yes| Parameters in the form of a command.|
**Example**
```ts
class DriverExt extends DriverExtension {
onDump(params) {
console.log('dump, params: ${JSON.stringify(params)}');
return ['params'];
}
}
```
# DriverExtensionContext
The **DriverExtensionContext** module provides the context of **DriverExtensionAbility**. It inherits from **ExtensionContext**.
The **DriverExtensionContext** module provides the operations that need to be actively initiated in the **DriverExtensionAbility** implementation.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> - The APIs of this module can be used only in the stage model.
## Modules to Import
```ts
import common from '@ohos.app.ability.common';
```
## How to Use
Before using **DriverExtensionContext**, you need to obtain it through a **DriverExtensionAbility** child class instance.
```ts
import DriverExtensionAbility from '@ohos.app.ability.DriverExtensionAbility';
let context;
class EntryAbility extends DriverExtensionAbility {
onInit() {
context = this.context; // Obtain DriverExtensionContext.
}
}
```
## DriverExtensionContext.updateDriverState
updateDriverState(): void;
Updates the driver state. This interface is reserved and does not provide specific functionality currently.
**System capability**: SystemCapability.Driver.ExternalDevice
**Example**
```ts
this.context.updateDriverState() ;
```
...@@ -6,7 +6,7 @@ The **mediaquery** module provides different styles for different media types. ...@@ -6,7 +6,7 @@ The **mediaquery** module provides different styles for different media types.
> >
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> >
> This module can be used only after a component instance is created, and it cannot be used in the [UIAbility](./js-apis-app-ability-uiAbility.md). > This module cannot be used in the file declaration of the [UIAbility](./js-apis-app-ability-uiAbility.md). In other words, the APIs of this module can be used only after a component instance is created; they cannot be called in the lifecycle of the UIAbility.
> >
> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext). > The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext).
> >
......
...@@ -6,7 +6,7 @@ The **PromptAction** module provides APIs for creating and showing toasts, dialo ...@@ -6,7 +6,7 @@ The **PromptAction** module provides APIs for creating and showing toasts, dialo
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> >
> This module can be used only after a component instance is created, and it cannot be used in the [UIAbility](./js-apis-app-ability-uiAbility.md). > This module cannot be used in the file declaration of the [UIAbility](./js-apis-app-ability-uiAbility.md). In other words, the APIs of this module can be used only after a component instance is created; they cannot be called in the lifecycle of the UIAbility.
> >
> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext). > The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](./js-apis-arkui-UIContext.md#uicontext).
> >
......
...@@ -14,14 +14,18 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -14,14 +14,18 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------------------------------------------| ---- | ------------------------------------------------------------ | | ---------- | ------------------------------------------| ---- | ------------------------------------------------------------ |
| duration | number | No | Animation duration, in ms.<br>Default value: **1000**<br>Unit: ms<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>- The maximum animation duration on an ArkTS widget is 1000 ms.<br>- A value less than 1 evaluates to the value **0**.<br>- If the value is of the floating point type, the value is rounded down. If the value is 1.2, the value **1** is used.| | duration | number | No | Animation duration, in ms.<br>Default value: **1000**<br>Unit: ms<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>- The maximum animation duration on an ArkTS widget is 1000 ms.<br>- A value less than 0 evaluates to the value **0**.<br>- Floating-point values will be rounded down to integers. For example, if the value set is 1.2, **1** will be used.|
| tempo | number | No | Animation playback speed. A larger value indicates a higher animation playback speed.<br>The value **0** indicates that no animation is applied.<br>Default value: **1**<br>**NOTE**<br>A value less than 1 evaluates to the value **1**.| | tempo | number | No | Animation playback speed. A larger value indicates a higher animation playback speed.<br>The value **0** indicates that no animation is applied.<br>Default value: **1**<br>**NOTE**<br>A value less than 0 evaluates to the value **1**.|
| curve | string \| [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve)<sup>9+</sup> | No | Animation curve. The default curve is linear.<br>Default value: **Curve.Linear**<br>Since API version 9, this API is supported in ArkTS widgets.| | curve | string \| [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve)<sup>9+</sup> | No | Animation curve. The default curve is linear.<br>Default value: **Curve.Linear**<br>Since API version 9, this API is supported in ArkTS widgets.|
| delay | number | No | Delay of animation playback, in ms. The value **0** indicates that the playback is not delayed.<br>Default value: **0**<br>Value range: [0, +∞)<br>**NOTE**<br>A value less than 1 evaluates to the value **0**. If the value is of the floating point type, the value is rounded down. If the value is 1.2, the value **1** is used.| | delay | number | No | Delay of animation playback, in ms. The value **0** indicates that the playback is not delayed.<br>Default value: **0**<br>Value range: [0, +∞)<br>**NOTE**<br>- A value less than 0 evaluates to the value **0**.<br>- Floating-point values will be rounded down to integers. For example, if the value set is 1.2, **1** will be used.|
| iterations | number | No | Number of times that the animation is played.<br>Default value: **1**<br>Value range: [-1, +∞)<br>**NOTE**<br>The value **-1** indicates that the animation is played for an unlimited number of times. The value **0** indicates that no animation is applied.| | iterations | number | No | Number of times that the animation is played.<br>Default value: **1**<br>Value range: [-1, +∞)<br>**NOTE**<br>The value **-1** indicates that the animation is played for an unlimited number of times. The value **0** indicates that no animation is applied.|
| playMode | [PlayMode](ts-appendix-enums.md#playmode) | No | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.<br>Default value: **PlayMode.Normal**<br>Since API version 9, this API is supported in ArkTS widgets.| | playMode | [PlayMode](ts-appendix-enums.md#playmode) | No | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.<br>Default value: **PlayMode.Normal**<br>Since API version 9, this API is supported in ArkTS widgets.<br>For details about the restrictions, see **Notes about PlayMode**.|
| onFinish | () => void | No | Callback invoked when the animation playback is complete.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This callback is not invoked when **iterations** is set to **-1**.| | onFinish | () => void | No | Callback invoked when the animation playback is complete.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This callback is not invoked when **iterations** is set to **-1**.|
> **Notes about PlayMode**:
> - **PlayMode.Normal** and **PlayMode.Alternate** are recommended. Under these settings, the first round of the animation is played forwards. If **PlayMode.Reverse** or **PlayMode.AlternateReverse** is used, the first round of the animation is played backwards. In this case, the animation jumps to the end state and then starts from there.
> - When using **PlayMode.Alternate** or **PlayMode.AlternateReverse**, make sure the final state of the animation is the same as the value of the state variable. In other words, make sure the last round of the animation is played forwards. When **PlayMode.Alternate** is used, **iterations** must be set to an odd number. When **PlayMode.AlternateReverse** is used, **iterations** must be set to an even number.
> - **PlayMode.Reverse** is not recommended. Under this setting, the animation jumps to the end state at the beginning, and its final state will be different from the value of the state variable.
## Example ## Example
......
...@@ -88,6 +88,7 @@ struct SelectExample { ...@@ -88,6 +88,7 @@ struct SelectExample {
.optionFont({ size: 16, weight: 400 }) .optionFont({ size: 16, weight: 400 })
.space(this.space) .space(this.space)
.arrowPosition(this.arrowPosition) .arrowPosition(this.arrowPosition)
.menuAlign(MenuAlignType.START, {dx:0, dy:0})
.onSelect((index:number, text: string)=>{ .onSelect((index:number, text: string)=>{
console.info('Select:' + index) console.info('Select:' + index)
this.index = index; this.index = index;
......
...@@ -40,8 +40,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md) and [ ...@@ -40,8 +40,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md) and [
| minFontSize | number \| string \| [Resource](ts-types.md#resource) | Minimum font size.<br>For the setting to take effect, this attribute must be used together with **maxFontSize**, **maxLines**, or layout constraint settings.<br>Since API version 9, this API is supported in ArkTS widgets. | | minFontSize | number \| string \| [Resource](ts-types.md#resource) | Minimum font size.<br>For the setting to take effect, this attribute must be used together with **maxFontSize**, **maxLines**, or layout constraint settings.<br>Since API version 9, this API is supported in ArkTS widgets. |
| maxFontSize | number \| string \| [Resource](ts-types.md#resource) | Maximum font size.<br>For the setting to take effect, this attribute must be used together with **minFontSize**, **maxLines**, or layout constraint settings.<br>Since API version 9, this API is supported in ArkTS widgets. | | maxFontSize | number \| string \| [Resource](ts-types.md#resource) | Maximum font size.<br>For the setting to take effect, this attribute must be used together with **minFontSize**, **maxLines**, or layout constraint settings.<br>Since API version 9, this API is supported in ArkTS widgets. |
| textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.<br>Default value: **TextCase.Normal**<br>Since API version 9, this API is supported in ArkTS widgets.| | textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.<br>Default value: **TextCase.Normal**<br>Since API version 9, this API is supported in ArkTS widgets.|
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.<br>Default value: **CopyOptions.None**<br>This API is supported in ArkTS widgets.| | copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.<br>Default value: **CopyOptions.None**<br>This API is supported in ArkTS widgets.<br>**NOTE**<br/>When this attribute is set to **CopyOptions.InApp** or **CopyOptions.LocalDevice**, a long press on the text will display a context menu that offers the copy and select-all options.|
| draggable<sup>(deprecated)</sup> | boolean | Drag effect of the selected text.<br>This attribute cannot be used with the [onDragStart](ts-universal-events-drag-drop.md) event.<br>It must be used with **copyOption** to enable the selected text to be dragged and copied.<br>Default value: **false**<br>**NOTE**<br/>This API is supported since API version 8 and deprecated since API version 10. You are advised to use the universal attribute [draggable](ts-universal-events-drag-drop.md) instead. | | draggable<sup>(deprecated)</sup> | boolean | Drag effect of the selected text.<br>This attribute cannot be used with the [onDragStart](ts-universal-events-drag-drop.md) event.<br>It must be used together with **copyOption**. When it is set to **true** and **copyOptions** is set to **CopyOptions.InApp** or **CopyOptions.LocalDevice**, the selected text can be dragged and copied to the text box.<br>Default value: **false**<br>**NOTE**<br/>This API is supported since API version 8 and deprecated since API version 10. You are advised to use the universal attribute [draggable](ts-universal-events-drag-drop.md) instead.|
| textShadow<sup>10+</sup> | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions) | Text shadow.| | textShadow<sup>10+</sup> | [ShadowOptions](ts-universal-attributes-image-effect.md#shadowoptions) | Text shadow.|
| heightAdaptivePolicy<sup>10+</sup> | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | How the adaptive height is determined for the text.<br>Default value: **TextHeightAdaptivePolicy.MAX_LINES_FIRST**<br>**NOTE**<br/>When this attribute is set to **TextHeightAdaptivePolicy.MAX_LINES_FIRST**, the **maxLines** attribute takes precedence for adjusting the text height. If the **maxLines** setting results in a layout beyond the layout constraints, the text will shrink to a font size between `minFontSize` and `maxFontSize` to allow for more content to be shown.<br>When this attribute is set to **TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST**, the **minFontSize** attribute takes precedence for adjusting the text height. If the text can fit in one line with the **minFontSize** setting, the text will enlarge to the largest possible font size between **minFontSize** and **maxFontSize**.<br>When this attribute is set to **TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST**, the layout constraints take precedence for adjusting the text height. If the resultant layout is beyond the layout constraints, the text will shrink to a font size between **minFontSize** and **maxFontSize** to respect the layout constraints. If the layout still exceeds the layout constraints after the font size is reduced to **minFontSize**, the lines that exceed the layout constraints are deleted. | | heightAdaptivePolicy<sup>10+</sup> | [TextHeightAdaptivePolicy](ts-appendix-enums.md#textheightadaptivepolicy10) | How the adaptive height is determined for the text.<br>Default value: **TextHeightAdaptivePolicy.MAX_LINES_FIRST**<br>**NOTE**<br/>When this attribute is set to **TextHeightAdaptivePolicy.MAX_LINES_FIRST**, the **maxLines** attribute takes precedence for adjusting the text height. If the **maxLines** setting results in a layout beyond the layout constraints, the text will shrink to a font size between `minFontSize` and `maxFontSize` to allow for more content to be shown.<br>When this attribute is set to **TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST**, the **minFontSize** attribute takes precedence for adjusting the text height. If the text can fit in one line with the **minFontSize** setting, the text will enlarge to the largest possible font size between **minFontSize** and **maxFontSize**.<br>When this attribute is set to **TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST**, the layout constraints take precedence for adjusting the text height. If the resultant layout is beyond the layout constraints, the text will shrink to a font size between **minFontSize** and **maxFontSize** to respect the layout constraints. If the layout still exceeds the layout constraints after the font size is reduced to **minFontSize**, the lines that exceed the layout constraints are deleted. |
| textIndent<sup>10+</sup> | number \| string | Indentation of the first line.<br>Default value: **0**| | textIndent<sup>10+</sup> | number \| string | Indentation of the first line.<br>Default value: **0**|
...@@ -250,3 +250,64 @@ struct TextExample2 { ...@@ -250,3 +250,64 @@ struct TextExample2 {
} }
``` ```
![textExp1](figures/textExp2.png) ![textExp1](figures/textExp2.png)
### Example 3
Example of using **textShadow**, **heightAdaptivePolicy**, and **TextOverflow.MARQUEE**:
```ts
@Entry
@Component
struct TextExample {
build() {
Column({ space: 8 }) {
Text('textShadow').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
Text('textShadow')
.width('80%')
.height(55)
.fontSize(40)
.lineHeight(55)
.textAlign(TextAlign.Center)
.textShadow({ radius: 10, color: Color.Black, offsetX: 0, offsetY: 0 })
.borderWidth(1)
Divider()
Text('heightAdaptivePolicy').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
Text('This is the text with the height adaptive policy set')
.width('80%')
.height(90)
.borderWidth(1)
.minFontSize(10)
.maxFontSize(30)
.maxLines(3)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.heightAdaptivePolicy(TextHeightAdaptivePolicy.MAX_LINES_FIRST)
Text('This is the text with the height adaptive policy set')
.width('80%')
.height(90)
.borderWidth(1)
.minFontSize(10)
.maxFontSize(30)
.maxLines(3)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.heightAdaptivePolicy(TextHeightAdaptivePolicy.MIN_FONT_SIZE_FIRST)
Text('This is the text with the height adaptive policy set')
.width('80%')
.height(90)
.borderWidth(1)
.minFontSize(10)
.maxFontSize(30)
.maxLines(3)
.textOverflow({ overflow: TextOverflow.Ellipsis })
.heightAdaptivePolicy(TextHeightAdaptivePolicy.LAYOUT_CONSTRAINT_FIRST)
Divider()
Text('marquee').fontSize(9).fontColor(0xCCCCCC).margin(15).width('90%')
Text('This is the text with the text overflow set marquee')
.width(300)
.borderWidth(1)
.textOverflow({ overflow: TextOverflow.MARQUEE })
}
}
}
```
![](figures/text_3.gif)
...@@ -413,6 +413,70 @@ struct Matrix2DMultiply { ...@@ -413,6 +413,70 @@ struct Matrix2DMultiply {
} }
``` ```
### rotate<sup>(deprecated) </sup>
rotate(rx?: number, ry?: number): Matrix2D
Performs a rotation operation on this matrix.
Since API version 9, this API is supported in ArkTS widgets. This API is a null API.
This API is deprecated since API version 10. You are advised to use [rotate](#rotate10) instead.
**Parameters**
| Parameter| Type | Mandatory| Default Value| Description |
| ---- | ------ | ---- | ------ | -------------------------------- |
| rx | number | No | 0 | Horizontal coordinate (in vp) of the rotation point.|
| ry | number | No | 0 | Vertical coordinate (in vp) of the rotation point.|
**Return value**
| Type | Description |
| --------------------- | -------------------- |
| [Matrix2D](#matrix2d) | Matrix of the rotation result.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct Matrix2DRotate {
@State message: string = 'Matrix2D Rotate'
printMatrix(title, matrix) {
console.log(title)
console.log("Matrix [scaleX = " + matrix.scaleX + ", scaleY = " + matrix.scaleY +
", rotateX = " + matrix.rotateX + ", rotateY = " + matrix.rotateY +
", translateX = " + matrix.translateX + ", translateY = " + matrix.translateY + "]")
}
build() {
Row() {
Column() {
Text(this.message)
.fontSize(20)
.fontWeight(FontWeight.Bold)
Button("matrix rotate")
.onClick(() => {
var matrix : Matrix2D = new Matrix2D()
matrix.scaleX = 1
matrix.scaleY = 1
matrix.rotateX = 0
matrix.rotateY = 0
matrix.translateX = 0
matrix.translateY = 0
matrix.rotate(10, 10)
this.printMatrix(this.message, matrix)
})
}
.width('100%')
}
.height('100%')
}
}
```
### rotate<sup>10+</sup> ### rotate<sup>10+</sup>
rotate(degree: number, rx?: number, ry?: number): Matrix2D rotate(degree: number, rx?: number, ry?: number): Matrix2D
......
...@@ -26,20 +26,26 @@ GridItem() ...@@ -26,20 +26,26 @@ GridItem()
| columnStart | number | Start column number of the component.| | columnStart | number | Start column number of the component.|
| columnEnd | number | End column number of the component.| | columnEnd | number | End column number of the component.|
| forceRebuild<sup>(deprecated)</sup> | boolean | Whether to re-create the component when it is being built.<br>This API is deprecated since API version 9. Whether to re-create the component is automatically determined based on the component attributes and child component changes. No manual configuration is required.<br>Default value: **false**| | forceRebuild<sup>(deprecated)</sup> | boolean | Whether to re-create the component when it is being built.<br>This API is deprecated since API version 9. Whether to re-create the component is automatically determined based on the component attributes and child component changes. No manual configuration is required.<br>Default value: **false**|
| selectable<sup>8+</sup> | boolean | Whether the current grid item is selectable by the mouse.<br>**NOTE**<br>This attribute takes effect only when mouse frame selection is enabled for the parent **\<Grid>** container.<br>Default value: **true** | | selectable<sup>8+</sup> | boolean | Whether the grid item is selectable by the mouse.<br>**NOTE**<br>This attribute takes effect only when mouse frame selection is enabled for the parent **\<Grid>** container.<br>Default value: **true** |
| selected<sup>10+</sup> | boolean | Whether the grid item is selected. This attribute supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.<br>**NOTE**<br>This attribute must be used before the [style for the selected state](./ts-universal-attributes-polymorphic-style.md) is set. Otherwise, the style settings will not take effect.<br>Default value: **false**|
> **NOTE** > **NOTE**
> >
> Rules for setting **rowStart**, **rowEnd**, **columnStart**, and **columnEnd**: > Rules for setting **rowStart**, **rowEnd**, **columnStart**, and **columnEnd**:
> >
> - The valid value range of **rowStart** and **rowEnd** is 0 to the total number of rows minus 1. The valid value range of **columnStart** and **columnEnd** is 0 to the total number of columns minus 1. > The valid value range of **rowStart** and **rowEnd** is 0 to the total number of rows minus 1. The valid value range of **columnStart** and **columnEnd** is 0 to the total number of columns minus 1.
> >
> - Settings outside of the valid ranges do not take effect. > Settings outside of the valid ranges do not take effect.
> >
> - In the grid that has both **columnTemplate** and **rowTemplate** set, a grid item takes up the specified number of rows (rowEnd – rowStart + 1) or columns (columnEnd – columnStart + 1), depending on whether **rowStart**/**rowEnd** or **columnStart**/**columnEnd** is set. > In the grid that has both **columnTemplate** and **rowTemplate** set, grid items that have **rowStart**/**rowEnd** or **columnStart**/**columnEnd** set are laid out in a row-by-row then column-by-column manner.
>- In the grid that has only **columnTemplate** set, a grid item takes up the specified number of columns. >
> - In the grid that has only **rowTemplate** set, a grid item takes up the specified number of rows. > In the grid that has only **columnTemplate** set, grid items that have **columnStart**/**columnEnd** set are laid out in the specific columns. If there are already grid items in those columns, the grid items will be laid out in another row.
>- In the grid that has neither **columnTemplate** nor **rowTemplate** set, the row and column number attributes do not work. >
> In the grid that has only **rowTemplate** set, grid items that have **rowStart**/**rowEnd** set are laid out in the specific rows. If there are already grid items in those rows, the grid items will be laid out in another column.
>
> In the grid that has only **columnTemplate** set, grid items whose row or column number settings are invalid are laid out in a row-by-row then column-by-column manner.
>
> In the grid that has neither **columnTemplate** nor **rowTemplate** set, the row and column number attributes do not work.
## Events ## Events
......
...@@ -42,7 +42,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -42,7 +42,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| sticky<sup>(deprecated)</sup> | [Sticky](#stickydeprecated) | Sticky effect of the list item.<br>Default value: **Sticky.None**<br>This API is deprecated since API version 9. You are advised to use **sticky** of the [\<List>](ts-container-list.md#attributes) component.| | sticky<sup>(deprecated)</sup> | [Sticky](#stickydeprecated) | Sticky effect of the list item.<br>Default value: **Sticky.None**<br>This API is deprecated since API version 9. You are advised to use **sticky** of the [\<List>](ts-container-list.md#attributes) component.|
| editable<sup>(deprecated)</sup> | boolean \| [EditMode](#editmodedeprecated) | Whether to enter editing mode, where the list item can be deleted or moved.<br>This API is deprecated since API version 9.<br>Default value: **false**| | editable<sup>(deprecated)</sup> | boolean \| [EditMode](#editmodedeprecated) | Whether to enter editing mode, where the list item can be deleted or moved.<br>This API is deprecated since API version 9.<br>Default value: **false**|
| selectable<sup>8+</sup> | boolean | Whether the current list item is selectable by mouse drag.<br>**NOTE**<br>This attribute takes effect only when mouse frame selection is enabled for the parent **\<List>** container.<br>Default value: **true**| | selectable<sup>8+</sup> | boolean | Whether the current list item is selectable by mouse drag.<br>**NOTE**<br>This attribute takes effect only when mouse frame selection is enabled for the parent **\<List>** container.<br>Default value: **true**|
| swipeAction<sup>9+</sup> | {<br>start?: CustomBuilder \| [SwipeActionItem](#swipeactionitem10),<br>end?:CustomBuilder \| [SwipeActionItem](#swipeactionitem10),<br>edgeEffect?: [SwipeEdgeEffect](#swipeedgeeffect9),<br>} | Swipe action displayed when the list item is swiped out from the screen edge.<br>- **start**: swipe action displayed on the left of the list item when the item is swiped right (in vertical list layout) or above the list item when the item is swiped down (in horizontal list layout).<br>- **end**: swipe action displayed on the right of the list item when the item is swiped left (in vertical list layout) or below the list item when the item is swiped up (in horizontal list layout).<br>- **edgeEffect**: scroll effect.<br>**NOTE**<br>- The top level of the **@builder** function corresponding to **start** and **end** must be a single component and cannot be an **if/else**, **ForEach**, or **LazyForEach** statement.<br> - The swipe gesture works only in the list item area. If a swipe causes a child component to extend beyond the list item area, the portion outside the area does not respond to the swipe. In light of this, avoid setting **swipeAction** to a component too wide in a multi-column list. | | selected<sup>10+</sup> | boolean | Whether the list item is selected. This attribute supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.<br>**NOTE**<br>This attribute must be used before the [style for the selected state](./ts-universal-attributes-polymorphic-style.md) is set. Otherwise, the style settings will not take effect.<br>Default value: **false**|
| swipeAction<sup>9+</sup> | {<br>start?: CustomBuilder \| [SwipeActionItem](#swipeactionitem10),<br>end?:CustomBuilder \| [SwipeActionItem](#swipeactionitem10),<br>edgeEffect?: [SwipeEdgeEffect](#swipeedgeeffect9),<br>} | Swipe action displayed when the list item is swiped out from the screen edge.<br>- **start**: swipe action displayed on the left of the list item when the item is swiped right (in vertical list layout) or above the list item when the item is swiped down (in horizontal list layout).<br>- **end**: swipe action displayed on the right of the list item when the item is swiped left (in vertical list layout) or below the list item when the item is swiped up (in horizontal list layout).<br>- **edgeEffect**: scroll effect.<br>**NOTE**<br>- The top level of the **@builder** function corresponding to **start** and **end** must be a single component and cannot be an **if/else**, **ForEach**, or **LazyForEach** statement.<br> - The swipe gesture works only in the list item area. If a swipe causes a child component to extend beyond the list item area, the portion outside the area does not respond to the swipe. In light of this, avoid setting **swipeAction** to a component too wide in a multi-column list.|
## Sticky<sup>(deprecated)</sup> ## Sticky<sup>(deprecated)</sup>
This API is deprecated since API version 9. You are advised to use [stickyStyle](ts-container-list.md#stickystyle9) of the **\<List>** component. This API is deprecated since API version 9. You are advised to use [stickyStyle](ts-container-list.md#stickystyle9) of the **\<List>** component.
......
...@@ -34,7 +34,7 @@ SideBarContainer( type?: SideBarContainerType ) ...@@ -34,7 +34,7 @@ SideBarContainer( type?: SideBarContainerType )
| -------- | -------- | | -------- | -------- |
| Embed | The sidebar is embedded in the component and displayed side by side with the content area.| | Embed | The sidebar is embedded in the component and displayed side by side with the content area.|
| Overlay | The sidebar is displayed overlaid on the content area.| | Overlay | The sidebar is displayed overlaid on the content area.|
| AUTO | The sidebar is displayed in Embed mode when the component size is greater than or equal to the sum of **minSideBarWidth** and **minContentWidth**<br>and in Overlay mode otherwise.| | AUTO | The sidebar is displayed in Embed mode when the component size is greater than or equal to the sum of **minSideBarWidth** and **minContentWidth**<br>and in Overlay mode otherwise.<br>If **minSideBarWidth** or **minContentWidth** is not set, the default value will be used for calculation. If the calculation result is less than 600 vp, 600 vp will be used as the breakpoint value for mode switching.|
## Attributes ## Attributes
...@@ -45,22 +45,22 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -45,22 +45,22 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| showSideBar | boolean | Whether to display the sidebar.<br>Default value: **true**<br>Since API version 10, this attribute supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.| | showSideBar | boolean | Whether to display the sidebar.<br>Default value: **true**<br>Since API version 10, this attribute supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables.|
| controlButton | [ButtonStyle](#buttonstyle) | Attributes of the sidebar control button.| | controlButton | [ButtonStyle](#buttonstyle) | Attributes of the sidebar control button.|
| showControlButton | boolean | Whether to display the sidebar control button.<br>Default value: **true**| | showControlButton | boolean | Whether to display the sidebar control button.<br>Default value: **true**|
| sideBarWidth | number \| [Length](ts-types.md#length)<sup>9+</sup> | Width of the sidebar.<br>Default value: **200**<br>Unit: vp<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>The value must comply with the width constraints. If it is not within the valid range, the value closest to the set one is used.<br>The width of the sidebar, whether it is specified or kept at the default, takes precedence over that of the sidebar child components.| | sideBarWidth | number \| [Length](ts-types.md#length)<sup>9+</sup> | Width of the sidebar.<br>Default value: **240vp**<br>Unit: vp<br>**NOTE**<br>In API version 9 and earlier versions, the default value is **200vp**. In API version 10, the default value is **240vp**.<br>A value less than 0 evaluates to the default value.<br>The value must comply with the width constraints. If it is not within the valid range, the value closest to the set one is used.<br>The width of the sidebar, whether it is specified or kept at the default, takes precedence over that of the sidebar child components.|
| minSideBarWidth | number \| [Length](ts-types.md#length)<sup>9+</sup> | Minimum width of the sidebar.<br>Default value: **200**, in vp<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used.<br>When set, the minimum width of the sidebar takes precedence over that of the sidebar child components. If it is not set, however, the minimum width of the sidebar child component takes precedence.| | minSideBarWidth | number \| [Length](ts-types.md#length)<sup>9+</sup> | Minimum width of the sidebar.<br>Default value: **240vp**<br>Unit: vp<br>**NOTE**<br>In API version 9 and earlier versions, the default value is **200vp**. In API version 10, the default value is **240vp**.<br>A value less than 0 evaluates to the default value.<br>The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used.<br>When set, the minimum width of the sidebar takes precedence over that of the sidebar child components. If it is not set, however, the minimum width of the sidebar child component takes precedence.|
| maxSideBarWidth | number \| [Length](ts-types.md#length)<sup>9+</sup> | Maximum width of the sidebar.<br>Default value: **280**, in vp<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used.<br>When set, the maximum width of the sidebar takes precedence over that of the sidebar child components. If it is not set, however, the maximum width of the sidebar child component takes precedence.| | maxSideBarWidth | number \| [Length](ts-types.md#length)<sup>9+</sup> | Maximum width of the sidebar.<br>Default value: **280vp**<br>Unit: vp<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>The value cannot exceed the width of the sidebar container itself. Otherwise, the width of the sidebar container itself is used.<br>When set, the maximum width of the sidebar takes precedence over that of the sidebar child components. If it is not set, however, the maximum width of the sidebar child component takes precedence.|
| autoHide<sup>9+</sup> | boolean | Whether to automatically hide the sidebar when it is dragged to be smaller than the minimum width.<br>Default value: **true**<br>**NOTE**<br>The value is subject to the **minSideBarWidth** attribute method. If it is not set in **minSideBarWidth**, the default value is used.<br>Whether the sidebar should be hidden is determined when it is being dragged. When its width is less than the minimum width, the damping effect is required to trigger hiding (a distance out of range).| | autoHide<sup>9+</sup> | boolean | Whether to automatically hide the sidebar when it is dragged to be smaller than the minimum width.<br>Default value: **true**<br>**NOTE**<br>The value is subject to the **minSideBarWidth** attribute method. If it is not set in **minSideBarWidth**, the default value is used.<br>Whether the sidebar should be hidden is determined when it is being dragged. When its width is less than the minimum width, the damping effect is required to trigger hiding (a distance out of range).|
| sideBarPosition<sup>9+</sup> | [SideBarPosition](#sidebarposition9) | Position of the sidebar.<br>Default value: **SideBarPosition.Start**| | sideBarPosition<sup>9+</sup> | [SideBarPosition](#sidebarposition9) | Position of the sidebar.<br>Default value: **SideBarPosition.Start**|
| divider<sup>10+</sup> | [DividerStyle](#dividerstyle10) \| null | Divider style.<br>- **DividerStyle** (default): The divider is displayed.<br>- **null**: The divider is not displayed.| | divider<sup>10+</sup> | [DividerStyle](#dividerstyle10) \| null | Divider style.<br>- **DividerStyle** (default): The divider is displayed.<br>- **null**: The divider is not displayed.|
| minContentWidth<sup>10+</sup> | Dimension | Minimum width of the content area of the sidebar container.<br>Default value: **360**<br>Unit: vp| | minContentWidth<sup>10+</sup> | [Dimension](ts-types.md#dimension10) | Minimum width of the content area of the sidebar container.<br>Default value: **360vp**<br>Unit: vp<br>**NOTE**<br>A value less than 0 evaluates to the default value.<br>In Embed mode, when the component size is increased, only the content area is enlarged; when the component size is decreased, the content area is shrunk until its width reaches the value defined by **minContentWidth**, and then the sidebar is shrunk until its width reaches the value defined by **minSideBarWidth**; if the component size is further decreased, while respecting the minimum width of the sidebar, the content area is further shrunk until it is 0 vp large.<br>minContentWidth takes precedence over maxSideBarWidth and sideBarWidth of the sidebar. If minContentWidth is not set, the priority of the default value is lower than that of minSideBarWidth and maxSideBarWidth.|
## ButtonStyle ## ButtonStyle
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| left | number | No| Spacing between the sidebar control button and the left of the container.<br>Default value: **16**<br>Unit: vp| | left | number | No| Spacing between the sidebar control button and the left of the container.<br>Default value: **16vp**<br>Unit: vp|
| top | number | No| Spacing between the sidebar control button and the top of the container.<br>Default value: **48**<br>Unit: vp| | top | number | No| Spacing between the sidebar control button and the top of the container.<br>Default value: **48vp**<br>Unit: vp|
| width | number | No| Width of the sidebar control button.<br>Default value: **32**<br>Unit: vp| | width | number | No| Width of the sidebar control button.<br>Default value:<br>API version 9 and earlier versions: **32vp**<br>API version 10 and later versions: **24vp**<br>Unit: vp|
| height | number | No| Height of the sidebar control button.<br>Default value: **32**<br>Unit: vp| | height | number | No| Height of the sidebar control button.<br>Default value:<br>API version 9 and earlier versions: **32vp**<br>API version 10 and later versions: **24vp**<br>Unit: vp|
| icons | {<br>shown: string \| PixelMap \| [Resource](ts-types.md) ,<br>hidden: string \| PixelMap \| [Resource](ts-types.md) ,<br>switching?: string \| PixelMap \| [Resource](ts-types.md) <br>} | No| Icons of the sidebar control button.<br> </p> - **shown**: icon of the control button when the sidebar is shown.<br>**NOTE**<br>When an error occurs during resource obtaining, the default icon is used.<br>- **hidden**: icon of the control button when the sidebar is hidden.<br>- **switching**: icon of the control button when the sidebar is switching between the shown and hidden states.| | icons | {<br>shown: string \| PixelMap \| [Resource](ts-types.md) ,<br>hidden: string \| PixelMap \| [Resource](ts-types.md) ,<br>switching?: string \| PixelMap \| [Resource](ts-types.md) <br>} | No| Icons of the sidebar control button.<br> </p> - **shown**: icon of the control button when the sidebar is shown.<br>**NOTE**<br>When an error occurs during resource obtaining, the default icon is used.<br>- **hidden**: icon of the control button when the sidebar is hidden.<br>- **switching**: icon of the control button when the sidebar is switching between the shown and hidden states.|
## SideBarPosition<sup>9+</sup> ## SideBarPosition<sup>9+</sup>
...@@ -74,21 +74,19 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -74,21 +74,19 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ----------- | ------------- | ---- | ---------------------------------------- | | ----------- | ------------- | ---- | ---------------------------------------- |
| strokeWidth | [Length](ts-types.md#length) | Yes | Stroke width of the divider.<br>Default value: **1**<br>Unit: vp| | strokeWidth | [Length](ts-types.md#length) | Yes | Stroke width of the divider.<br>Default value: **1vp**<br>Unit: vp|
| color | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the divider.<br>Default value: **#000000, 3%** | | color | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the divider.<br>Default value: **#000000, 3%** |
| startMargin | [Length](ts-types.md#length) | No | Distance between the divider and the top of the sidebar.<br>Default value: **0**| | startMargin | [Length](ts-types.md#length) | No | Distance between the divider and the top of the sidebar.<br>Default value: **0**|
| endMargin | [Length](ts-types.md#length) | No | Distance between the divider and the bottom of the sidebar.<br>Default value: **0**| | endMargin | [Length](ts-types.md#length) | No | Distance between the divider and the bottom of the sidebar.<br>Default value: **0**|
> **NOTE** > **NOTE**
> >
> When the universal attributes [width and height](ts-universal-attributes-size.md) are set for the sidebar, the **width** setting takes effect only when the sidebar container width is not set, and the **height** settings does not take effect. > The settings of the [universal size attributes](ts-universal-attributes-size.md) **width** and **height** do not take effect for the sidebar child component.
> The settings of the universal attributes **width** and **height** do not take effect for the sidebar content area. By default, sidebar content area takes up the remaining space of the sidebar container. > The settings do not take effect for the sidebar content area either. By default, the sidebar content area takes up the remaining space of the sidebar container.
> >
> If the attribute method is not used, the sidebar is displayed depending on the size. > If the attribute method is not used, the sidebar is displayed depending on the size.
> >
> - If the size is less than 520 vp, the sidebar is not displayed by default. > - If the size is less than 520 vp, the sidebar is not displayed by default.
> - If the size is greater than or equal to 520 vp, the sidebar is displayed by default. > - If the size is greater than or equal to 520 vp, the sidebar is displayed by default.
> -
> -
## Events ## Events
......
...@@ -30,7 +30,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -30,7 +30,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Description | | Name | Type | Description |
| ------------ | ------------------------------------------- | ------------------------------------------------------------ | | ------------ | ------------------------------------------- | ------------------------------------------------------------ |
| alignContent | [Alignment](ts-appendix-enums.md#alignment) | Alignment of child components in the container.<br>Default value: **Alignment.Center**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>When this attribute and the universal attribute [align](ts-universal-attributes-location.md) are both set, only the **align** setting takes effect.| | alignContent | [Alignment](ts-appendix-enums.md#alignment) | Alignment of child components in the container.<br>Default value: **Alignment.Center**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>When both this attribute and the universal attribute [align](ts-universal-attributes-location.md) are set, whichever is set last takes effect.|
## Example ## Example
......
...@@ -22,8 +22,8 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -22,8 +22,8 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| width | string \| number | No| Width of the circle.<br>Default value: **0**| | width | string \| number | No| Width of the circle.<br>Default value: **0**<br>**NOTE**<br>An invalid value is handled as the default value.|
| height | string \| number | No| Height of the circle.<br>Default value: **0**| | height | string \| number | No| Height of the circle.<br>Default value: **0**<br>**NOTE**<br>An invalid value is handled as the default value.|
## Attributes ## Attributes
...@@ -31,19 +31,20 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -31,19 +31,20 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| fill | [ResourceColor](ts-types.md) | Color of the fill area.<br>Default value: **Color.Black**<br>Since API version 9, this API is supported in ArkTS widgets.| | fill | [ResourceColor](ts-types.md) | Color of the fill area.<br>Default value: **Color.Black**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| Opacity of the fill area.<br>Default value: **1**<br>Since API version 9, this API is supported in ArkTS widgets.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| Opacity of the fill area.<br>Default value: **1**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| stroke | [ResourceColor](ts-types.md) | Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | stroke | [ResourceColor](ts-types.md) | Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If the value is invalid, no stroke will be drawn.|
| strokeDashArray | Array&lt;Length&gt; | Stroke dashes.<br>Default value: **[]**<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashArray | Array&lt;Length&gt; | Stroke dashes.<br>Default value: **[]**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeDashOffset | number \| string | Offset of the start point for drawing the stroke.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashOffset | number \| string | Offset of the start point for drawing the stroke.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | Cap style of the stroke.<br>Default value: **LineCapStyle.Butt**<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | Cap style of the stroke.<br>Default value: **LineCapStyle.Butt**<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | Join style of the stroke.<br>Default value: **LineJoinStyle.Miter**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not work for the **\<circle>** component, which does not have corners.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | Join style of the stroke.<br>Default value: **LineJoinStyle.Miter**<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeMiterLimit | number \| string | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join.<br>Default value: **4**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not take effect for the **\<Circle>** component, because it does not have a miter join.| | strokeMiterLimit | number \| string | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join.<br>Default value: **4**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not take effect for the **\<Circle>** component, because it does not have a miter join.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| Stroke opacity.<br>Default value: **1**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| Stroke opacity.<br>Default value: **1**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value range is [0.0, 1.0]. A value less than 0.0 evaluates to the value **0.0**. A value greater than 1.0 evaluates to the value **1.0**. Any other value evaluates to the value **1.0**.|
| strokeWidth | Length | Stroke width.<br>Default value: **1**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.| | strokeWidth | Length | Stroke width.<br>Default value: **1**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.<br>An invalid value is handled as the default value.|
| antiAlias | boolean | Whether anti-aliasing is enabled.<br>Default value: **true**<br>Since API version 9, this API is supported in ArkTS widgets.| | antiAlias | boolean | Whether anti-aliasing is enabled.<br>Default value: **true**<br>Since API version 9, this API is supported in ArkTS widgets.|
## Example ## Example
```ts ```ts
......
...@@ -22,8 +22,10 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -22,8 +22,10 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| width | string \| number | No| Width.<br>Default value: **0**| | width | string \| number | No| Width.<br>Default value: **0**<br>**NOTE**<br>An invalid value is handled as the default value.|
| height | string \| number | No| Height.<br>Default value: **0**| | height | string \| number | No| Height.<br>Default value: **0**<br>**NOTE**<br>An invalid value is handled as the default value.|
## Attributes ## Attributes
...@@ -31,19 +33,20 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -31,19 +33,20 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Default Value| Description| | Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.| | fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| stroke | [ResourceColor](ts-types.md) | - |Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | stroke | [ResourceColor](ts-types.md) | - |Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If the value is invalid, no stroke will be drawn.|
| strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not work for the **\<ellipse>** component, which does not have corners.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not work for the **\<ellipse>** component, which does not have corners.|
| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not take effect for the **\<Ellipse>** component, because it does not have a miter join.| | strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not take effect for the **\<Ellipse>** component, because it does not have a miter join.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value range is [0.0, 1.0]. A value less than 0.0 evaluates to the value **0.0**. A value greater than 1.0 evaluates to the value **1.0**. Any other value evaluates to the value **1.0**.|
| strokeWidth | Length | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.| | strokeWidth | Length | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.<br>An invalid value is handled as the default value.|
| antiAlias | boolean | true | Whether anti-aliasing is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.|
## Example ## Example
```ts ```ts
......
...@@ -21,8 +21,9 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -21,8 +21,9 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | string \| number | No| 0 | Width.| | width | string \| number | No| 0 | Width.<br>**NOTE**<br>An invalid value is handled as the default value.|
| height | string \| number | No| 0 | Height.| | height | string \| number | No| 0 | Height.<br>**NOTE**<br>An invalid value is handled as the default value.|
## Attributes ## Attributes
...@@ -31,20 +32,22 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -31,20 +32,22 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Default Value| Description| | Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| startPoint | Array&lt;Length&gt; | [0, 0] | Coordinates (relative coordinates) of the start point of the line, in vp.<br>Since API version 9, this API is supported in ArkTS widgets.| | startPoint | Array&lt;Length&gt; | [0, 0] | Coordinates (relative coordinates) of the start point of the line, in vp.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| endPoint | Array&lt;Length&gt; | [0, 0] | Coordinates (relative coordinates) of the end point of the line, in vp.<br>Since API version 9, this API is supported in ArkTS widgets.| | endPoint | Array&lt;Length&gt; | [0, 0] | Coordinates (relative coordinates) of the end point of the line, in vp.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not take effect because the **\<Line>** component cannot be used to draw a closed shape.| | fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not take effect because the **\<Line>** component cannot be used to draw a closed shape.|
| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not take effect because the **\<Line>** component cannot be used to draw a closed shape.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not take effect because the **\<Line>** component cannot be used to draw a closed shape.|
| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If the value is invalid, no stroke will be drawn.|
| strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not work for the **\<Line>** component, which does not have corners.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not work for the **\<Line>** component, which does not have corners.|
| strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not take effect because the **\<Line>** component cannot be used to draw a shape with a sharp angle.| | strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute does not take effect because the **\<Line>** component cannot be used to draw a shape with a sharp angle.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value range is [0.0, 1.0]. A value less than 0.0 evaluates to the value **0.0**. A value greater than 1.0 evaluates to the value **1.0**. Any other value evaluates to the value **1.0**.|
| strokeWidth | Length | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.| | strokeWidth | Length | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.<br>An invalid value is handled as the default value.|
| antiAlias | boolean | true | Whether anti-aliasing is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.|
## Example ## Example
### Example 1 ### Example 1
......
...@@ -20,10 +20,12 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -20,10 +20,12 @@ Since API version 9, this API is supported in ArkTS widgets.
**Parameters** **Parameters**
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------------- | ---- | ----------------------------------- | | -------- | ---------------- | ---- | ------------------------------------------------------------ |
| width | number \| string | No | Width of the rectangle where the path is located.<br>Default value: **0** | | width | number \| string | No | Width of the rectangle where the path is located.<br>Default value: **0**<br>**NOTE**<br>An invalid value is handled as the default value.|
| height | number \| string | No | Height of the rectangle where the path is located.<br>Default value: **0** | | height | number \| string | No | Height of the rectangle where the path is located.<br>Default value: **0**<br>**NOTE**<br>An invalid value is handled as the default value.|
| commands | string | No | Command for drawing the path.<br>Default value: **''**| | commands | string | No | Command for drawing the path.<br>Default value: **''**<br>**NOTE**<br>An invalid value is handled as the default value.|
## Attributes ## Attributes
...@@ -31,17 +33,17 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -31,17 +33,17 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | ----------------------------------- | ---- | ---------------------------------------- | | -------- | ----------------------------------- | ---- | ---------------------------------------- |
| commands | string | '' | Command for drawing the path. The unit is px. For details about how to convert pixel units, see [Pixel Units](ts-pixel-units.md).<br>Since API version 9, this API is supported in ArkTS widgets.| | commands | string | '' | Command for drawing the path. The unit is px. For details about how to convert pixel units, see [Pixel Units](ts-pixel-units.md).<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.| | fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| stroke | [ResourceColor](ts-types.md) | - |Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | stroke | [ResourceColor](ts-types.md) | - |Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If the value is invalid, no stroke will be drawn.|
| strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>**NOTE**<br>This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute works only when **strokeLineJoin** is set to **LineJoinStyle.Miter**.<br>The value must be greater than or equal to 1.0. If the value is in the [0, 1) range, the value **1.0** will be used. In other cases, the default value will be used.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the stroke.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value range is [0.0, 1.0]. A value less than 0.0 evaluates to the value **0.0**. A value greater than 1.0 evaluates to the value **1.0**. Any other value evaluates to the value **1.0**.|
| strokeWidth | Length | 1 | Width of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.| | strokeWidth | Length | 1 | Width of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.<br>An invalid value is handled as the default value.|
| antiAlias | boolean | true | Whether anti-aliasing is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.|
The supported commands are as follows: The supported commands are as follows:
......
...@@ -22,8 +22,9 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -22,8 +22,9 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | string \| number | No| 0 | Width.| | width | string \| number | No| 0 | Width.<br>**NOTE**<br>An invalid value is handled as the default value.|
| height | string \| number | No| 0 | Height.| | height | string \| number | No| 0 | Height.<br>**NOTE**<br>An invalid value is handled as the default value.|
## Attributes ## Attributes
...@@ -32,17 +33,17 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -32,17 +33,17 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Default Value| Description| | Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| points | Array&lt;Point&gt; | [] | Vertex coordinates of the polygon.<br>Since API version 9, this API is supported in ArkTS widgets.| | points | Array&lt;Point&gt; | [] | Vertex coordinates of the polygon.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.| | fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If the value is invalid, no stroke will be drawn.|
| strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>**NOTE**<br>This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>**NOTE**<br>This attribute works only when **strokeLineJoin** is set to **LineJoinStyle.Miter**.<br>The value must be greater than or equal to 1.0. If the value is in the [0, 1) range, the value **1.0** will be used. In other cases, the default value will be used.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>**NOTE**<br>The value range is [0.0, 1.0]. A value less than 0.0 evaluates to the value **0.0**. A value greater than 1.0 evaluates to the value **1.0**. Any other value evaluates to the value **1.0**.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeWidth | Length | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.| | strokeWidth | Length | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.<br>An invalid value is handled as the default value.|
| antiAlias | boolean | true | Whether anti-aliasing is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.|
## Point ## Point
......
...@@ -22,8 +22,9 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -22,8 +22,9 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | string \| number | No| 0 | Width.| | width | string \| number | No| 0 | Width.<br>**NOTE**<br>An invalid value is handled as the default value.|
| height | string \| number | No| 0 | Height.| | height | string \| number | No| 0 | Height.<br>**NOTE**<br>An invalid value is handled as the default value.|
## Attributes ## Attributes
...@@ -32,18 +33,20 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -32,18 +33,20 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Default Value| Description| | Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| points | Array&lt;Point&gt; | [] | List of coordinates that the polyline passes through.<br>Since API version 9, this API is supported in ArkTS widgets.| | points | Array&lt;Point&gt; | [] | List of coordinates that the polyline passes through.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.| | fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If the value is invalid, no stroke will be drawn.|
| strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>**NOTE**<br>This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute works only when **strokeLineJoin** is set to **LineJoinStyle.Miter**.<br>The value must be greater than or equal to 1.0. If the value is in the [0, 1) range, the value **1.0** will be used. In other cases, the default value will be used.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value range is [0.0, 1.0]. A value less than 0.0 evaluates to the value **0.0**. A value greater than 1.0 evaluates to the value **1.0**. Any other value evaluates to the value **1.0**.|
| strokeWidth | Length | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.| | strokeWidth | Length | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.<br>An invalid value is handled as the default value.|
| antiAlias | boolean | true | Whether anti-aliasing is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
## Point ## Point
......
...@@ -23,12 +23,11 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -23,12 +23,11 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Default Value| Description| | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| width | string \| number | No| 0 | Width.| | width | string \| number | No| 0 | Width.<br>**NOTE**<br>An invalid value is handled as the default value.|
| height | string \| number | No| 0 | Height.| | height | string \| number | No| 0 | Height.<br>**NOTE**<br>An invalid value is handled as the default value.|
| radius | string \| number \| Array&lt;string \| number&gt; | No| 0 | Radius of the rounded corner. You can set separate radiuses for four rounded corners.| | radius | string \| number \| Array&lt;string \| number&gt; | No| 0 | Radius of the rounded corner. You can set separate radiuses for four rounded corners.<br>This attribute works in a similar manner as **radiusWidth**/**radiusHeight**. When they are used together, it takes precedence over **radiusWidth**/**radiusHeight**.<br>**NOTE**<br>An invalid value is handled as the default value.|
| radiusWidth | string \| number | No| 0 | Width of the rounded corner.| | radiusWidth | string \| number | No| 0 | Width of the rounded corner.<br>**NOTE**<br>An invalid value is handled as the default value.|
| radiusHeight | string \| number | No| 0 | Height of the rounded corner.| | radiusHeight | string \| number | No| 0 | Height of the rounded corner.<br>**NOTE**<br>An invalid value is handled as the default value.|
## Attributes ## Attributes
...@@ -36,21 +35,20 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -36,21 +35,20 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Default Value| Description| | Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| radiusWidth | string \| number | 0 | Width of the rounded corner. The width and height are the same when only the width is set.<br>Since API version 9, this API is supported in ArkTS widgets.| | radiusWidth | string \| number | 0 | Width of the rounded corner. The width and height are the same when only the width is set.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| radiusHeight | string \| number | 0 | Height of the rounded corner. The width and height are the same only when the height is set.<br>Since API version 9, this API is supported in ArkTS widgets.| | radiusHeight | string \| number | 0 | Height of the rounded corner. The width and height are the same only when the height is set.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| radius | string \| number \| Array&lt;string \| number&gt; | 0 | Radius of the rounded corner. You can set separate radiuses for four rounded corners.<br>Since API version 9, this API is supported in ArkTS widgets.| | radius | string \| number \| Array&lt;string \| number&gt; | 0 | Radius of the rounded corner. You can set separate radiuses for four rounded corners.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.| | fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If the value is invalid, no stroke will be drawn.|
| strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>**NOTE**<br>This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute works only when **strokeLineJoin** is set to **LineJoinStyle.Miter**.<br>The value must be greater than or equal to 1.0. If the value is in the [0, 1) range, the value **1.0** will be used. In other cases, the default value will be used.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value range is [0.0, 1.0]. A value less than 0.0 evaluates to the value **0.0**. A value greater than 1.0 evaluates to the value **1.0**. Any other value evaluates to the value **1.0**.|
| strokeWidth | Length | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.| | strokeWidth | Length | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value cannot be a percentage.<br>An invalid value is handled as the default value.|
| antiAlias | boolean | true | Whether anti-aliasing is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
## Example ## Example
......
...@@ -2,7 +2,6 @@ ...@@ -2,7 +2,6 @@
The **\<Shape>** component is the parent component of the drawing components. The attributes described in this topic are universal attributes supported by all the drawing components. The **\<Shape>** component is the parent component of the drawing components. The attributes described in this topic are universal attributes supported by all the drawing components.
1. Drawing components use **\<Shape>** as their parent to implement the effect similar to SVG. 1. Drawing components use **\<Shape>** as their parent to implement the effect similar to SVG.
2. The **\<Shape>** component is used independently to draw a specific shape. 2. The **\<Shape>** component is used independently to draw a specific shape.
...@@ -36,17 +35,17 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -36,17 +35,17 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Default Value| Description| | Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| viewPort | {<br>x?: number \| string,<br>y?: number \| string,<br>width?: number \| string,<br>height?: number \| string<br>} | { x:0, y:0, width:0, height:0 } | Viewport of the shape.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If of the string type, the value cannot be a percentage.| | viewPort | {<br>x?: number \| string,<br>y?: number \| string,<br>width?: number \| string,<br>height?: number \| string<br>} | { x:0, y:0, width:0, height:0 } | View port of the shape.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If of the string type, the value cannot be a percentage.<br>An invalid value is handled as the default value.|
| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.| | fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If the value is invalid, no stroke will be drawn.|
| strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>An invalid value is handled as the default value.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.<br>Since API version 9, this API is supported in ArkTS widgets.|
| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>**NOTE**<br>This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute works only when **strokeLineJoin** is set to **LineJoinStyle.Miter**. The value must be greater than or equal to 1.0. If the value is in the [0, 1) range, the value **1.0** will be used. In other cases, the default value will be used.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.<br>Since API version 9, this API is supported in ArkTS widgets.| | strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>The value range is [0.0, 1.0]. A value less than 0.0 evaluates to the value **0.0**. A value greater than 1.0 evaluates to the value **1.0**. Any other value evaluates to the value **1.0**.|
| strokeWidth | number \| string | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If of the string type, the value cannot be a percentage.| | strokeWidth | number \| string | 1 | Stroke width.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If of the string type, the value cannot be a percentage.<br>An invalid value is handled as the default value.|
| antiAlias | boolean | true | Whether anti-aliasing is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.| | antiAlias | boolean | true | Whether anti-aliasing is enabled.<br>Since API version 9, this API is supported in ArkTS widgets.|
| mesh<sup>8+</sup> | Array&lt;number&gt;,number,number | [],0,0 | Mesh effect. The first parameter is an array of lengths (column + 1) * (row + 1) * 2, which records the position of each vertex of the distorted bitmap. The second parameter is the number of columns in the mesh matrix. The third parameter is the number of rows in the mesh matrix.<br>Since API version 9, this API is supported in ArkTS widgets.| | mesh<sup>8+</sup> | Array&lt;number&gt;,number,number | [],0,0 | Mesh effect. The first parameter is an array of lengths (column + 1) * (row + 1) * 2, which records the position of each vertex of the distorted bitmap. The second parameter is the number of columns in the mesh matrix. The third parameter is the number of rows in the mesh matrix.<br>Since API version 9, this API is supported in ArkTS widgets.|
......
...@@ -5,6 +5,10 @@ You can create explicit animation with your custom settings. ...@@ -5,6 +5,10 @@ You can create explicit animation with your custom settings.
> **NOTE** > **NOTE**
> >
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>
> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext).
>
> Since API version 10, you can use the [animateTo](../apis/js-apis-arkui-UIContext.md#animateto) API in [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext) to obtain the UI context.
animateTo(value: AnimateParam, event: () => void): void animateTo(value: AnimateParam, event: () => void): void
...@@ -19,14 +23,18 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -19,14 +23,18 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| duration | number | Animation duration, in ms.<br>Default value: **1000**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>- The maximum animation duration on an ArkTS widget is 1000 ms. If the set value exceeds the limit, the value **1000** will be used.| | duration | number | Animation duration, in ms.<br>Default value: **1000**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>- The maximum animation duration on an ArkTS widget is 1000 ms. If the set value exceeds the limit, the value **1000** will be used.<br>- A value less than 0 evaluates to the value **0**.<br>- Floating-point values will be rounded down to integers. For example, if the value set is 1.2, **1** will be used.|
| tempo | number | Animation playback speed. A larger value indicates faster animation playback, and a smaller value indicates slower animation playback. The value **0** means that there is no animation.<br>Default value: **1.0**| | tempo | number | Animation playback speed. A larger value indicates faster animation playback, and a smaller value indicates slower animation playback. The value **0** means that there is no animation.<br>Default value: **1.0**<br>**NOTE**<br>A value less than 0 evaluates to the value **1**.|
| curve | [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve) \| string | Animation curve.<br>Default value: **Curve.Linear**<br>Since API version 9, this API is supported in ArkTS widgets.| | curve | [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve) \| string | Animation curve.<br>Default value: **Curve.Linear**<br>Since API version 9, this API is supported in ArkTS widgets.|
| delay | number | Delay of animation playback, in ms. By default, the playback is not delayed.<br>Default value: **0**| | delay | number | Delay of animation playback, in ms. By default, the playback is not delayed.<br>Default value: **0**<br>**NOTE**<br>- A value less than 0 evaluates to the value **0**.<br>- Floating-point values will be rounded down to integers. For example, if the value set is 1.2, **1** will be used.|
| iterations | number | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.<br>Default value: **1**| | iterations | number | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.<br>Default value: **1**|
| playMode | [PlayMode](ts-appendix-enums.md#playmode) | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.<br>Default value: **PlayMode.Normal**<br>Since API version 9, this API is supported in ArkTS widgets.| | playMode | [PlayMode](ts-appendix-enums.md#playmode) | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.<br>Default value: **PlayMode.Normal**<br>Since API version 9, this API is supported in ArkTS widgets.<br>For details about the restrictions, see **Notes about PlayMode**.|
| onFinish | () =&gt; void | Callback invoked when the animation playback is complete.<br>Since API version 9, this API is supported in ArkTS widgets.| | onFinish | () =&gt; void | Callback invoked when the animation playback is complete.<br>Since API version 9, this API is supported in ArkTS widgets.|
> **Notes about PlayMode**:
> - **PlayMode.Normal** and **PlayMode.Alternate** are recommended. Under these settings, the first round of the animation is played forwards. If **PlayMode.Reverse** or **PlayMode.AlternateReverse** is used, the first round of the animation is played backwards. In this case, the animation jumps to the end state and then starts from there.
> - When using **PlayMode.Alternate** or **PlayMode.AlternateReverse**, make sure the final state of the animation is the same as the value of the state variable. In other words, make sure the last round of the animation is played forwards. When **PlayMode.Alternate** is used, **iterations** must be set to an odd number. When **PlayMode.AlternateReverse** is used, **iterations** must be set to an even number.
> - **PlayMode.Reverse** is not recommended. Under this setting, the animation jumps to the end state at the beginning, and its final state will be different from the value of the state variable.
## Example ## Example
......
...@@ -65,6 +65,9 @@ The component binds gesture objects of different **GestureType**s through gestur ...@@ -65,6 +65,9 @@ The component binds gesture objects of different **GestureType**s through gestur
| tiltX<sup>9+</sup> | number | Angle between the projection of the stylus on the device plane and the x-axis.| | tiltX<sup>9+</sup> | number | Angle between the projection of the stylus on the device plane and the x-axis.|
| tiltY<sup>9+</sup> | number | Angle between the projection of the stylus on the device plane and the y-axis.| | tiltY<sup>9+</sup> | number | Angle between the projection of the stylus on the device plane and the y-axis.|
| sourceTool<sup>9+</sup> | [SourceTool](#sourcetool) | Event input source.| | sourceTool<sup>9+</sup> | [SourceTool](#sourcetool) | Event input source.|
| velocityX<sup>10+</sup> | number | Velocity along the x-axis. This parameter is used in [PanGesture](ts-basic-gestures-pangesture.md). The origin of the coordinate axis is the upper left corner of the screen. The velocity is positive if the movement is from left to right, and it is negative if the movement is from right to left.|
| velocityY<sup>10+</sup> | number | Velocity along the y-axis. This parameter is used in [PanGesture](ts-basic-gestures-pangesture.md). The origin of the coordinate axis is the upper left corner of the screen. The velocity is positive if the movement is from top to bottom, and it is negative if the movement is from bottom to top.|
| velocity<sup>10+</sup> | number | Velocity along the main axis. This parameter is used in [PanGesture](ts-basic-gestures-pangesture.md). The value is the arithmetic square root of the sum of squares of the velocity along the x- and y-axis.|
## SourceType ## SourceType
| Name| Description| | Name| Description|
......
...@@ -8,7 +8,7 @@ You can set the text content and response callback for an alert dialog box. ...@@ -8,7 +8,7 @@ You can set the text content and response callback for an alert dialog box.
> >
> The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext). > The functionality of this module depends on UI context. This means that the APIs of this module cannot be used where the UI context is unclear. For details, see [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext).
> >
> Since API version 10, you can use the[showAlertDialog](../apis/js-apis-arkui-UIContext.md#showalertdialog) API in [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext) to obtain the UI context. > Since API version 10, you can use the [showAlertDialog](../apis/js-apis-arkui-UIContext.md#showalertdialog) API in [UIContext](../apis/js-apis-arkui-UIContext.md#uicontext) to obtain the UI context.
## Attributes ## Attributes
......
...@@ -12,23 +12,8 @@ You can configure the component transition animations through the **transition** ...@@ -12,23 +12,8 @@ You can configure the component transition animations through the **transition**
| Name| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| transition | TransitionOptions \| TransitionEffect<sup>10+</sup> | Transition effects when the component is inserted, displayed, deleted, or hidden.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>For details, see the description of **TransitionOptions** and **TransitionEffect**.| | transition | TransitionOptions<sup>(deprecated)</sup> \| TransitionEffect<sup>10+</sup> | Transition effects when the component is inserted, displayed, deleted, or hidden.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>For details, see the descriptions of **TransitionOptions** and **TransitionEffect**.|
## TransitionOptions
Defines the transition effect by setting parameters in the struct.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | [TransitionType](ts-appendix-enums.md#transitiontype) | No| Transition type.<br>Default value: **TransitionType.All**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If **type** is not specified, the default value **TransitionType.All** is used, which means that the transition effect works for both component addition and deletion.|
| 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>Value range: [0, 1]<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>A value less than 0 or greater than 1 evaluates to the value **1**.|
| 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.<br>Since API version 9, this API is supported in ArkTS widgets.|
| 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**: scale center point. The default values are both **"50%"**, indicating that the center point of the page.<br>- If the center point is (0, 0), it refers to the upper left corner of the component.<br>Since API version 9, this API is supported in ArkTS widgets.|
| 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**: X-component of the rotation vector.<br>- **y**: Y-component of the rotation vector.<br>- **z**: Z-component of the rotation vector.<br>- **centerX** and **centerY**: rotation center point. The default values are both **"50%"**, indicating that the center point of the page.<br>- If the center point is (0, 0), it refers to the upper left corner of the component.<br>Since API version 9, this API is supported in ArkTS widgets.|
> **NOTE**
>
> 1. When set to a value of the **TransitionOptions** type, the **transition** attribute must work with [animateTo](ts-explicit-animation.md). The animation duration, curve, and delay follow the settings in **animateTo**.
> 2. If the value of the **TransitionOptions** type has only **type** specified, the transition effect will take on the default opacity. For example, **{type: TransitionType.Insert}** produces the same effect as **{type: TransitionType.Insert, opacity: 0}**. If a specific style is specified, the transition effect will not take on the default opacity.
> 3. For details about the scale and rotate effects, see [Transformation](ts-universal-attributes-transformation.md).
## TransitionEffect<sup>10+</sup> ## TransitionEffect<sup>10+</sup>
Defines the transition effect by using the provided APIs, as listed below. Defines the transition effect by using the provided APIs, as listed below.
...@@ -37,7 +22,7 @@ Defines the transition effect by using the provided APIs, as listed below. ...@@ -37,7 +22,7 @@ Defines the transition effect by using the provided APIs, as listed below.
| opacity | number | Yes| Opacity of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>Value range: [0, 1]<br>**NOTE**<br>A value less than 0 or greater than 1 evaluates to the value **1**.| | opacity | number | Yes| Opacity of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>Value range: [0, 1]<br>**NOTE**<br>A value less than 0 or greater than 1 evaluates to the value **1**.|
| translate | {<br>x? : number \| string,<br>y? : number \| string,<br>z? : number \| string<br>} | Yes| 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.| | translate | {<br>x? : number \| string,<br>y? : number \| string,<br>z? : number \| string<br>} | Yes| 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>} | Yes| 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**: scale center point. The default values are both **"50%"**, indicating that the center point of the page.<br>- If the center point is (0, 0), it refers to the upper left corner of the component.| | scale | {<br>x? : number,<br>y? : number,<br>z? : number,<br>centerX? : number \| string,<br>centerY? : number \| string<br>} | Yes| 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**: scale center point. The default values are both **"50%"**, indicating that the center point of the page.<br>- If the center point is (0, 0), it refers to the upper left corner of the component.|
| rotate | {<br>x?: number,<br>y?: number,<br>z?: number,<br>angle: number \| string,<br>centerX?: number \| string,<br>centerY?: number \| string<br>} | Yes| 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**: Y-component of the rotation vector.<br>- **z**: Z-component of the rotation vector.<br>- **centerX** and **centerY**: rotation center point. The default values are both **"50%"**, indicating that the center point of the page.<br>- If the center point is (0, 0), it refers to the upper left corner of the component.| | rotate | {<br>x?: number,<br>y?: number,<br>z?: number,<br>angle: number \| string,<br>centerX?: number \| string,<br>centerY?: number \| string<br>} | Yes| Rotation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: X-component of the rotation vector.<br>- **y**: Y-component of the rotation vector.<br>- **z**: Z-component of the rotation vector.<br>- **centerX** and **centerY**: rotation center point. The default values are both **"50%"**, indicating that the center point of the page.<br>- If the center point is (0, 0), it refers to the upper left corner of the component.|
| move | [TransitionEdge](ts-appendix-enums.md#transitionedge10) | Yes| Slide-in and slide-out of the component from the screen edge during transition. It is essentially a translation effect, which is the value of the start point of insertion and the end point of deletion.| | move | [TransitionEdge](ts-appendix-enums.md#transitionedge10) | Yes| Slide-in and slide-out of the component from the screen edge during transition. It is essentially a translation effect, which is the value of the start point of insertion and the end point of deletion.|
| asymmetric | appear: TransitionEffect,<br>disappear: TransitionEffect<br>| Yes| Asymmetric transition effect.<br>The first parameter indicates the transition effect for appearance, and the second parameter indicates the transition effect for disappearance.<br>If the **asymmetric** function is not used for **TransitionEffect**, the transition effect takes effect for both appearance and disappearance of the component.| | asymmetric | appear: TransitionEffect,<br>disappear: TransitionEffect<br>| Yes| Asymmetric transition effect.<br>The first parameter indicates the transition effect for appearance, and the second parameter indicates the transition effect for disappearance.<br>If the **asymmetric** function is not used for **TransitionEffect**, the transition effect takes effect for both appearance and disappearance of the component.|
| combine | TransitionEffect | No| Combination of transition effects.| | combine | TransitionEffect | No| Combination of transition effects.|
...@@ -49,7 +34,7 @@ The static functions listed in the preceding table are used to create a **Transi ...@@ -49,7 +34,7 @@ The static functions listed in the preceding table are used to create a **Transi
| -------- | -------- | | -------- | -------- |
| IDENTITY | Disables the transition effect.| | IDENTITY | Disables the transition effect.|
| OPACITY | Applies a transition effect with the opacity of 0. It is equivalent to **TransitionEffect.opacity(0)**.| | OPACITY | Applies a transition effect with the opacity of 0. It is equivalent to **TransitionEffect.opacity(0)**.|
| SLIDE | Applies a transition effect of sliding in from the left when the component appears and sliding out from the right when the component disappears. It is equivalent to **TransitionEffect.asymmetric(TransitionEffect.START, TrasitionEffect.END)**.| | SLIDE | Applies a transition effect of sliding in from the left when the component appears and sliding out from the right when the component disappears. It is equivalent to **TransitionEffect.asymmetric(TransitionEffect.move(TransitionEdge.START), TransitionEffect.move(TransitionEdge.END))**.|
> **NOTE** > **NOTE**
> >
...@@ -57,47 +42,26 @@ The static functions listed in the preceding table are used to create a **Transi ...@@ -57,47 +42,26 @@ The static functions listed in the preceding table are used to create a **Transi
> 2. The animation settings take effect in the following sequence: animation settings specified in the current **TransitionEffect** > animation settings specified in the previous **TransitionEffect** > animation settings specified in **animateTo** that triggers the component to appear and disappear. > 2. The animation settings take effect in the following sequence: animation settings specified in the current **TransitionEffect** > animation settings specified in the previous **TransitionEffect** > animation settings specified in **animateTo** that triggers the component to appear and disappear.
> 3. If **animateTo** is not used and **TransitionEffect** does not have the **animation** parameter specified, the component will appear or disappear without any transition animation. > 3. If **animateTo** is not used and **TransitionEffect** does not have the **animation** parameter specified, the component will appear or disappear without any transition animation.
> 4. If the value of an attribute specified in **TransitionEffect** is the same as the default value, no transition animation is applied for the attribute. For example, with **TransitionEffect.opacity(1).animation({duration:1000})**, because the default value of **opacity** is also **1**, no opacity animation will be applied, and the component appears or disappears without any transition animation. > 4. If the value of an attribute specified in **TransitionEffect** is the same as the default value, no transition animation is applied for the attribute. For example, with **TransitionEffect.opacity(1).animation({duration:1000})**, because the default value of **opacity** is also **1**, no opacity animation will be applied, and the component appears or disappears without any transition animation.
> 5. For details about the scale and rotate effects, see [Transformation](ts-universal-attributes-transformation.md).
## Example ## TransitionOptions<sup>(deprecated)</sup>
The following is an example of using **TransitionOptions** for appearance and disappearance of the component. Defines the transition effect by setting parameters in the struct.
```ts
// xxx.ets
@Entry
@Component
struct TransitionExample {
@State flag: boolean = true
@State show: string = 'show'
build() { This API is deprecated since API version 10. You are advised to use [TransitionEffect](#transitioneffect10) instead.
Column() { | Name| Type| Mandatory| Description|
Button(this.show).width(80).height(30).margin(30) | -------- | -------- | -------- | -------- |
.onClick(() => { | type | [TransitionType](ts-appendix-enums.md#transitiontype) | No| Transition type.<br>Default value: **TransitionType.All**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>If **type** is not specified, the default value **TransitionType.All** is used, which means that the transition effect works for both component addition and deletion.|
// Click the button to show or hide the image. | 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>Value range: [0, 1]<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>A value less than 0 or greater than 1 evaluates to the value **1**.|
if (this.flag) { | 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.<br>Since API version 9, this API is supported in ArkTS widgets.|
this.show = 'hide'; | 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**: scale center point. The default values are both **"50%"**, indicating that the center point of the page.<br>- If the center point is (0, 0), it refers to the upper left corner of the component.<br>Since API version 9, this API is supported in ArkTS widgets.|
} else { | 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**: X-component of the rotation vector.<br>- **y**: Y-component of the rotation vector.<br>- **z**: Z-component of the rotation vector.<br>- **centerX** and **centerY**: rotation center point. The default values are both **"50%"**, indicating that the center point of the page.<br>- If the center point is (0, 0), it refers to the upper left corner of the component.<br>Since API version 9, this API is supported in ArkTS widgets.|
this.show = 'show';
}
// When set to a value of the TransitionOptions type, the transition attribute must work with animateTo.
animateTo({ duration: 1000 }, () => {
this.flag = !this.flag
})
})
if (this.flag) {
// Apply different transition effects to the appearance and disappearance of the image.
// When the image appears, it changes from the state where the scale factor is 0 along the x-axis and 1 along the y-axis to the state where the scale factor is both 1 along x-axis and y-axis.
// When the image disappears, it rotates from 0° to 180° clockwise around the z-axis.
Image($r('app.media.testImg')).width(200).height(200)
.transition({ type: TransitionType.Insert, scale: { x: 0, y: 1.0 } })
.transition({ type: TransitionType.Delete, rotate: { z: 1, angle: 180 } })
}
}.width('100%')
}
}
```
Below you can see the example in action.<br> > **NOTE**
![transitionComponent1](figures/transitionComponent1.gif) >
> 1. When set to a value of the **TransitionOptions** type, the **transition** attribute must work with [animateTo](ts-explicit-animation.md). The animation duration, curve, and delay follow the settings in **animateTo**.
> 2. If the value of the **TransitionOptions** type has only **type** specified, the transition effect will take on the default opacity. For example, **{type: TransitionType.Insert}** produces the same effect as **{type: TransitionType.Insert, opacity: 0}**. If a specific style is specified, the transition effect will not take on the default opacity.
## Example
The following is an example of using the same transition effect for the appearance and disappearance (which are inverse processes) of the component. The following is an example of using the same transition effect for the appearance and disappearance (which are inverse processes) of the component.
```ts ```ts
......
...@@ -12,7 +12,7 @@ A shared element transition is a transition animation applied to a component tha ...@@ -12,7 +12,7 @@ A shared element transition is a transition animation applied to a component tha
| Name | Parameter | Description | | Name | Parameter | Description |
| ---------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| sharedTransition | id: string,<br>{<br> duration?: number,<br> curve?: Curve \| string,<br> delay?: number,<br> motionPath?: <br>{<br> path: string,<br> form?: number,<br> to?: number,<br> rotatable?: boolean<br>},<br>zIndex?: number,<br>type?: [SharedTransitionEffectType](ts-appendix-enums.md#sharedtransitioneffecttype)<br>} | Transition of the shared element. If the same **id** value is configured for a component on the two pages, this component is considered as a shared element of the pages. If the **id** value is an empty string, no transition will be applied to the component.<br>- **id**: component ID.<br>- **duration**: animation duration.<br>Default value: **1000**<br>Unit: ms<br>Value range: [0, +∞)<br>The value **0** indicates that no animation is applied. A value less than 0 evaluates to the value **0**.<br>- **curve**: animation curve. The default curve is **Linear**. For details about the valid values, see [Curve](ts-animatorproperty.md).<br>- **delay**: animation delay.<br>Default value: **0**<br>Unit: ms<br>Value range: [0, +∞)<br>A value less than 0 evaluates to the value **0**.<br>- **motionPath**: motion path information. For details, see [Motion Path Animation](ts-motion-path-animation.md).<br>- **path**: path.<br>- **from**: start value.<br>- **to**: end value.<br>- **rotatable**: whether to rotate.<br>- **zIndex**: z-axis.<br>- **type**: animation type.| | sharedTransition | id: string,<br>{<br> duration?: number,<br> curve?: Curve \| string,<br> delay?: number,<br> motionPath?: <br>{<br> path: string,<br> form?: number,<br> to?: number,<br> rotatable?: boolean<br>},<br>zIndex?: number,<br>type?: [SharedTransitionEffectType](ts-appendix-enums.md#sharedtransitioneffecttype)<br>} | Transition of the shared element. If the same **id** value is configured for a component on the two pages, this component is considered as a shared element of the pages. If the **id** value is an empty string, no transition will be applied to the component.<br>- **id**: component ID.<br>- **duration**: animation duration.<br>Default value: **1000**<br>Unit: ms<br>Value range: [0, +∞)<br>The value **0** indicates that no animation is applied. A value less than 0 evaluates to the default value **1000**.<br>- **curve**: animation curve. The default curve is **Linear**. For details about the valid values, see [Curve](ts-animatorproperty.md).<br>- **delay**: animation delay.<br>Default value: **0**<br>Unit: ms<br>Value range: [0, +∞)<br>A value less than 0 evaluates to the value **0**.<br>- **motionPath**: motion path information. For details, see [Motion Path Animation](ts-motion-path-animation.md).<br>- **path**: path.<br>- **from**: start value.<br>- **to**: end value.<br>- **rotatable**: whether to rotate.<br>- **zIndex**: z-axis.<br>- **type**: animation type.|
## Example ## Example
......
...@@ -228,7 +228,7 @@ The **CustomBuilder** type is used to define custom UI descriptions in component ...@@ -228,7 +228,7 @@ The **CustomBuilder** type is used to define custom UI descriptions in component
| Name | Type | Description | | Name | Type | Description |
| ------------- | ---------------------- | ---------------------------------------- | | ------------- | ---------------------- | ---------------------------------------- |
| CustomBuilder | () =&gt; any | Must be decorated by **@Builder**. For details, see [@Builder](../../quick-start/arkts-builder.md).| | CustomBuilder | () =&gt; any | Builder for creating a custom component; must be used with @Builder. For details, see [@Builder](../../quick-start/arkts-builder.md).|
## PixelStretchEffectOptions<sup>10+</sup> ## PixelStretchEffectOptions<sup>10+</sup>
...@@ -321,3 +321,23 @@ Describes the animation information of the \<Swiper> component. ...@@ -321,3 +321,23 @@ Describes the animation information of the \<Swiper> component.
| currentOffset | number | Offset of the currently displayed element relative to the start position of the **\<Swiper>** along the main axis. Unit: vp<br>Default value: **0**| | currentOffset | number | Offset of the currently displayed element relative to the start position of the **\<Swiper>** along the main axis. Unit: vp<br>Default value: **0**|
| targetOffset | number | Offset of the target element relative to the start position of the **\<Swiper>** along the main axis. Unit: vp<br>Default value: **0**| | targetOffset | number | Offset of the target element relative to the start position of the **\<Swiper>** along the main axis. Unit: vp<br>Default value: **0**|
| velocity | number | Hands-off velocity at the beginning of the animation. Unit: vp/s<br>Default value: **0**| | velocity | number | Hands-off velocity at the beginning of the animation. Unit: vp/s<br>Default value: **0**|
## SafeAreaType<sup>10+</sup>
The **SafeAreaType** type is used to describe the types of expanded safe areas.
| Name | Description |
| -------- | ------------------------------------------ |
| SYSTEM | Default non-safe area of the system, including the status bar and navigation bar. |
| CUTOUT | Non-safe area of the device, for example, the notch area.|
| KEYBOARD | Soft keyboard area. |
## SafeAreaEdge<sup>10+</sup>
The **SafeAreaEdge** type is used to define the edge for expanding the safe area.
| Name | Description |
| ------ | ---------- |
| TOP | Top edge.|
| BOTTOM | Bottom edge.|
| START | Start edge.|
| END | End edge.|
...@@ -4,15 +4,16 @@ ...@@ -4,15 +4,16 @@
> >
> - The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > - The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> >
> - The column width and column gap in the grid layout are determined by the nearest parent component **GridContainer**. The component tree that uses grid attributes must contain one **GridContainer** or more. > - The column width and column gap in the grid layout are determined by the nearest parent component **\<GridContainer>**. The component tree that uses grid attributes must contain one **\<GridContainer>** component or more.
> - To call the **gridSpan** or **gridOffset** attribute, its parent or ancestor component must be **\<GridContainer>**.
## Attributes ## Attributes
| Name | Type | Description | | Name | Type | Description |
| ----------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ----------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| useSizeType<sup>(deprecated)</sup> | {<br>xs?: number \| { span: number, offset: number },<br>sm?: number \| { span: number, offset: number },<br>md?: number \| { span: number, offset: number },<br>lg?: number \| { span: number, offset: number }<br>} | Number of occupied columns and offset columns for a specific device width type. **span** indicates the number of occupied columns, and **offset** indicates the number of offset columns.<br>If the value is of the number type, only the number of columns can be set. If the value is in the format of {"span": 1, "offset": 0}, both the number of occupied columns and the number of offset columns need to be set.<br>- **xs** indicates that the device width type is **SizeType.XS**.<br>- **sm** indicates that the device width type is **SizeType.SM**.<br>- **md** indicates that the device width type is **SizeType.MD**.<br>- **lg** indicates that the device width type is **SizeType.LG**.<br>This attribute is deprecated since API version 9. You are advised to use [GridCol](ts-container-gridcol.md) and [GridRow](ts-container-gridrow.md) instead. | | useSizeType<sup>(deprecated) </sup> | {<br>xs?: number \| { span: number, offset: number },<br>sm?: number \| { span: number, offset: number },<br>md?: number \| { span: number, offset: number },<br>lg?: number \| { span: number, offset: number }<br>} | Number of occupied columns and offset columns for a specific device width type. **span** indicates the number of occupied columns, and **offset** indicates the number of offset columns.<br>If the value is of the number type, only the number of columns can be set. If the value is in the format of {"span": 1, "offset": 0}, both the number of occupied columns and the number of offset columns need to be set.<br>- **xs** indicates that the device width type is **SizeType.XS**.<br>- **sm** indicates that the device width type is **SizeType.SM**.<br>- **md** indicates that the device width type is **SizeType.MD**.<br>- **lg** indicates that the device width type is **SizeType.LG**.<br>This attribute is deprecated since API version 9. You are advised to use [GridCol](ts-container-gridcol.md) and [GridRow](ts-container-gridrow.md) instead.|
| gridSpan | number | Default number of occupied columns, that is, the number of occupied columns when **span** in **useSizeType** is not set.<br>**NOTE**<br>If the **span** attribute is set, the component width is determined by the grid layout.<br>Default value: **1**| | gridSpan | number | Default number of occupied columns, that is, the number of occupied columns when **span** in **useSizeType** is not set.<br>**NOTE**<br>If the **span** attribute is set, the component width is determined by the grid layout.<br>Default value: **1**|
| gridOffset | number | Default number of offset columns, that is, the number of offset columns in the start direction of the parent component (which is also the nth column that the component is in) when **offset** in **useSizeType** is not set.<br>**NOTE**<br>- After this attribute is set, the horizontal layout of the current component does not follow the original layout of the parent component. Instead, it offsets along the start direction of the parent component.<br>- Offset = (Column width + Gap) \* Number of columns.<br>- After this attribute is set, sibling components will be arranged relatively to this component, as in the relative layout.<br>Default value: **0**| | gridOffset | number | Default number of offset columns, that is, the number of offset columns in the start direction of the parent component (which is also the nth column that the component is in) when **offset** in **useSizeType** is not set.<br>**NOTE**<br>- After this attribute is set, the horizontal layout of the current component does not follow the original layout of the parent component. Instead, it offsets along the start direction of the parent component.<br>- Offset = (Column width + Gap) \* Number of columns.<br>- After this attribute is set, sibling components will be arranged relatively to this component, as in the relative layout.<br>Default value: **0**|
...@@ -110,6 +111,6 @@ struct GridContainerExample1 { ...@@ -110,6 +111,6 @@ struct GridContainerExample1 {
![en-us_image_0000001212378416](figures/en-us_image_0000001212378416.png) ![en-us_image_0000001212378416](figures/en-us_image_0000001212378416.png)
**Figure 4** Setting gridSpan and gridOffset separately has the same effect as using SizeType for a specific device width type **Figure 4** Setting gridSpan and gridOffset separately has the same effect as useSizeType for a specific device width type
![gridSpan](figures/gridSpan.png) ![gridSpan](figures/gridSpan.png)
...@@ -55,7 +55,7 @@ struct AspectRatioExample { ...@@ -55,7 +55,7 @@ struct AspectRatioExample {
Text(item) Text(item)
.backgroundColor(0xbbb2cb) .backgroundColor(0xbbb2cb)
.fontSize(40) .fontSize(40)
.height(160) .width('100%')
.aspectRatio(1.5) .aspectRatio(1.5)
} }
}, item => item) }, item => item)
...@@ -70,10 +70,12 @@ struct AspectRatioExample { ...@@ -70,10 +70,12 @@ struct AspectRatioExample {
} }
``` ```
**Figure 1** Portrait display<br> **Figure 1** Portrait display
![en-us_image_0000001256978379](figures/en-us_image_0000001256978379.gif) ![en-us_image_0000001256978379](figures/en-us_image_0000001256978379.gif)
**Figure 2** Landscape display<br> **Figure 2** Landscape display
![en-us_image_0000001212218476](figures/en-us_image_0000001212218476.gif) ![en-us_image_0000001212218476](figures/en-us_image_0000001212218476.gif)
```ts ```ts
...@@ -133,4 +135,6 @@ struct DisplayPriorityExample { ...@@ -133,4 +135,6 @@ struct DisplayPriorityExample {
``` ```
Landscape display in containers of different sizes
![en-us_image_0000001212058504](figures/en-us_image_0000001212058504.gif) ![en-us_image_0000001212058504](figures/en-us_image_0000001212058504.gif)
...@@ -9,7 +9,7 @@ You can set state-specific styles for components. ...@@ -9,7 +9,7 @@ You can set state-specific styles for components.
## Attributes ## Attributes
| Style| Type| Description| | Name| Type| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| stateStyles | StateStyles | Styles of the component for different states.<br>Since API version 9, this API is supported in ArkTS widgets.| | stateStyles | StateStyles | Styles of the component for different states.<br>Since API version 9, this API is supported in ArkTS widgets.|
...@@ -21,9 +21,10 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -21,9 +21,10 @@ Since API version 9, this API is supported in ArkTS widgets.
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| normal | ()=&gt;void | No| Style of the component when being stateless.| | normal | ()=&gt;void | No| Style of the component when being stateless.|
| pressed | ()=&gt;void | No| Style of the component in the pressed state.| | pressed | ()=&gt;void | No| Style of the component in the pressed state.|
| disabled | ()=&gt;void | No| Style of the component in disabled state.| | disabled | ()=&gt;void | No| Style of the component in the disabled state.|
| focused | ()=&gt;void | No| Style of the component in focused state.| | focused | ()=&gt;void | No| Style of the component in the focused state.|
| clicked | ()=&gt;void | No| Style of the component in clicked state.| | clicked | ()=&gt;void | No| Style of the component in the clicked state.|
| selected<sup>10+</sup> | ()=&gt;void | No| Style of the component in the selected state.|
## Example ## Example
......
...@@ -5,19 +5,14 @@ A drag event is triggered when a component is dragged. ...@@ -5,19 +5,14 @@ A drag event is triggered when a component is dragged.
> **NOTE** > **NOTE**
> >
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
>
> The following components provide the drag effect by default: [\<Image>](../arkui-ts/ts-basic-components-image.md), [\<Text>](../arkui-ts/ts-basic-components-text.md), [\<TextArea>](../arkui-ts/ts-basic-components-textarea.md), and [\<Search>](../arkui-ts/ts-basic-components-search.md).
## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name| Type| Description|
| -------- | -------- | -------- |
| allowDrop<sup>10+</sup> | Array\<UnifiedData> | Type of data that can be dropped to the component.<br>Default value: empty<br>|
| draggable<sup>10+</sup> | boolean | Whether the widget is draggable.<br>Default value: **false**<br>|
## Events ## Events
| Name | Bubbling Supported| Description | | Name | Bubbling Supported| Description |
| ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| onDragStart(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; [CustomBuilder](ts-types.md#custombuilder8) \| [DragItemInfo](#dragiteminfo)) | No | Triggered when the component bound to the event is dragged for the first time.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>Return value: object being dragged, which is used for prompts displayed when the object is dragged.<br>A drag event can be triggered by a 500 ms long press. If the duration of a long press gesture is set to less than or equal to 500 ms, the callback for the long press gesture takes precedence. Otherwise, the callback for the drag event takes precedence.| | onDragStart(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; [CustomBuilder](ts-types.md#custombuilder8) \| [DragItemInfo](#dragiteminfo)) | No | Triggered when the component bound to the event is dragged for the first time.<br>- **event**: information about the drag event. For details, see [DragEvent](#dragevent).<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br> Return value: component information displayed during dragging.<br>Trigger condition: long press for at least 500 ms.<br> Event priority:<br>Long press time < 500 ms: Long press event > Drag event<br> Other: Drag event > Long press event.|
| onDragEnter(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item enters a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when a listener for the **onDrop** event is enabled.| | onDragEnter(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item enters a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when a listener for the **onDrop** event is enabled.|
| onDragMove(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item moves in a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when a listener for the **onDrop** event is enabled.| | onDragMove(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item moves in a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when a listener for the **onDrop** event is enabled.|
| onDragLeave(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item leaves a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when a listener for the **onDrop** event is enabled.| | onDragLeave(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item leaves a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when a listener for the **onDrop** event is enabled.|
...@@ -35,9 +30,9 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -35,9 +30,9 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
## extraParams ## extraParams
Provides additional information required for dragging an item. Provides additional information required for dragging an item.
**extraParams** is a string converted from a JSON object. You can obtain the following attributes using the JSON object converted from **Json.parse**. **extraParams** is a string converted from a JSON object. You can obtain the following attributes using the JSON object converted from **Json.parse**.
| Name | Type | Description | | Name | Type | Description |
| ------------- | ------ | ---------------------------------------- | | ------------- | ------ | ---------------------------------------- |
...@@ -51,20 +46,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -51,20 +46,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| getX() | number | X-coordinate of the drag position relative to the upper left corner of the screen, in vp.| | getX() | number | X-coordinate of the drag position relative to the upper left corner of the screen, in vp.|
| getY() | number | Y-coordinate of the drag position relative to the upper left corner of the screen, in vp.| | getY() | number | Y-coordinate of the drag position relative to the upper left corner of the screen, in vp.|
| useCustomDropAnimation<sup>10+</sup> | boolean | Whether to use the default drop animation when the dragging ends.| | useCustomDropAnimation<sup>10+</sup> | boolean | Whether to use the default drop animation when the dragging ends.|
| dragBehavior<sup>10+</sup> | [DragBehavior](#dragbehavior10) | Component tree behavior corresponding to the drga event.| | setData(unifiedData: [UnifiedData](../apis/js-apis-data-udmf.md#unifieddata))<sup>10+</sup> | void | Sets drag-related data in the drag event.|
| setData(unifiedData: UnifiedData)<sup>10+</sup> | void | Sets drag-related data in the drag event.| | getData()<sup>10+</sup> | [UnifiedData](../apis/js-apis-data-udmf.md#unifieddata) | Obtains drag-related data from the drag event.|
| getData()<sup>10+</sup> | UnifiedData | Obtains drag-related data from the drag event.| | getSummary()<sup>10+</sup> | [Summary](../apis/js-apis-data-udmf.md#summary) | Obtains the summary of drag-related data from the drag event.|
| getSummary()<sup>10+</sup> | Summary | Obtains the summary of drag-related data from the drag event.|
| setResult(dragRect: [DragRet](#dragret10))<sup>10+</sup>| void | Sets the drag and drop result in the drag event.| | setResult(dragRect: [DragRet](#dragret10))<sup>10+</sup>| void | Sets the drag and drop result in the drag event.|
| getResult()<sup>10+</sup> | [DragRet](#dragret10)| Obtains the drag and drop result from the drag event.| | getResult()<sup>10+</sup> | [DragRet](#dragret10)| Obtains the drag and drop result from the drag event.|
| getPrviewRect()<sup>10+</sup> | [Rectangle](ts-universal-attributes-touch-target.md#rectangle) | Obtains the rectangle where the preview image is located.| | getPrviewRect()<sup>10+</sup> | [Rectangle](ts-universal-attributes-touch-target.md#rectangle) | Obtains the rectangle where the preview image is located.|
| getVelocityX()<sup>10+</sup> | number | Obtains the dragging velocity along the x-axis. The origin of the coordinate axis is the upper left corner of the screen. The unit is vp. The velocity is positive if the movement is from left to right, and it is negative if the movement is from right to left.|
## DragBehavior<sup>10+</sup> | getVelocityY()<sup>10+</sup> | number | Obtains the dragging velocity along the y-axis. The origin of the coordinate axis is the upper left corner of the screen. The unit is vp. The velocity is positive if the movement is from top to bottom, and it is negative if the movement is from bottom to top.|
| getVelocity()<sup>10+</sup> | number | Obtains the dragging velocity along the main axis. The value is the arithmetic square root of the sum of squares of the velocity along the x- and y-axis. |
| Name| Description|
| ------ | ------ |
| COPY | In the component tree, copy the component that initiates the dragging and copy the copy result to the position where the dragging ends.|
| MOVE | In the component tree, cut the component that initiates the dragging and move it to the position where the dragging ends.|
## DragRet<sup>10+</sup> ## DragRet<sup>10+</sup>
...@@ -78,230 +68,165 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ...@@ -78,230 +68,165 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
## Example ## Example
### Example 1
```ts ```ts
@Observed import udmf from '@ohos.data.UDMF';
class ClassA { import promptAction from '@ohos.promptAction';
public name: string
public bol: boolean
constructor(name: string, bol: boolean) {
this.name = name
this.bol = bol
}
}
@Extend(Text) function textStyle() {
.width('25%')
.height(35)
.fontSize(16)
.textAlign(TextAlign.Center)
.backgroundColor(0xAFEEEE)
}
@Entry @Entry
@Component @Component
struct DragExample { struct Index {
@State arr: ClassA[] = [new ClassA('A', true), new ClassA('B', true), new ClassA('C', true)] @State targetImage: string = '';
@State dragIndex: number = 0 @State targetText: string = 'Drag Text';
@State hyperLinkText: string = 'HyperLink';
changeIndex(index1: number, index2: number) {// Exchange the array position. @State hyperLinkContent: string = 'HyperLink';
[this.arr[index1], this.arr[index2]] = [this.arr[index2], this.arr[index1]]; @State imageWidth: number = 100;
@State imageHeight: number = 100;
@State imgState: Visibility = Visibility.Visible;
@State videoSrc: string = 'resource://RAWFILE/02.mp4';
@State abstractContent: string = "abstract";
@State textContent: string = "";
getDataFromUdmfRetry(event: DragEvent, callback: (data: DragEvent)=>void)
{
let records: Array<udmf.UnifiedRecord> = event.getData().getRecords();
if (records.length !== 0) {
callback(event);
return;
}
setTimeout(()=>{
this.getDataFromUdmfRetry(event, callback);
}, 1500);
} }
build() { build() {
Row() {
Column() { Column() {
Row({ space: 15 }) { Text('start Drag')
List({ space: 20 }) { .fontSize(18)
ForEach(this.arr, (item, index) => { .width('100%')
ListItem() { .height(40)
Column() { .margin(10)
Child({ a: this.arr[index] }) .backgroundColor('#008888')
} Image($r('app.media.icon'))
.onTouch((event: TouchEvent) => { .width(100)
if (event.type === TouchType.Down) { .height(100)
this.dragIndex = index // Obtain the index of the current dragged child component. .draggable(true)
console.info('onTouch' + this.dragIndex) .margin({left: 15})
} .visibility(this.imgState)
}) .onDragEnd((event)=>{
} if (event.getResult() === DragRet.DRAG_SUCCESS) {
}) promptAction.showToast({duration: 100, message: 'Drag Success'});
} else if (event.getResult() === DragRet.DRAG_FAILED) {
promptAction.showToast({duration: 100, message: 'Drag failed'});
} }
.listDirection(Axis.Horizontal)
.onDrop((event: DragEvent, extraParams: string) => { // The component bound to this event can be used as the drop target. When the dragging stops within the component scope, the callback is triggered.
let jsonString = JSON.parse(extraParams);
this.changeIndex(this.dragIndex, jsonString.insertIndex)
}) })
}.padding({ top: 10, bottom: 10 }).margin(10) Text('test drag event')
.width('100%')
}.width('100%').height('100%').padding({ top: 20 }).margin({ top: 20 }) .height(100)
} .draggable(true)
} .margin({left: 15})
.copyOption(CopyOptions.InApp)
@Component TextArea({placeholder: 'please input words'})
struct Child { .copyOption(CopyOptions.InApp)
@ObjectLink a: ClassA .width('100%')
.height(50)
@Builder pixelMapBuilder() { .draggable(true)
Column() { Search({placeholder: 'please input you word'})
Text(this.a.name) .searchButton('Search')
.width('50%') .width('100%')
.height(60) .height(80)
.fontSize(16) .textFont({size: 20})
.borderRadius(10)
.textAlign(TextAlign.Center)
.backgroundColor(Color.Yellow)
}
}
build() {
Column() { Column() {
Text(this.a.name) Text('change video source')
.textStyle() }.draggable(true)
.visibility(this.a.bol ? Visibility.Visible : Visibility.None) .onDragStart((event)=>{
.onDragStart(() => { // The callback is triggered when the component bound to this event is dragged for the first time. let video: udmf.Video = new udmf.Video();
this.a.bol = false // Control the visibility. video.videoUri = 'resource://RAWFILE/01.mp4';
return this.pixelMapBuilder() // Set the image displayed during dragging. let data: udmf.UnifiedData = new udmf.UnifiedData(video);
}) event.setData(data);
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Up) {
this.a.bol = true
}
}) })
Text('')
.width('25%')
.height(35)
.fontSize(16)
.textAlign(TextAlign.Center)
.border({ width: 5, color: 'red' })
.visibility(!this.a.bol ? Visibility.Visible : Visibility.None)
}
}
}
```
![drag-drop](figures/drag-drop.gif)
### Example 2
```ts
// xxx.ets
@Extend(Text) function textStyle () {
.width('25%')
.height(35)
.fontSize(16)
.textAlign(TextAlign.Center)
.backgroundColor(0xAFEEEE)
}
@Entry
@Component
struct DragExample {
@State numbers: string[] = ['one', 'two', 'three', 'four', 'five', 'six']
@State text: string = ''
@State bool: boolean = true
@State eventType: string = ''
@State appleVisible: Visibility = Visibility.Visible
@State orangeVisible: Visibility = Visibility.Visible
@State bananaVisible: Visibility = Visibility.Visible
private dragList: string[] = ['apple', 'orange', 'banana']
@State fruitVisible: Visibility[] = [Visibility.Visible, Visibility.Visible, Visibility.Visible]
@State idx: number = 0
// Customize the content displayed during dragging.
@Builder pixelMapBuilder() {
Column() { Column() {
Text(this.text) Text('this is abstract')
.width('50%') .fontSize(20)
.height(60) .width('100%')
.fontSize(16) }.margin({left: 40, top: 20})
.borderRadius(10) .width('100%')
.textAlign(TextAlign.Center) .height(100)
.backgroundColor(Color.Yellow) .onDragStart((event)=>{
} let data: udmf.PlainText = new udmf.PlainText();
} data.abstract = 'this is abstract';
data.textContent = 'this is content this is content';
build() { event.setData(new udmf.UnifiedData(data));
})
}.width('45%')
.height('100%')
Column() { Column() {
Text('There are three Text elements here') Text('Drag Target Area')
.fontSize(12) .fontSize(20)
.fontColor(0xCCCCCC) .width('100%')
.width('90%') .height(40)
.textAlign(TextAlign.Start) .margin(10)
.margin(5) .backgroundColor('#008888')
Row({ space: 15 }) { Image(this.targetImage)
ForEach(this.dragList, (item, index) => { .width(this.imageWidth)
Text(item) .height(this.imageHeight)
.textStyle() .draggable(true)
.visibility(this.fruitVisible[index]) .margin({left: 15})
.onDragStart(() => { .border({color: Color.Black, width: 1})
this.bool = true .allowDrop([udmf.UnifiedDataType.IMAGE])
this.text = item .onDrop((dragEvent: DragEvent)=> {
this.fruitVisible[index] = Visibility.None this.getDataFromUdmfRetry(dragEvent, (event)=>{
return this.pixelMapBuilder let records: Array<udmf.UnifiedRecord> = event.getData().getRecords();
let rect: Rectangle = event.getPreviewRect();
this.imageWidth = Number(rect.width);
this.imageHeight = Number(rect.height);
this.targetImage = (<udmf.Image>(records[0])).imageUri;
event.useCustomDropAnimation = false;
animateTo({duration: 1000}, ()=>{
this.imageWidth = 100;
this.imageHeight = 100;
this.imgState = Visibility.None;
}) })
.onTouch((event: TouchEvent) => { event.setResult(DragRet.DRAG_SUCCESS);
if (event.type === TouchType.Down) {
this.eventType = 'Down'
this.idx = index
}
if (event.type === TouchType.Up) {
this.eventType = 'Up'
if (this.bool) {
this.fruitVisible[index] = Visibility.Visible
}
}
}) })
}) })
}.padding({ top: 10, bottom: 10 }).margin(10)
Text('This is a List element') Text(this.targetText)
.fontSize(12)
.fontColor(0xCCCCCC)
.width('90%')
.textAlign(TextAlign.Start)
.margin(15)
List({ space: 20 }) {
ForEach(this.numbers, (item) => {
ListItem() {
Text(item)
.width('100%') .width('100%')
.height(80) .height(100)
.fontSize(16) .border({color: Color.Black, width: 1})
.borderRadius(10) .margin(15)
.textAlign(TextAlign.Center) .allowDrop([udmf.UnifiedDataType.TEXT])
.backgroundColor(0xAFEEEE) .onDrop((dragEvent: DragEvent)=>{
} this.getDataFromUdmfRetry(dragEvent, event => {
}, item => item) let records:Array<udmf.UnifiedRecord> = event.getData().getRecords();
} this.targetText = (<udmf.Text>(records[0])).details['value'];
.editMode(true)
.height('50%')
.width('90%')
.border({ width: 1 })
.padding(15)
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 })
.onDragEnter((event: DragEvent, extraParams: string) => {
console.log('List onDragEnter, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY())
}) })
.onDragMove((event: DragEvent, extraParams: string) => {
console.log('List onDragMove, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY())
}) })
.onDragLeave((event: DragEvent, extraParams: string) => {
console.log('List onDragLeave, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY()) Video({src: this.videoSrc, previewUri: $r('app.media.icon')})
.width('100%')
.height(200)
.controls(true)
.allowDrop([udmf.UnifiedDataType.VIDEO])
Column() {
Text(this.abstractContent).fontSize(20).width('100%')
Text(this.textContent).fontSize(15).width('100%')
}.width('100%').height(100).margin(20).border({color: Color.Black, width: 1})
.allowDrop([udmf.UnifiedDataType.PLAIN_TEXT])
.onDrop((dragEvent)=>{
this.getDataFromUdmfRetry(dragEvent, event=>{
let records: Array<udmf.UnifiedRecord> = event.getData().getRecords();
let plainText: udmf.PlainText = <udmf.PlainText>(records[0]);
this.abstractContent = plainText.abstract;
this.textContent = plainText.textContent;
}) })
.onDrop((event: DragEvent, extraParams: string) => {
let jsonString = JSON.parse(extraParams);
if (this.bool) {
// Insert an element using the splice method.
this.numbers.splice(jsonString.insertIndex, 0, this.text)
this.bool = false
}
this.fruitVisible[this.idx] = Visibility.None
}) })
}.width('100%').height('100%').padding({ top: 20 }).margin({ top: 20 }) }.width('45%')
.height('100%')
.margin({left: '5%'})
}
.height('100%')
} }
} }
``` ```
![en-us_image_0000001252667389](figures/en-us_image_0000001252667389.gif)
...@@ -22,9 +22,10 @@ A touch event is triggered when a finger is pressed, slides, or is lifted from a ...@@ -22,9 +22,10 @@ A touch event is triggered when a finger is pressed, slides, or is lifted from a
| touches | Array&lt;[TouchObject](#touchobject)&gt; | All finger information. | | touches | Array&lt;[TouchObject](#touchobject)&gt; | All finger information. |
| changedTouches | Array&lt;[TouchObject](#touchobject)&gt; | Finger information changed.| | changedTouches | Array&lt;[TouchObject](#touchobject)&gt; | Finger information changed.|
| stopPropagation | () => void | Stops the event from bubbling upwards or downwards.| | stopPropagation | () => void | Stops the event from bubbling upwards or downwards.|
| timestamp<sup>8+</sup> | number | Timestamp of the event. It is interval between the time when the event is triggered and the time when the system starts, in nanoseconds.| | timestamp<sup>8+</sup> | number | Timestamp of the event. It is the interval between the time when the event is triggered and the time when the system starts, in nanoseconds.|
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8) | Display area of the element that triggers the gesture event.| | target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8) | Display area of the element that triggers the gesture event.|
| source<sup>8+</sup> | [SourceType](ts-gesture-settings.md#sourcetype)| Event input device.| | source<sup>8+</sup> | [SourceType](ts-gesture-settings.md#sourcetype)| Event input device.|
| getHistoricalPoints<sup>10+</sup> | Array&lt;[HistoricalPoint](#historicalpoint10)&gt;| All historical points of the current frame (the touch event frequency of a frame varies by device, and all touch events of the current frame are referred to as historical points).|
## TouchObject ## TouchObject
...@@ -38,6 +39,14 @@ A touch event is triggered when a finger is pressed, slides, or is lifted from a ...@@ -38,6 +39,14 @@ A touch event is triggered when a finger is pressed, slides, or is lifted from a
| x | number | X coordinate of the touch point relative to the upper left corner of the component being touched.| | x | number | X coordinate of the touch point relative to the upper left corner of the component being touched.|
| y | number | Y coordinate of the touch point relative to the upper left corner of the component being touched.| | y | number | Y coordinate of the touch point relative to the upper left corner of the component being touched.|
## HistoricalPoint<sup>10+</sup>
| Name | Type | Description |
| ----------- | ----------------------------------- | ----------------------------------------------------------------------------- |
| touchObject | [TouchObject](#touchobject) | Basic information of the historical point. |
| size | number | Size of the contact area between the finger and screen for the historical point. |
| force | number | Touch force of the historical point.<br>Default value: **0**<br>Value range: [0,1]. A larger value indicates a greater touch force.<br>The support for this API varies by device. Currently, it is only available on tablets.|
| timestamp | number | Timestamp of the historical point. It is the interval between the time when the event is triggered and the time when the system starts, in nanoseconds. |
## Example ## Example
```ts ```ts
......
...@@ -19,7 +19,7 @@ You can use the provided APIs to read the SycCap parameter file to check whether ...@@ -19,7 +19,7 @@ You can use the provided APIs to read the SycCap parameter file to check whether
| Name| Description| | Name| Description|
| -------- | -------- | | -------- | -------- |
| [syscap_ndk.h](syscap__ndk_8h.md) | Defines the APIs for checking SycCap support.| | [syscap_ndk.h](syscap__ndk_8h.md) | Declares the APIs for checking SycCap support.<br>**File to include**: <syscap_ndk.h><br>**Library**: libdeviceinfo_ndk.z.so|
### Functions ### Functions
......
...@@ -226,22 +226,24 @@ try { ...@@ -226,22 +226,24 @@ try {
```ts ```ts
import vibrator from '@ohos.vibrator'; import vibrator from '@ohos.vibrator';
const FILE_NAME = "xxx.json";
// 获取振动文件资源描述符 // 获取振动文件资源描述符
let fileDescriptor = undefined; async function getRawfileFd(fileName) {
getContext().resourceManager.getRawFd(FILE_NAME).then(value => { let rawFd = await globalThis.getContext().resourceManager.getRawFd(fileName);
fileDescriptor = { fd: value.fd, offset: value.offset, length: value.length }; return rawFd;
console.info('Succeed in getting resource file descriptor'); }
}).catch(error => {
console.error(`Failed to get resource file descriptor. Code: ${error.code}, message: ${error.message}`); // 关闭振动文件资源描述符
}); async function closeRawfileFd(fileName) {
// 使用startVibration、stopVibration需要添加ohos.permission.VIBRATE权限 await globalThis.getContext().resourceManager.closeRawFd(fileName)
try { }
// 启动自定义振动
// 播放自定义振动,使用startVibration、stopVibration需要添加ohos.permission.VIBRATE权限
async function playCustomHaptic(fileName) {
try {
let rawFd = await getRawfileFd(fileName);
vibrator.startVibration({ vibrator.startVibration({
type: "file", type: "file",
hapticFd: { fd: fileDescriptor.fd, offset: fileDescriptor.offset, length: fileDescriptor.length } hapticFd: { fd: rawFd.fd, offset: rawFd.offset, length: rawFd.length }
}, { }, {
usage: "alarm" usage: "alarm"
}).then(() => { }).then(() => {
...@@ -249,7 +251,6 @@ try { ...@@ -249,7 +251,6 @@ try {
}, (error) => { }, (error) => {
console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`); console.error(`Failed to start vibration. Code: ${error.code}, message: ${error.message}`);
}); });
// 停止所有类型的马达振动
vibrator.stopVibration(function (error) { vibrator.stopVibration(function (error) {
if (error) { if (error) {
console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`); console.error(`Failed to stop vibration. Code: ${error.code}, message: ${error.message}`);
...@@ -257,15 +258,11 @@ try { ...@@ -257,15 +258,11 @@ try {
} }
console.info('Succeed in stopping vibration'); console.info('Succeed in stopping vibration');
}) })
} catch (error) { await closeRawfileFd(fileName);
} catch (error) {
console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`); console.error(`An unexpected error occurred. Code: ${error.code}, message: ${error.message}`);
}
} }
// 关闭振动文件资源
getContext().resourceManager.closeRawFd(FILE_NAME).then(() => {
console.info('Succeed in closing resource file descriptor');
}).catch(error => {
console.error(`Failed to close resource file descriptor. Code: ${error.code}, message: ${error.message}`);
});
``` ```
......
...@@ -31,7 +31,7 @@ ...@@ -31,7 +31,7 @@
**字体像素单位:fp** **字体像素单位:fp**
字体像素(font pixel) 大小默认情况下与 vp 相同,即默认情况下 1 fp = 1vp。如果用户在设置中选择了更大的字体,字体的实际显示大小就会在 vp 的基础上乘以 scale 系数,即 1 fp = 1 vp \* scale。 字体像素(font pixel) 大小默认情况下与 vp 相同,即默认情况下 1 fp = 1vp。
**视觉属性:分层参数** **视觉属性:分层参数**
......
...@@ -321,6 +321,94 @@ XComponent({ id: 'xcomponentId1', type: 'surface', libraryname: 'nativerender' } ...@@ -321,6 +321,94 @@ XComponent({ id: 'xcomponentId1', type: 'surface', libraryname: 'nativerender' }
render->OnKeyEvent(component, window); render->OnKeyEvent(component, window);
} }
} }
// 定义一个OnSurfaceChanged()方法
void PluginRender::OnSurfaceChanged(OH_NativeXComponent* component, void* window)
{
// ...
std::string id(idStr);
PluginRender* render = PluginRender::GetInstance(id);
double offsetX;
double offsetY;
// 获取XComponent持有的surface相对窗口左上角的偏移量
OH_NativeXComponent_GetXComponentOffset(component, window, &offsetX, &offsetY);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "OH_NativeXComponent_GetXComponentOffset",
"offsetX = %{public}lf, offsetY = %{public}lf", offsetX, offsetY);
uint64_t width;
uint64_t height;
OH_NativeXComponent_GetXComponentSize(component, window, &width, &height);
if (render != nullptr) {
render->eglCore_->UpdateSize(width, height);
}
}
// 定义一个OnTouchEvent()方法
void PluginRender::OnTouchEvent(OH_NativeXComponent* component, void* window)
{
// ...
OH_NativeXComponent_TouchEvent touchEvent;
// 获取由XComponent触发的触摸事件
OH_NativeXComponent_GetTouchEvent(component, window, &touchEvent);
std::string id(idStr);
PluginRender* render = PluginRender::GetInstance(id);
if (render != nullptr && touchEvent.type == OH_NativeXComponent_TouchEventType::OH_NATIVEXCOMPONENT_UP) {
render->eglCore_->ChangeColor();
hasChangeColor_ = 1;
}
float tiltX = 0.0f;
float tiltY = 0.0f;
OH_NativeXComponent_TouchPointToolType toolType =
OH_NativeXComponent_TouchPointToolType::OH_NATIVEXCOMPONENT_TOOL_TYPE_UNKNOWN;
// 获取XComponent触摸点的工具类型
OH_NativeXComponent_GetTouchPointToolType(component, 0, &toolType);
// 获取XComponent触摸点处相对X轴的倾斜角度
OH_NativeXComponent_GetTouchPointTiltX(component, 0, &tiltX);
// 获取XComponent触摸点处相对Y轴的倾斜角度
OH_NativeXComponent_GetTouchPointTiltY(component, 0, &tiltY);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "OnTouchEvent",
"touch info: toolType = %{public}d, tiltX = %{public}lf, tiltY = %{public}lf", toolType, tiltX, tiltY);
}
// 定义一个OnMouseEvent()方法
void PluginRender::OnMouseEvent(OH_NativeXComponent *component, void *window) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "OnMouseEvent");
OH_NativeXComponent_MouseEvent mouseEvent;
// 获取由XComponent触发的鼠标事件
int32_t ret = OH_NativeXComponent_GetMouseEvent(component, window, &mouseEvent);
if (ret == OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "MouseEvent Info: x = %{public}f, y = %{public}f, action = %{public}d, button = %{public}d", mouseEvent.x, mouseEvent.y, mouseEvent.action, mouseEvent.button);
} else {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "GetMouseEvent error");
}
}
// 定义一个OnMouseEvent()方法
void PluginRender::OnKeyEvent(OH_NativeXComponent *component, void *window) {
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "OnKeyEvent");
OH_NativeXComponent_KeyEvent *keyEvent = nullptr;
// 获取由XComponent触发的按键事件。
if (OH_NativeXComponent_GetKeyEvent(component, &keyEvent) >= 0) {
OH_NativeXComponent_KeyAction action;
// 获取按键事件的动作
OH_NativeXComponent_GetKeyEventAction(keyEvent, &action);
OH_NativeXComponent_KeyCode code;
// 获取按键事件的键码值
OH_NativeXComponent_GetKeyEventCode(keyEvent, &code);
OH_NativeXComponent_EventSourceType sourceType;
// 获取按键事件的输入源类型
OH_NativeXComponent_GetKeyEventSourceType(keyEvent, &sourceType);
int64_t deviceId;
// 获取按键事件的设备ID
OH_NativeXComponent_GetKeyEventDeviceId(keyEvent, &deviceId);
int64_t timeStamp;
// 获取按键事件的时间戳
OH_NativeXComponent_GetKeyEventTimestamp(keyEvent, &timeStamp);
OH_LOG_Print(LOG_APP, LOG_INFO, LOG_PRINT_DOMAIN, "PluginRender", "KeyEvent Info: action=%{public}d, code=%{public}d, sourceType=%{public}d, deviceId=%{public}ld, timeStamp=%{public}ld", action, code, sourceType, deviceId, timeStamp);
} else {
OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_PRINT_DOMAIN, "PluginRender", "GetKeyEvent error");
}
}
``` ```
(2) 注册XComponent事件回调函数,在XComponent事件触发时调用3.1步骤中定义的方法。 (2) 注册XComponent事件回调函数,在XComponent事件触发时调用3.1步骤中定义的方法。
......
...@@ -358,6 +358,7 @@ ...@@ -358,6 +358,7 @@
- [@ohos.systemDateTime (系统时间、时区)](js-apis-system-date-time.md) - [@ohos.systemDateTime (系统时间、时区)](js-apis-system-date-time.md)
- [@ohos.systemTimer (系统定时器)](js-apis-system-timer.md) - [@ohos.systemTimer (系统定时器)](js-apis-system-timer.md)
- [@ohos.wallpaper (壁纸)](js-apis-wallpaper.md) - [@ohos.wallpaper (壁纸)](js-apis-wallpaper.md)
- [@ohos.WallpaperExtensionAbility (WallpaperExtensionAbility)](js-apis-WallpaperExtensionAbility.md)
- [@ohos.web.webview (Webview)](js-apis-webview.md) - [@ohos.web.webview (Webview)](js-apis-webview.md)
- [console (控制台)](js-apis-logs.md) - [console (控制台)](js-apis-logs.md)
- [Timer (定时器)](js-apis-timer.md) - [Timer (定时器)](js-apis-timer.md)
...@@ -423,6 +424,7 @@ ...@@ -423,6 +424,7 @@
- [@ohos.enterprise.deviceSettings (设备设置管理)](js-apis-enterprise-deviceSettings.md) - [@ohos.enterprise.deviceSettings (设备设置管理)](js-apis-enterprise-deviceSettings.md)
- [@ohos.enterprise.EnterpriseAdminExtensionAbility (企业设备管理扩展能力)](js-apis-EnterpriseAdminExtensionAbility.md) - [@ohos.enterprise.EnterpriseAdminExtensionAbility (企业设备管理扩展能力)](js-apis-EnterpriseAdminExtensionAbility.md)
- [@ohos.enterprise.networkManager (网络管理)](js-apis-enterprise-networkManager.md) - [@ohos.enterprise.networkManager (网络管理)](js-apis-enterprise-networkManager.md)
- [@ohos.enterprise.restrictions (限制类策略)](js-apis-enterprise-restrictions.md)
- [@ohos.enterprise.wifiManager (WiFi管理)](js-apis-enterprise-wifiManager.md) - [@ohos.enterprise.wifiManager (WiFi管理)](js-apis-enterprise-wifiManager.md)
- 语言基础类库 - 语言基础类库
......
...@@ -646,7 +646,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -646,7 +646,7 @@ SystemCapability.BundleManager.BundleFramework
```ts ```ts
let bundleName = "com.example.myapplication"; let bundleName = "com.example.myapplication";
bundleManager.setApplicationEnabled(bundleName, false).then(()=> { bundle.setApplicationEnabled(bundleName, false).then(()=> {
console.info('setApplicationEnabled successfully.'); console.info('setApplicationEnabled successfully.');
}).catch(err=> { }).catch(err=> {
console.error('setApplicationEnabled failed.'); console.error('setApplicationEnabled failed.');
...@@ -767,7 +767,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -767,7 +767,7 @@ SystemCapability.BundleManager.BundleFramework
```ts ```ts
let permission = "ohos.permission.GET_BUNDLE_INFO"; let permission = "ohos.permission.GET_BUNDLE_INFO";
bundleManager.getPermissionDef(permission, (err, data) => { bundle.getPermissionDef(permission, (err, data) => {
if (err) { if (err) {
console.error('getPermissionDef failed:' + err.message); console.error('getPermissionDef failed:' + err.message);
} else { } else {
......
...@@ -13,6 +13,8 @@ Ability模块将二级模块API组织在一起方便开发者进行导出。 ...@@ -13,6 +13,8 @@ Ability模块将二级模块API组织在一起方便开发者进行导出。
import ability from '@ohos.ability.ability'; import ability from '@ohos.ability.ability';
``` ```
## 属性
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
| 名称 | 类型 | 描述 | | 名称 | 类型 | 描述 |
......
...@@ -31,8 +31,8 @@ import config from '@ohos.accessibility.config'; ...@@ -31,8 +31,8 @@ import config from '@ohos.accessibility.config';
| shortkeyTarget | [Config](#config)\<string>| 是 | 是 | 表示辅助扩展快捷键的目标配置。取值为辅助应用的名称,格式为:'bundleName/abilityName'。 | | shortkeyTarget | [Config](#config)\<string>| 是 | 是 | 表示辅助扩展快捷键的目标配置。取值为辅助应用的名称,格式为:'bundleName/abilityName'。 |
| captions | [Config](#config)\<boolean>| 是 | 是 | 表示辅助字幕功能启用状态。 | | captions | [Config](#config)\<boolean>| 是 | 是 | 表示辅助字幕功能启用状态。 |
| captionsStyle | [Config](#config)\<[accessibility.CaptionsStyle](js-apis-accessibility.md#captionsstyle8)>| 是 | 是 | 表示辅助字幕的配置。 | | captionsStyle | [Config](#config)\<[accessibility.CaptionsStyle](js-apis-accessibility.md#captionsstyle8)>| 是 | 是 | 表示辅助字幕的配置。 |
| audioMono| [Config](#config)\<boolean>| 是 | 是 | 表示音频单声道的配置。True表示打开单声道,False表示关闭单声道。 | | audioMono<sup>10+</sup>| [Config](#config)\<boolean>| 是 | 是 | 表示音频单声道的配置。True表示打开单声道,False表示关闭单声道。 |
| audioBalance| [Config](#config)\<number>| 是 | 是 | 表示左右声道音量平衡的配置。取值 -1.0~1.0。 | | audioBalance<sup>10+</sup>| [Config](#config)\<number>| 是 | 是 | 表示左右声道音量平衡的配置。取值 -1.0~1.0。 |
## enableAbility ## enableAbility
......
...@@ -14,7 +14,7 @@ import common from '@ohos.app.ability.common'; ...@@ -14,7 +14,7 @@ import common from '@ohos.app.ability.common';
``` ```
## 属性 ## 属性
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 类型 | 说明 | | 名称 | 类型 | 说明 |
| ----------- | -------------------- | ------------------------------------------------------------ | | ----------- | -------------------- | ------------------------------------------------------------ |
......
...@@ -21,7 +21,6 @@ import DriverExtension from '@ohos.app.ability.DriverExtensionAbility'; ...@@ -21,7 +21,6 @@ import DriverExtension from '@ohos.app.ability.DriverExtensionAbility';
**系统能力**:SystemCapability.Driver.ExternalDevice **系统能力**:SystemCapability.Driver.ExternalDevice
**系统API**: 此接口为系统接口,三方应用不支持调用。
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
......
...@@ -64,21 +64,13 @@ applyQuickFix(hapModuleQuickFixFiles: Array\<string>, callback: AsyncCallback\<v ...@@ -64,21 +64,13 @@ applyQuickFix(hapModuleQuickFixFiles: Array\<string>, callback: AsyncCallback\<v
**错误码** **错误码**
在打补丁过程中发生的错误,其错误码及错误信息通过公共事件[COMMON_EVENT_QUICK_FIX_APPLY_RESULT](commonEvent-definitions.md#common_event_quick_fix_apply_result9)的参数返回给应用开发者。
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| ------- | -------- | | ------- | -------- |
| 18500002 | The specified quick fix is invalid. It may not exist or inaccessible. | | 18500002 | The specified quick fix is invalid. It may not exist or inaccessible. |
| 18500008 | Internal error. | | 18500008 | Internal error. |
在打补丁过程中发生的错误,其错误码及错误信息通过公共事件[COMMON_EVENT_QUICK_FIX_APPLY_RESULT](commonEvent-definitions.md#common_event_quick_fix_apply_result9)的参数返回给应用开发者。这部分错误码及错误信息如下:
| 错误码ID | 错误信息 |
| ------- | -------- |
| 18500003 | Deploy hqf failed. |
| 18500004 | Switch hqf failed. |
| 18500005 | Delete hqf failed. |
| 18500006 | Load patch failed. |
| 18500007 | Unload patch failed. |
以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) 以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)
> 说明:调用applyQuickFix接口时,补丁文件所在路径为应用沙箱路径。沙箱路径的获取参考[获取应用的沙箱路径](js-apis-bundle-BundleInstaller.md#获取应用的沙箱路径),映射到设备上的路径为/proc/&lt;应用进程Id&gt;/root/沙箱路径。 > 说明:调用applyQuickFix接口时,补丁文件所在路径为应用沙箱路径。沙箱路径的获取参考[获取应用的沙箱路径](js-apis-bundle-BundleInstaller.md#获取应用的沙箱路径),映射到设备上的路径为/proc/&lt;应用进程Id&gt;/root/沙箱路径。
...@@ -126,21 +118,13 @@ applyQuickFix(hapModuleQuickFixFiles: Array\<string>): Promise\<void>; ...@@ -126,21 +118,13 @@ applyQuickFix(hapModuleQuickFixFiles: Array\<string>): Promise\<void>;
**错误码** **错误码**
在打补丁过程中发生的错误,其错误码及错误信息通过公共事件[COMMON_EVENT_QUICK_FIX_APPLY_RESULT](commonEvent-definitions.md#common_event_quick_fix_apply_result9)的参数返回给应用开发者。
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| ------- | -------- | | ------- | -------- |
| 18500002 | The specified quick fix is invalid. It may not exist or inaccessible. | | 18500002 | The specified quick fix is invalid. It may not exist or inaccessible. |
| 18500008 | Internal error. | | 18500008 | Internal error. |
在打补丁过程中发生的错误,其错误码及错误信息通过公共事件[COMMON_EVENT_QUICK_FIX_APPLY_RESULT](commonEvent-definitions.md#common_event_quick_fix_apply_result9)的参数返回给应用开发者。这部分错误码及错误信息如下:
| 错误码ID | 错误信息 |
| ------- | -------- |
| 18500003 | Deploy hqf failed. |
| 18500004 | Switch hqf failed. |
| 18500005 | Delete hqf failed. |
| 18500006 | Load patch failed. |
| 18500007 | Unload patch failed. |
以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md) 以上错误码详细介绍请参考[errcode-ability](../errorcodes/errorcode-ability.md)
**示例:** **示例:**
...@@ -279,13 +263,7 @@ revokeQuickFix(bundleName: string, callback: AsyncCallback\<void>): void; ...@@ -279,13 +263,7 @@ revokeQuickFix(bundleName: string, callback: AsyncCallback\<void>): void;
| 18500001 | The bundle is not exist or no patch has applied. | | 18500001 | The bundle is not exist or no patch has applied. |
| 18500009 | The application has a apply quick fix task that is being processed. | | 18500009 | The application has a apply quick fix task that is being processed. |
在撤销补丁过程中发生的错误,其错误码及错误信息通过公共事件[COMMON_EVENT_QUICK_FIX_REVOKE_RESULT](./common_event/commonEvent-ability.md#common_event_quick_fix_revoke_result10)的参数返回给应用开发者。这部分错误码及错误信息如下: 在撤销补丁过程中发生的错误,其错误码及错误信息通过公共事件[COMMON_EVENT_QUICK_FIX_REVOKE_RESULT](./common_event/commonEvent-ability.md#common_event_quick_fix_revoke_result10)的参数返回给应用开发者。
| 错误码ID | 错误信息 |
| ------- | -------- |
| 18500004 | Switch hqf failed. |
| 18500005 | Delete hqf failed. |
| 18500007 | Unload patch failed. |
**示例:** **示例:**
......
...@@ -171,6 +171,7 @@ import Want from '@ohos.app.ability.Want'; ...@@ -171,6 +171,7 @@ import Want from '@ohos.app.ability.Want';
```ts ```ts
// (1) UIAbility1启动一个ServiceExtension // (1) UIAbility1启动一个ServiceExtension
import common from '@ohos.app.ability.common';
let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext let context = getContext(this) as common.UIAbilityContext; // UIAbilityContext
let want = { let want = {
bundleName: 'com.example.myapplication1', bundleName: 'com.example.myapplication1',
......
...@@ -75,14 +75,3 @@ try { ...@@ -75,14 +75,3 @@ try {
console.error(`catch error, code: ${error.code}, message: ${error.message}`); console.error(`catch error, code: ${error.code}, message: ${error.message}`);
} }
``` ```
## ProxyData
定义表单代理数据。
**系统能力**:SystemCapability.Ability.Form
| 名称 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| key | string | 是 | 代理的密钥。值取决于数据发布者。|
| subscriberId | string | 否 | 订阅者ID。值取决于数据发布者。默认值为当前卡片ID。|
\ No newline at end of file
...@@ -169,6 +169,8 @@ import formInfo from '@ohos.app.form.formInfo'; ...@@ -169,6 +169,8 @@ import formInfo from '@ohos.app.form.formInfo';
**系统能力**:SystemCapability.Ability.Form **系统能力**:SystemCapability.Ability.Form
**系统API**: 此接口为系统接口,三方应用不支持调用。
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| ----------- | -------- | -------- | -------------------- | ------------------------------------------------------------ | | ----------- | -------- | -------- | -------------------- | ------------------------------------------------------------ |
| bundleName | string | 是 | 否 | 提供方卡片所属包的Bundle名称。 | | bundleName | string | 是 | 否 | 提供方卡片所属包的Bundle名称。 |
......
...@@ -57,13 +57,23 @@ onStartAuthorization(request: AuthorizationRequest, callback: AuthorizationCallb ...@@ -57,13 +57,23 @@ onStartAuthorization(request: AuthorizationRequest, callback: AuthorizationCallb
**示例:** **示例:**
```ts ```ts
import appAccount from '@ohos.account.appAccount';
class MyResponse extends appAccount.AccountCapabilityResponse {
name: string;
scopes: string[];
constructor(request: appAccount.AccountCapabilityRequest) {
super(request);
}
};
class MyAuthorizationExtensionAbility extends AuthorizationExtensionAbility { class MyAuthorizationExtensionAbility extends AuthorizationExtensionAbility {
onStartAuthorization(request: AuthorizationRequest, callback: AuthorizationCallback) { onStartAuthorization(request: AuthorizationRequest, callback: AuthorizationCallback) {
console.log('onStartAuthorization, callerUid: ' + request.callerUid + ', parameters: ' + request.parameters); console.log('onStartAuthorization, callerUid: ' + request.callerUid + ', parameters: ' + request.parameters);
let response = { let response = new MyResponse(null);
name: 'xxxx', response.name = 'xxx';
scopes: ['xxx', 'xxx'] response.scopes = ['xxx', 'xxx'];
};
callback.onResult(null, response); callback.onResult(null, response);
} }
}; };
......
...@@ -37,7 +37,7 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void; ...@@ -37,7 +37,7 @@ startAbility(want: Want, callback: AsyncCallback&lt;void&gt;): void;
- 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限
- 跨应用场景下,目标Ability的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 跨应用场景下,目标Ability的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限
**需要权限**:ohos.permission.CLEAN_BACKGROUND_PROCESSES **需要权限**:ohos.permission.START_ABILITIES_FROM_BACKGROUND
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **系统能力**:SystemCapability.Ability.AbilityRuntime.Core
...@@ -106,7 +106,7 @@ startAbility(want: Want): Promise&lt;void&gt;; ...@@ -106,7 +106,7 @@ startAbility(want: Want): Promise&lt;void&gt;;
- 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限 - 调用方应用位于后台时,使用该接口启动Ability需申请`ohos.permission.START_ABILITIES_FROM_BACKGROUND`权限
- 跨应用场景下,目标Ability的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限 - 跨应用场景下,目标Ability的visible属性若配置为false,调用方应用需申请`ohos.permission.START_INVISIBLE_ABILITY`权限
**需要权限**:ohos.permission.CLEAN_BACKGROUND_PROCESSES **需要权限**:ohos.permission.START_ABILITIES_FROM_BACKGROUND
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **系统能力**:SystemCapability.Ability.AbilityRuntime.Core
......
...@@ -404,7 +404,7 @@ killProcessWithAccount(bundleName: string, accountId: number): Promise\<void\> ...@@ -404,7 +404,7 @@ killProcessWithAccount(bundleName: string, accountId: number): Promise\<void\>
> >
> 当accountId为当前用户时,不需要校验ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS权限。 > 当accountId为当前用户时,不需要校验ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS权限。
**需要权限**:ohos.permission.CLEAN_BACKGROUND_PROCESSES, ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS **需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS, ohos.permission.CLEAN_BACKGROUND_PROCESSES
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **系统能力**:SystemCapability.Ability.AbilityRuntime.Core
...@@ -446,7 +446,7 @@ killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCal ...@@ -446,7 +446,7 @@ killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCal
**系统API**: 此接口为系统接口,三方应用不支持调用。 **系统API**: 此接口为系统接口,三方应用不支持调用。
**需要权限**:ohos.permission.CLEAN_BACKGROUND_PROCESSES, ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS **需要权限**:ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS, ohos.permission.CLEAN_BACKGROUND_PROCESSES
**参数:** **参数:**
......
...@@ -4862,10 +4862,10 @@ async function getCacheDir(){ ...@@ -4862,10 +4862,10 @@ async function getCacheDir(){
} }
let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; let filePath = path + '/StarWars10s-2C-48000-4SW.wav';
let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
let currStat = await fs.stat(path); fs.stat(path).then((stat) => {
let buf = new ArrayBuffer(bufferSize); let buf = new ArrayBuffer(bufferSize);
let len = currStat.size % bufferSize == 0 ? Math.floor(currStat.size / bufferSize) : Math.floor(currStat.size / bufferSize + 1); let len = stat.size % bufferSize == 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1);
for (let i = 0;i < len; i++) { for (let i = 0;i < len; i++) {
let options = { let options = {
offset: i * bufferSize, offset: i * bufferSize,
length: bufferSize length: bufferSize
...@@ -4880,7 +4880,9 @@ for (let i = 0;i < len; i++) { ...@@ -4880,7 +4880,9 @@ for (let i = 0;i < len; i++) {
} }
}) })
}) })
} }
});
``` ```
...@@ -4916,10 +4918,10 @@ async function getCacheDir(){ ...@@ -4916,10 +4918,10 @@ async function getCacheDir(){
} }
let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; let filePath = path + '/StarWars10s-2C-48000-4SW.wav';
let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY); let file = fs.openSync(filePath, fs.OpenMode.READ_ONLY);
let currStat = await fs.stat(path); fs.stat(path).then((stat) => {
let buf = new ArrayBuffer(bufferSize); let buf = new ArrayBuffer(bufferSize);
let len = currStat.size % bufferSize == 0 ? Math.floor(currStat.size / bufferSize) : Math.floor(currStat.size / bufferSize + 1); let len = stat.size % bufferSize == 0 ? Math.floor(stat.size / bufferSize) : Math.floor(stat.size / bufferSize + 1);
for (let i = 0;i < len; i++) { for (let i = 0;i < len; i++) {
let options = { let options = {
offset: i * bufferSize, offset: i * bufferSize,
length: bufferSize length: bufferSize
...@@ -4930,7 +4932,8 @@ for (let i = 0;i < len; i++) { ...@@ -4930,7 +4932,8 @@ for (let i = 0;i < len; i++) {
} catch(err) { } catch(err) {
console.error(`audioRenderer.write err: ${err}`); console.error(`audioRenderer.write err: ${err}`);
} }
} }
});
``` ```
### getAudioTime<sup>8+</sup> ### getAudioTime<sup>8+</sup>
......
...@@ -9,7 +9,7 @@ ...@@ -9,7 +9,7 @@
**系统接口:** 此接口为系统接口。 **系统接口:** 此接口为系统接口。
**系统能力**: SystemCapability.BundleManager.BundleFramework.Core **系统能力**: SystemCapability.Ability.AbilityRuntime.Core
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| --------------------------------- | ------------------------------------------------------------ | ---- | ---- | -------------------- | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | -------------------- |
......
...@@ -15,8 +15,8 @@ import bundleManager from '@ohos.bundle.bundleManager'; ...@@ -15,8 +15,8 @@ import bundleManager from '@ohos.bundle.bundleManager';
| 权限 | 权限等级 | 描述 | | 权限 | 权限等级 | 描述 |
| ------------------------------------------ | ------------ | ------------------| | ------------------------------------------ | ------------ | ------------------|
| ohos.permission.GET_BUNDLE_INFO | normal | 查询指定应用信息。 | | ohos.permission.GET_BUNDLE_INFO | normal | 允许查询应用的基本信息。 |
| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | 可查询所有应用信息。 | | ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | 允许查询应用的基本信息和其他敏感信息。 |
| ohos.permission.REMOVE_CACHE_FILES | system_basic | 清理应用缓存。 | | ohos.permission.REMOVE_CACHE_FILES | system_basic | 清理应用缓存。 |
|ohos.permission.CHANGE_ABILITY_ENABLED_STATE| system_basic | 设置禁用使能所需的权限。 | |ohos.permission.CHANGE_ABILITY_ENABLED_STATE| system_basic | 设置禁用使能所需的权限。 |
| ohos.permission.GET_INSTALLED_BUNDLE_LIST | system_basic | 读取已安装应用列表。 | | ohos.permission.GET_INSTALLED_BUNDLE_LIST | system_basic | 读取已安装应用列表。 |
......
...@@ -41,7 +41,7 @@ import bundleMonitor from '@ohos.bundle.bundleMonitor'; ...@@ -41,7 +41,7 @@ import bundleMonitor from '@ohos.bundle.bundleMonitor';
| 名称 | 说明 | | 名称 | 说明 |
| ---------- | --------------- | | ---------- | --------------- |
| app | 监听应用事件。 | | add | 监听应用事件。 |
| update | 监听更新事件。 | | update | 监听更新事件。 |
| remove | 监听删除事件。 | | remove | 监听删除事件。 |
......
...@@ -26,7 +26,7 @@ import businessAbilityRouter from '@ohos.app.businessAbilityRouter'; ...@@ -26,7 +26,7 @@ import businessAbilityRouter from '@ohos.app.businessAbilityRouter';
此枚举值用于标识过滤条件类型。 此枚举值用于标识过滤条件类型。
**系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework.Core **系统能力:** 以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
**系统API:** 此接口为系统接口。 **系统API:** 此接口为系统接口。
...@@ -39,7 +39,7 @@ import businessAbilityRouter from '@ohos.app.businessAbilityRouter'; ...@@ -39,7 +39,7 @@ import businessAbilityRouter from '@ohos.app.businessAbilityRouter';
此过滤值用于过滤查询的ability类型。 此过滤值用于过滤查询的ability类型。
**系统能力:** SystemCapability.BundleManager.BundleFramework.Core **系统能力:** SystemCapability.Ability.AbilityRuntime.Core
**系统API:** 此接口为系统接口。 **系统API:** 此接口为系统接口。
...@@ -57,7 +57,7 @@ queryBusinessAbilityInfo(filter: BusinessAbilityFilter, callback: AsyncCallback\ ...@@ -57,7 +57,7 @@ queryBusinessAbilityInfo(filter: BusinessAbilityFilter, callback: AsyncCallback\
**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**系统能力:** SystemCapability.BundleManager.BundleFramework.Core **系统能力:** SystemCapability.Ability.AbilityRuntime.Core
**系统API:** 此接口为系统接口。 **系统API:** 此接口为系统接口。
...@@ -94,7 +94,7 @@ queryBusinessAbilityInfo(filter: BusinessAbilityFilter): Promise\<Array\<Busines ...@@ -94,7 +94,7 @@ queryBusinessAbilityInfo(filter: BusinessAbilityFilter): Promise\<Array\<Busines
**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
**系统能力:** SystemCapability.BundleManager.BundleFramework.Core **系统能力:** SystemCapability.Ability.AbilityRuntime.Core
**系统API:** 此接口为系统接口。 **系统API:** 此接口为系统接口。
......
...@@ -2870,7 +2870,7 @@ getModifyTime(table: string, columnName: string, primaryKeys: PRIKeyType[], call ...@@ -2870,7 +2870,7 @@ getModifyTime(table: string, columnName: string, primaryKeys: PRIKeyType[], call
```js ```js
let PRIKey = [1, 4, 2, 3]; let PRIKey = [1, 4, 2, 3];
relationalStore.getModifyTime("cloud_tasks", "uuid", PRIKey, function (err, modifyTime) { store.getModifyTime("cloud_tasks", "uuid", PRIKey, function (err, modifyTime) {
if (err) { if (err) {
console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`); console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`);
return; return;
...@@ -2913,7 +2913,7 @@ getModifyTime(table: string, columnName: string, primaryKeys: PRIKeyType[]): Pro ...@@ -2913,7 +2913,7 @@ getModifyTime(table: string, columnName: string, primaryKeys: PRIKeyType[]): Pro
```js ```js
let PRIKey = [1, 2, 3]; let PRIKey = [1, 2, 3];
relationalStore.getModifyTime("cloud_tasks", "uuid", PRIKey).then((modifyTime) => { store.getModifyTime("cloud_tasks", "uuid", PRIKey).then((modifyTime) => {
let size = modifyTime.size(); let size = modifyTime.size();
}).catch((err) => { }).catch((err) => {
console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`); console.error(`getModifyTime failed, code is ${err.code},message is ${err.message}`);
...@@ -3592,7 +3592,7 @@ cloudSync(mode: SyncMode, progress: Callback&lt;ProgressDetails&gt;, callback: A ...@@ -3592,7 +3592,7 @@ cloudSync(mode: SyncMode, progress: Callback&lt;ProgressDetails&gt;, callback: A
**示例:** **示例:**
```js ```js
relationalStore.cloudSync(relatioanalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, function (progressDetails) { relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, function (progressDetails) {
console.info(`Progess: ${progressDetails}`); console.info(`Progess: ${progressDetails}`);
}, function (err) { }, function (err) {
if (err) { if (err) {
...@@ -3633,7 +3633,7 @@ function progress(progressDetail) { ...@@ -3633,7 +3633,7 @@ function progress(progressDetail) {
console.info(`progress: ${progressDetail}`); console.info(`progress: ${progressDetail}`);
} }
relationalStore.cloudSync(relatioanalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, progress).then(() => { relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, progress).then(() => {
console.info('Cloud sync succeeded'); console.info('Cloud sync succeeded');
}).catch((err) => { }).catch((err) => {
console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`); console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`);
...@@ -3663,7 +3663,7 @@ cloudSync(mode: SyncMode, tables: string[], progress: Callback&lt;ProgressDetail ...@@ -3663,7 +3663,7 @@ cloudSync(mode: SyncMode, tables: string[], progress: Callback&lt;ProgressDetail
```js ```js
const tables = ["table1", "table2"]; const tables = ["table1", "table2"];
relationalStore.cloudSync(relatioanalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, function (progressDetails) { relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, function (progressDetails) {
console.info(`Progess: ${progressDetails}`); console.info(`Progess: ${progressDetails}`);
}, function (err) { }, function (err) {
if (err) { if (err) {
...@@ -3706,7 +3706,7 @@ function progress(progressDetail) { ...@@ -3706,7 +3706,7 @@ function progress(progressDetail) {
console.info(`progress: ${progressDetail}`); console.info(`progress: ${progressDetail}`);
} }
relationalStore.cloudSync(relatioanalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, progress).then(() => { relationalStore.cloudSync(relationalStore.SyncMode.SYNC_MODE_CLOUD_FIRST, tables, progress).then(() => {
console.info('Cloud sync succeeded'); console.info('Cloud sync succeeded');
}).catch((err) => { }).catch((err) => {
console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`); console.error(`cloudSync failed, code is ${err.code},message is ${err.message}`);
......
...@@ -22,7 +22,7 @@ SystemCapability.BundleManager.DistributedBundleFramework ...@@ -22,7 +22,7 @@ SystemCapability.BundleManager.DistributedBundleFramework
| 权限 | 权限等级 | 说明 | | 权限 | 权限等级 | 说明 |
| ------------------------------------------ | ------------ | ------------------ | | ------------------------------------------ | ------------ | ------------------ |
| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | 可查询系统中所有应用信息。 | | ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | 允许查询应用的基本信息和其他敏感信息。 |
权限等级参考[权限等级说明](../../security/accesstoken-overview.md#权限等级说明) 权限等级参考[权限等级说明](../../security/accesstoken-overview.md#权限等级说明)
......
...@@ -78,10 +78,9 @@ emitter.once(innerEvent, emitterCallback); ...@@ -78,10 +78,9 @@ emitter.once(innerEvent, emitterCallback);
## emitter.off ## emitter.off
off(eventId: number,callback?: Callback\<[EventData](#eventdata)\>): void off(eventId: number): void
取消针对该事件ID的订阅。如果不传入可选参数callback,则取消针对该事件ID的所有订阅。 取消针对该事件ID的订阅。
如果传入可选参数callback,并且该callback已经通过on或者once接口订阅,则取消该订阅;否则,不做任何处理。
**系统能力**: `SystemCapability.Notification.Emitter` **系统能力**: `SystemCapability.Notification.Emitter`
...@@ -90,7 +89,6 @@ off(eventId: number,callback?: Callback\<[EventData](#eventdata)\>): void ...@@ -90,7 +89,6 @@ off(eventId: number,callback?: Callback\<[EventData](#eventdata)\>): void
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------ | | ------- | ------ | ---- | ------ |
| eventId | number | 是 | 事件ID | | eventId | number | 是 | 事件ID |
| callback<sup>10+</sup> | Callback\<[EventData](#eventdata)\> | 否 | API version 10 新增取消该事件的回调处理函数。该参数可选,不影响API version 9 及更早版本的接口兼容性 |
**示例:** **示例:**
...@@ -99,6 +97,23 @@ off(eventId: number,callback?: Callback\<[EventData](#eventdata)\>): void ...@@ -99,6 +97,23 @@ off(eventId: number,callback?: Callback\<[EventData](#eventdata)\>): void
emitter.off(1); emitter.off(1);
``` ```
## emitter.off<sup>10+<sup>
off(eventId: number,callback: Callback\<[EventData](#eventdata)\>): void
取消针对该事件ID的订阅,传入可选参数callback,并且该callback已经通过on或者once接口订阅,则取消该订阅;否则,不做任何处理。
**系统能力**: `SystemCapability.Notification.Emitter`
**参数:**
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ------ |
| eventId | number | 是 | 事件ID |
| callback<sup>10+</sup> | Callback\<[EventData](#eventdata)\> | 是 | API version 10 新增取消该事件的回调处理函数。 |
**示例:**
```javascript ```javascript
// 取消eventID为1的事件回调处理函数 emitterCallback // 取消eventID为1的事件回调处理函数 emitterCallback
// 如果该回调处理函数没有被订阅,则不做任何处理 // 如果该回调处理函数没有被订阅,则不做任何处理
......
...@@ -16,8 +16,8 @@ import ability from '@ohos.ability.ability'; ...@@ -16,8 +16,8 @@ import ability from '@ohos.ability.ability';
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
| 名称 | 可读 | 可写 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| ----------- | -------- |-------- | -------------------- | ---- | ------------------------------------------------------------ | | ----------- | -------------------- | ---- | ------------------------------------------------------------ |
| resultCode | 是 | 是 | number | 是 | 表示Ability被拉起并退出后返回的结果码。 | | resultCode | number | 是 | 表示Ability被拉起并退出后返回的结果码。 |
| want | 是 | 是 | [Want](./js-apis-app-ability-want.md) | 否 | 表示Ability被拉起并退出后返回的数据。 | | want | [Want](./js-apis-app-ability-want.md) | 否 | 表示Ability被拉起并退出后返回的数据。 |
...@@ -16,7 +16,7 @@ import common from '@ohos.app.ability.common'; ...@@ -16,7 +16,7 @@ import common from '@ohos.app.ability.common';
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
| 参数名 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| ------------ | -------- | ---- | ------------------------- | | ------------ | -------- | ---- | ------------------------- |
| onConnect<sup>7+</sup> | function | 是 | 建立连接时的回调函数。 | | onConnect<sup>7+</sup> | function | 是 | 建立连接时的回调函数。 |
| onDisconnect<sup>7+</sup> | function | 是 | 断开连接时的回调函数。 | | onDisconnect<sup>7+</sup> | function | 是 | 断开连接时的回调函数。 |
......
...@@ -27,7 +27,7 @@ import Want from '@ohos.app.ability.Want'; ...@@ -27,7 +27,7 @@ import Want from '@ohos.app.ability.Want';
| action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。具体参考:[action说明](js-apis-ability-wantConstant.md#wantconstantaction)。隐式Want定义及匹配规则参考:[显式Want与隐式Want匹配规则](../../application-models/explicit-implicit-want-mappings.md)。 | | action | string | 否 | 表示要执行的通用操作(如:查看、分享、应用详情)。在隐式Want中,您可以定义该字段,配合uri或parameters来表示对数据要执行的操作。具体参考:[action说明](js-apis-ability-wantConstant.md#wantconstantaction)。隐式Want定义及匹配规则参考:[显式Want与隐式Want匹配规则](../../application-models/explicit-implicit-want-mappings.md)。 |
| parameters | {[key: string]: Object} | 否 | 表示WantParams,由开发者自行决定传入的键值对。默认会携带以下key值:<br>ohos.aafwk.callerPid 表示拉起方的pid。<br>ohos.aafwk.param.callerToken 表示拉起方的token。<br>ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo)中的uid,应用包里应用程序的uid。<br />- component.startup.newRules:表示是否启用新的管控规则。<br />- moduleName:表示拉起方的模块名,该字段的值即使定义成其他字符串,在传递到另一端时会被修改为正确的值。<br />- ohos.dlp.params.sandbox:表示dlp文件才会有。 | | parameters | {[key: string]: Object} | 否 | 表示WantParams,由开发者自行决定传入的键值对。默认会携带以下key值:<br>ohos.aafwk.callerPid 表示拉起方的pid。<br>ohos.aafwk.param.callerToken 表示拉起方的token。<br>ohos.aafwk.param.callerUid 表示[bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo)中的uid,应用包里应用程序的uid。<br />- component.startup.newRules:表示是否启用新的管控规则。<br />- moduleName:表示拉起方的模块名,该字段的值即使定义成其他字符串,在传递到另一端时会被修改为正确的值。<br />- ohos.dlp.params.sandbox:表示dlp文件才会有。 |
| entities | Array\<string> | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器),在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。具体参考:[entity说明](js-apis-app-ability-wantConstant.md#wantconstantentity)。 | | entities | Array\<string> | 否 | 表示目标Ability额外的类别信息(如:浏览器、视频播放器),在隐式Want中是对action字段的补充。在隐式Want中,您可以定义该字段,来过滤匹配Ability类型。具体参考:[entity说明](js-apis-app-ability-wantConstant.md#wantconstantentity)。 |
| moduleName<sup>9+</sup> | string | 否 | 表示待启动的Ability所属的模块(module)。 | | moduleName<sup>10+</sup> | string | 否 | 表示待启动的Ability所属的模块(module)。 |
**示例:** **示例:**
......
...@@ -1231,7 +1231,7 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise ...@@ -1231,7 +1231,7 @@ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | 是 | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) 实例 | | monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | 是 | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) 实例 |
| timeout | number | | 超时最大等待时间,以毫秒为单位。 | | timeout | number | | 超时最大等待时间,以毫秒为单位。 |
**返回值:** **返回值:**
......
...@@ -16,6 +16,8 @@ import appManager from '@ohos.application.appManager'; ...@@ -16,6 +16,8 @@ import appManager from '@ohos.application.appManager';
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
**系统API**: 此接口为系统接口,三方应用不支持调用。
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| ----------------------- | ---------| ---- | ---- | ------------------------- | | ----------------------- | ---------| ---- | ---- | ------------------------- |
| pid | number | 是 | 否 | 进程ID。 | | pid | number | 是 | 否 | 进程ID。 |
......
...@@ -12,6 +12,8 @@ ...@@ -12,6 +12,8 @@
import appManager from '@ohos.app.ability.appManager'; import appManager from '@ohos.app.ability.appManager';
``` ```
## 属性
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
**系统API**:本模块被标记为@systemapi,对三方应用隐藏 **系统API**:本模块被标记为@systemapi,对三方应用隐藏
......
...@@ -359,7 +359,7 @@ export default class EntryAbility extends UIAbility { ...@@ -359,7 +359,7 @@ export default class EntryAbility extends UIAbility {
## ApplicationContext.off(type: 'applicationStateChange')<sup>10+</sup> ## ApplicationContext.off(type: 'applicationStateChange')<sup>10+</sup>
off(type: 'applicationStateChange'): **void**; off(type: 'applicationStateChange', callback?: ApplicationStateChangeCallback): **void**;
取消当前应用注册的前后台变化的全部监听。 取消当前应用注册的前后台变化的全部监听。
...@@ -370,6 +370,7 @@ off(type: 'applicationStateChange'): **void**; ...@@ -370,6 +370,7 @@ off(type: 'applicationStateChange'): **void**;
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| ------ | ------------- | ---- | -------------------- | | ------ | ------------- | ---- | -------------------- |
| type | string | 是 | 取消监听事件的类型,必须为'applicationStateChange'。 | | type | string | 是 | 取消监听事件的类型,必须为'applicationStateChange'。 |
| callback | [ApplicationStateChangeCallback](#js-apis-app-ability-applicationStateChangeCallback.md) | 否 | 对于该事件监听的回调方法,可以对应用从后台切换到前台,以及前台切换到后台分别定义回调。 |
**示例:** **示例:**
......
...@@ -12,6 +12,8 @@ ...@@ -12,6 +12,8 @@
import appManager from '@ohos.app.ability.appManager'; import appManager from '@ohos.app.ability.appManager';
``` ```
## 属性
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
**系统API**:该接口为系统接口,三方应用不支持调用。 **系统API**:该接口为系统接口,三方应用不支持调用。
......
...@@ -158,7 +158,7 @@ try { ...@@ -158,7 +158,7 @@ try {
## Context.getGroupDir<sup>10+</sup> ## Context.getGroupDir<sup>10+</sup>
getGroupDir(groupId: string): Promise\<string>; getGroupDir(dataGroupID: string): Promise\<string>;
通过使用元服务应用中的Group ID获取对应的共享目录,使用Promise异步回调。 通过使用元服务应用中的Group ID获取对应的共享目录,使用Promise异步回调。
...@@ -166,9 +166,9 @@ getGroupDir(groupId: string): Promise\<string>; ...@@ -166,9 +166,9 @@ getGroupDir(groupId: string): Promise\<string>;
**参数:** **参数:**
| 名称 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------- | ---- | ------------- | | -------- | ---------------------- | ---- | ------------- |
| groupId | string | 是 | 元服务应用项目创建时,系统会指定分配唯一Group ID。 | | dataGroupID | string | 是 | 元服务应用项目创建时,系统会指定分配唯一Group ID。 |
**返回值:** **返回值:**
...@@ -188,16 +188,19 @@ getGroupDir(groupId: string): Promise\<string>; ...@@ -188,16 +188,19 @@ getGroupDir(groupId: string): Promise\<string>;
```ts ```ts
let groupId = "1"; let groupId = "1";
context.getGroupDir(groupId).then(data => { let getGroupDirContext: common.Context;
try {
getGroupDirContext.getGroupDir(groupId).then(data => {
console.log("getGroupDir result:" + data); console.log("getGroupDir result:" + data);
}).catch((err) => { })
console.error('error: ${JSON.stringify(err)}'); } catch (error) {
}); console.error('getGroupDirContext failed, error.code: ${error.code}, error.message: ${error.message}');
}
``` ```
## Context.getGroupDir<sup>10+</sup> ## Context.getGroupDir<sup>10+</sup>
getGroupDir(groupId: string, callback: AsyncCallback\<string>); getGroupDir(dataGroupID: string, callback: AsyncCallback\<string>);
通过使用元服务应用中的Group ID获取对应的共享目录,使用callback异步回调。 通过使用元服务应用中的Group ID获取对应的共享目录,使用callback异步回调。
...@@ -205,9 +208,9 @@ getGroupDir(groupId: string, callback: AsyncCallback\<string>); ...@@ -205,9 +208,9 @@ getGroupDir(groupId: string, callback: AsyncCallback\<string>);
**参数:** **参数:**
| 名称 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------- | ---- | ------------- | | -------- | ---------------------- | ---- | ------------- |
| groupId | string | 是 | 元服务应用项目创建时,系统会指定分配唯一Group ID。 | | dataGroupID | string | 是 | 元服务应用项目创建时,系统会指定分配唯一Group ID。 |
| callback | AsyncCallback\<string> | 是 | 以callback方式返回对应的共享目录。如果不存在则返回为空,仅支持应用el2加密级别。| | callback | AsyncCallback\<string> | 是 | 以callback方式返回对应的共享目录。如果不存在则返回为空,仅支持应用el2加密级别。|
**错误码** **错误码**
...@@ -221,7 +224,9 @@ getGroupDir(groupId: string, callback: AsyncCallback\<string>); ...@@ -221,7 +224,9 @@ getGroupDir(groupId: string, callback: AsyncCallback\<string>);
**示例:** **示例:**
```ts ```ts
context.getGroupDir("1", (err, data) => { let getGroupDirContext: common.Context;
getGroupDirContext.getGroupDir("1", (err, data) => {
if (err) { if (err) {
console.error('getGroupDir faile, err: ${JSON.stringify(err)}'); console.error('getGroupDir faile, err: ${JSON.stringify(err)}');
} else { } else {
......
...@@ -10,6 +10,8 @@ ...@@ -10,6 +10,8 @@
**系统能力**:SystemCapability.Ability.AbilityRuntime.Mission **系统能力**:SystemCapability.Ability.AbilityRuntime.Mission
**系统API**: 此接口为系统接口,三方应用不支持调用。
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
| -------- | ------ | ---- | ---- | ------- | | -------- | ------ | ---- | ---- | ------- |
| srcDeviceId | string | 是 | 是 | 表示任务迁移源设备ID。 | | srcDeviceId | string | 是 | 是 | 表示任务迁移源设备ID。 |
......
...@@ -13,6 +13,8 @@ ...@@ -13,6 +13,8 @@
import distributedMissionManager from '@ohos.distributedMissionManager'; import distributedMissionManager from '@ohos.distributedMissionManager';
``` ```
## 属性
**系统能力**:SystemCapability.Ability.AbilityRuntime.Mission **系统能力**:SystemCapability.Ability.AbilityRuntime.Mission
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
......
...@@ -28,6 +28,7 @@ import missionManager from '@ohos.app.ability.missionManager'; ...@@ -28,6 +28,7 @@ import missionManager from '@ohos.app.ability.missionManager';
| label | string | 是 | 是 | 表示任务的标签。 | | label | string | 是 | 是 | 表示任务的标签。 |
| iconPath | string | 是 | 是 | 表示任务的图标路径。 | | iconPath | string | 是 | 是 | 表示任务的图标路径。 |
| continuable | boolean | 是 | 是 | 表示任务是否可以迁移。 | | continuable | boolean | 是 | 是 | 表示任务是否可以迁移。 |
| abilityState | number | 是 | 是 | 表示此任务的能力状态。 |
| unclearable<sup>10+</sup> | boolean | 是 | 是 | 表示任务是否可以被用户手动删除。 | | unclearable<sup>10+</sup> | boolean | 是 | 是 | 表示任务是否可以被用户手动删除。 |
**示例:** **示例:**
......
...@@ -16,6 +16,8 @@ import missionManager from '@ohos.app.ability.missionManager'; ...@@ -16,6 +16,8 @@ import missionManager from '@ohos.app.ability.missionManager';
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Mission **系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Mission
**系统API**: 此接口为系统接口,三方应用不支持调用。
| 名称 | 类型 | 必填 | 说明 | | 名称 | 类型 | 必填 | 说明 |
| ----------- | -------- | ---- | ------------------------------------------------------------ | | ----------- | -------- | ---- | ------------------------------------------------------------ |
| onMissionCreated | function | 否 | 表示当系统创建任务时回调执行。 | | onMissionCreated | function | 否 | 表示当系统创建任务时回调执行。 |
......
...@@ -1102,6 +1102,7 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; ...@@ -1102,6 +1102,7 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number;
| 16000001 | The specified ability does not exist. | | 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. | | 16000002 | Incorrect ability type. |
| 16000004 | Can not start invisible component. | | 16000004 | Can not start invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. | | 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. | | 16000008 | The crowdtesting application expires. |
| 16000053 | The ability is not on the top of the UI. | | 16000053 | The ability is not on the top of the UI. |
...@@ -1169,6 +1170,7 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options ...@@ -1169,6 +1170,7 @@ connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options
| 16000001 | The specified ability does not exist. | | 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. | | 16000002 | Incorrect ability type. |
| 16000004 | Can not start invisible component. | | 16000004 | Can not start invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. | | 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. | | 16000008 | The crowdtesting application expires. |
| 16000053 | The ability is not on the top of the UI. | | 16000053 | The ability is not on the top of the UI. |
......
...@@ -116,7 +116,6 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void& ...@@ -116,7 +116,6 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback&lt;void&
**错误码:** **错误码:**
| 错误码ID | 错误信息 |
| 错误码ID | 错误信息 | | 错误码ID | 错误信息 |
| ------- | -------------------------------- | | ------- | -------------------------------- |
| 16000001 | The specified ability does not exist. | | 16000001 | The specified ability does not exist. |
...@@ -276,6 +275,8 @@ startAbilityForResult(want: Want, callback: AsyncCallback&lt;AbilityResult&gt;): ...@@ -276,6 +275,8 @@ startAbilityForResult(want: Want, callback: AsyncCallback&lt;AbilityResult&gt;):
| 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000010 | The call with the continuation flag is forbidden. | | 16000010 | The call with the continuation flag is forbidden. |
| 16000011 | The context does not exist. | | 16000011 | The context does not exist. |
| 16000012 | The application is controlled. |
| 16000013 | The application is controlled by EDM. |
| 16000050 | Internal error. | | 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. | | 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. | | 16000055 | Installation-free timed out. |
...@@ -345,6 +346,8 @@ startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback ...@@ -345,6 +346,8 @@ startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback
| 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000010 | The call with the continuation flag is forbidden. | | 16000010 | The call with the continuation flag is forbidden. |
| 16000011 | The context does not exist. | | 16000011 | The context does not exist. |
| 16000012 | The application is controlled. |
| 16000013 | The application is controlled by EDM. |
| 16000050 | Internal error. | | 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. | | 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. | | 16000055 | Installation-free timed out. |
...@@ -424,6 +427,8 @@ startAbilityForResult(want: Want, options?: StartOptions): Promise&lt;AbilityRes ...@@ -424,6 +427,8 @@ startAbilityForResult(want: Want, options?: StartOptions): Promise&lt;AbilityRes
| 16000009 | An ability cannot be started or stopped in Wukong mode. | | 16000009 | An ability cannot be started or stopped in Wukong mode. |
| 16000010 | The call with the continuation flag is forbidden. | | 16000010 | The call with the continuation flag is forbidden. |
| 16000011 | The context does not exist. | | 16000011 | The context does not exist. |
| 16000012 | The application is controlled. |
| 16000013 | The application is controlled by EDM. |
| 16000050 | Internal error. | | 16000050 | Internal error. |
| 16000053 | The ability is not on the top of the UI. | | 16000053 | The ability is not on the top of the UI. |
| 16000055 | Installation-free timed out. | | 16000055 | Installation-free timed out. |
...@@ -979,6 +984,7 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void; ...@@ -979,6 +984,7 @@ stopServiceExtensionAbility(want: Want, callback: AsyncCallback\<void>): void;
| ------- | -------------------------------- | | ------- | -------------------------------- |
| 16000001 | The specified ability does not exist. | | 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. | | 16000002 | Incorrect ability type. |
| 16000004 | Can not start invisible component. |
| 16000005 | The specified process does not have the permission. | | 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. | | 16000006 | Cross-user operations are not allowed. |
| 16000011 | The context does not exist. | | 16000011 | The context does not exist. |
...@@ -1040,8 +1046,6 @@ stopServiceExtensionAbility(want: Want): Promise\<void>; ...@@ -1040,8 +1046,6 @@ stopServiceExtensionAbility(want: Want): Promise\<void>;
| 16000005 | The specified process does not have the permission. | | 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. | | 16000006 | Cross-user operations are not allowed. |
| 16000011 | The context does not exist. | | 16000011 | The context does not exist. |
| 16000012 | The application is controlled. |
| 16000013 | The application is controlled by EDM. |
| 16000050 | Internal error. | | 16000050 | Internal error. |
| 16200001 | The caller has been released. | | 16200001 | The caller has been released. |
...@@ -1445,6 +1449,7 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; ...@@ -1445,6 +1449,7 @@ connectServiceExtensionAbility(want: Want, options: ConnectOptions): number;
| 16000001 | The specified ability does not exist. | | 16000001 | The specified ability does not exist. |
| 16000002 | Incorrect ability type. | | 16000002 | Incorrect ability type. |
| 16000004 | Can not start invisible component. | | 16000004 | Can not start invisible component. |
| 16000005 | The specified process does not have the permission. |
| 16000006 | Cross-user operations are not allowed. | | 16000006 | Cross-user operations are not allowed. |
| 16000008 | The crowdtesting application expires. | | 16000008 | The crowdtesting application expires. |
| 16000053 | The ability is not on the top of the UI. | | 16000053 | The ability is not on the top of the UI. |
...@@ -2226,7 +2231,7 @@ setMissionContinueState(state: AbilityConstant.ContinueState, callback:AsyncCall ...@@ -2226,7 +2231,7 @@ setMissionContinueState(state: AbilityConstant.ContinueState, callback:AsyncCall
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| state | [ContinueState](js-apis-app-ability-abilityConstant.md#abilityconstantcontinuestate10) | 是 | 流转状态。 | | state | [AbilityConstant.ContinueState](js-apis-app-ability-abilityConstant.md#abilityconstantcontinuestate10) | 是 | 流转状态。 |
| callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,返回接口调用是否成功的结果。 | | callback | AsyncCallback&lt;void&gt; | 是 | 回调函数,返回接口调用是否成功的结果。 |
**错误码:** **错误码:**
...@@ -2260,7 +2265,7 @@ setMissionContinueState(state: AbilityConstant.ContinueState): Promise&lt;void&g ...@@ -2260,7 +2265,7 @@ setMissionContinueState(state: AbilityConstant.ContinueState): Promise&lt;void&g
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| state | [ContinueState](js-apis-app-ability-abilityConstant.md#abilityconstantcontinuestate10) | 是 | 流转状态。 | | state | [AbilityConstant.ContinueState](js-apis-app-ability-abilityConstant.md#abilityconstantcontinuestate10) | 是 | 流转状态。 |
**返回值:** **返回值:**
...@@ -2787,9 +2792,9 @@ startAbilityByCallWithAccount(want: Want, accountId: number): Promise&lt;Caller& ...@@ -2787,9 +2792,9 @@ startAbilityByCallWithAccount(want: Want, accountId: number): Promise&lt;Caller&
} }
``` ```
## UIAbilityContext.reportDrawnCompleted ## UIAbilityContext.reportDrawnCompleted<sup>10+</sup>
reportDrawnCompleted(callback: AsyncCallback<void>): void; reportDrawnCompleted(callback: AsyncCallback\<void>): void;
当页面加载完成(loadContent成功)时,为开发者提供打点功能(callback形式)。 当页面加载完成(loadContent成功)时,为开发者提供打点功能(callback形式)。
**系统能力**:SystemCapability.Ability.AbilityRuntime.Core **系统能力**:SystemCapability.Ability.AbilityRuntime.Core
...@@ -2812,7 +2817,11 @@ reportDrawnCompleted(callback: AsyncCallback<void>): void; ...@@ -2812,7 +2817,11 @@ reportDrawnCompleted(callback: AsyncCallback<void>): void;
**示例:** **示例:**
```ts ```ts
onWindowStageCreate(windowStage: Window.WindowStage) { import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
windowStage.loadContent('pages/Index', (err, data) => { windowStage.loadContent('pages/Index', (err, data) => {
if (err.code) { if (err.code) {
return; return;
...@@ -2833,5 +2842,6 @@ onWindowStageCreate(windowStage: Window.WindowStage) { ...@@ -2833,5 +2842,6 @@ onWindowStageCreate(windowStage: Window.WindowStage) {
} }
}); });
console.log("MainAbility onWindowStageCreate") console.log("MainAbility onWindowStageCreate")
} }
};
``` ```
\ No newline at end of file
...@@ -6,6 +6,8 @@ ...@@ -6,6 +6,8 @@
> >
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 属性
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent **系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
......
...@@ -6,6 +6,8 @@ ...@@ -6,6 +6,8 @@
> >
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 属性
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent **系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.CommonEvent
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
......
...@@ -4,6 +4,8 @@ ...@@ -4,6 +4,8 @@
> >
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 属性
**系统能力:** `SystemCapability.Notification.CommonEvent` **系统能力:** `SystemCapability.Notification.CommonEvent`
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
......
...@@ -6,6 +6,8 @@ ...@@ -6,6 +6,8 @@
> >
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 属性
**系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.Notification **系统能力:** 以下各项对应的系统能力均为SystemCapability.Notification.Notification
| 名称 | 类型 | 只读 | 必填 | 说明 | | 名称 | 类型 | 只读 | 必填 | 说明 |
......
...@@ -35,14 +35,14 @@ ...@@ -35,14 +35,14 @@
| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 否 | 通知小图标。可选字段,大小不超过30KB。 | | smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 否 | 通知小图标。可选字段,大小不超过30KB。 |
| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 否 | 通知大图标。可选字段,大小不超过30KB。 | | largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | 否 | 通知大图标。可选字段,大小不超过30KB。 |
| creatorBundleName | string | 否 | 创建通知的包名。 | | creatorBundleName | string | 否 | 创建通知的包名。 |
| creatorUid<sup>8+<sup> | number | 否 | 创建通知的UID。 | | creatorUid | number | 否 | 创建通知的UID。 |
| creatorPid | number | 否 | 创建通知的PID。 | | creatorPid | number | 否 | 创建通知的PID。 |
| creatorUserId | number | 否 | 创建通知的UserId。 | | creatorUserId<sup>8+<sup> | number | 否 | 创建通知的UserId。 |
| hashCode | string | 否 | 通知唯一标识。 | | hashCode | string | 否 | 通知唯一标识。 |
| classification | string | 否 | 通知分类。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 | | classification | string | 否 | 通知分类。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
| groupName<sup>8+<sup> | string | 否 | 组通知名称。 | | groupName<sup>8+<sup> | string | 否 | 组通知名称。 |
| template<sup>8+<sup> | [NotificationTemplate](./js-apis-inner-notification-notificationTemplate.md) | 否 | 通知模板。 | | template<sup>8+<sup> | [NotificationTemplate](./js-apis-inner-notification-notificationTemplate.md) | 否 | 通知模板。 |
| isRemoveAllowed<sup>8+<sup> | boolean | 否 | 通知是否能被移除。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 | | isRemoveAllowed<sup>10+<sup> | boolean | 否 | 通知是否能被移除。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
| source<sup>8+<sup> | number | 否 | 通知源。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 | | source<sup>8+<sup> | number | 否 | 通知源。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
| distributedOption<sup>8+<sup> | [DistributedOptions](#distributedoptions) | 否 | 分布式通知的选项。 | | distributedOption<sup>8+<sup> | [DistributedOptions](#distributedoptions) | 否 | 分布式通知的选项。 |
| deviceId<sup>8+<sup> | string | 否 | 通知源的deviceId。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 | | deviceId<sup>8+<sup> | string | 否 | 通知源的deviceId。<br>**系统API**: 此接口为系统接口,三方应用不支持调用。 |
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
> >
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
# NotificationSorting ## 属性
**系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification **系统能力**:以下各项对应的系统能力均为SystemCapability.Notification.Notification
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册