提交 1dcefb86 编写于 作者: J jiaoyanlin3

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

......@@ -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. 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.
- In the [widget page code file](arkts-ui-widget-creation.md), 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
let storage = new LocalStorage();
@Entry(storage)
......@@ -178,7 +178,7 @@ The update-through-proxy configuration varies by the type of shared data.
}
```
- 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.
- In the [widget page code file](arkts-ui-widget-creation.md), 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
let storage = new LocalStorage();
@Entry(storage)
......@@ -215,4 +215,4 @@ The update-through-proxy configuration varies by the type of shared data.
## Data Provider Development
For details, see [Data Management](../database/data-mgmt-overview.md).
For details, see [Data Management](../database/share-data-by-silent-access.md).
......@@ -15,10 +15,11 @@
- Widget rendering service: a service that manages widget rendering instances. Widget rendering instances are bound to the [widget components](../reference/arkui-ts/ts-basic-components-formcomponent.md) on the widget host on a one-to-one basis. The widget rendering service runs the widget page code **widgets.abc** for rendering, and sends the rendered data to the corresponding widget component on the widget host.
**Figure 2** Working principles of the ArkTS widget rendering service
![WidgetRender](figures/WidgetRender.png)
**Figure 2** Working principles of the ArkTS widget rendering service
Unlike JS widgets, ArkTS widgets support logic code running. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same virtual machine operating environment, and rendering instances of different widget providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-page) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers.
![WidgetRender](figures/WidgetRender.png)
Unlike JS widgets, ArkTS widgets support logic code execution. The widget page code **widgets.abc** is executed by the widget rendering service, which is managed by the Widget Manager. Each widget component of a widget host corresponds to a rendering instance in the widget rendering service. Rendering instances of a widget provider run in the same virtual machine operating environment, and rendering instances of different widget providers run in different virtual machine operating environments. In this way, the resources and state data are isolated between widgets of different widget providers. During development, pay attention to the use of the [globalThis](uiability-data-sync-with-ui.md#using-globalthis-between-uiability-and-ui-page) object. Use one **globalThis** object for widgets from the same widget provider, and different **globalThis** objects for widgets from different widget providers.
## Advantages of ArkTS Widgets
......@@ -57,6 +58,8 @@ In addition, ArkTS widgets do not support the following features:
- Instant preview
- Breakpoint debugging.
- Breakpoint debugging
- Hot reload
- **setTimeOut**
......@@ -19,8 +19,8 @@
- Cross-Application Data Sharing
- [Data Sharing Overview](data-share-overview.md)
- [Unified Data Definition](unified-data-definition.md)
- One-to-Many Data Sharing (Only for System Applications)
- [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md)
- [Silent Access via the DatamgrService](share-data-by-silent-access.md)
- One-to-Many Data Sharing (for System Applications Only)
- [Sharing Data Using DataShareExtensionAbility](share-data-by-datashareextensionability.md)
- [Silent Access via the DatamgrService](share-data-by-silent-access.md)
- Many-to-Many Data Sharing
- [Sharing Data Using Unified Data Channels](unified-data-channels.md)
\ No newline at end of file
......@@ -760,147 +760,6 @@ Text in the **\<Text>** component is centered by default. You do not need to set
[Text](../reference/arkui-ts/ts-basic-components-text.md#example-1)
## How do I set the controlButton attribute for the \<SideBarContainer> component?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
The sample code is as follows:
```
@Entry
@Component
struct SideBarContainerExample {
normalIcon : Resource = $r("app.media.icon")
selectedIcon: Resource = $r("app.media.icon")
@State arr: number[] = [1, 2, 3]
@State current: number = 1
build() {
SideBarContainer(SideBarContainerType.Embed)
{
Column() {
ForEach(this.arr, (item, index) => {
Column({ space: 5 }) {
Image(this.current === item ? this.selectedIcon : this.normalIcon).width(64).height(64)
Text("Index0" + item)
.fontSize(25)
.fontColor(this.current === item ? '#0A59F7' : '#999')
.fontFamily('source-sans-pro,cursive,sans-serif')
}
.onClick(() => {
this.current = item
})
}, item => item)
}.width('100%')
.justifyContent(FlexAlign.SpaceEvenly)
.backgroundColor('#19000000')
Column() {
Text('SideBarContainer content text1').fontSize(25)
Text('SideBarContainer content text2').fontSize(25)
}
.margin({ top: 50, left: 20, right: 30 })
}
.sideBarWidth(150)
.minSideBarWidth(50)
.controlButton({left:32,
top:32,
width:32,
height:32,
icons:{shown: $r("app.media.icon"),
hidden: $r("app.media.icon"),
switching: $r("app.media.icon")}})
.maxSideBarWidth(300)
.onChange((value: boolean) => {
console.info('status:' + value)
})
}
}
```
## How do I implement the dragging feature for the \<Grid> component?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
1. Set the **editMode\(true\)** attribute of the **\<Grid>** component to specify whether the component enters the editing mode. In the editing mode, you can drag grid items.
2. Set the image displayed during dragging in the [onItemDragStart](../reference/arkui-ts/ts-container-grid.md#events) callback.
3. Obtain the drag start position and drag insertion position from the [onItemDrop](../reference/arkui-ts/ts-container-grid.md#events) callback, and complete the array position exchange logic in the [onDrag](../reference/arkui-ts/ts-universal-events-drag-drop.md#events) callback. The sample code is as follows:
```
@Entry
@Component
struct GridExample {
@State numbers: String[] = []
scroller: Scroller = new Scroller()
@State text: string = 'drag'
@Builder pixelMapBuilder () { // Drag style
Column() {
Text(this.text)
.fontSize(16)
.backgroundColor(0xF9CF93)
.width(80)
.height(80)
.textAlign(TextAlign.Center)
}
}
aboutToAppear() {
for (let i = 1;i <= 15; i++) {
this.numbers.push(i + '')
}
}
changeIndex(index1: number, index2: number) {// Exchange the array item position.
[this.numbers[index1], this.numbers[index2]] = [this.numbers[index2], this.numbers[index1]];
}
build() {
Column({ space: 5 }) {
Grid(this.scroller) {
ForEach(this.numbers, (day: string) => {
GridItem() {
Text(day)
.fontSize(16)
.backgroundColor(0xF9CF93)
.width(80)
.height(80)
.textAlign(TextAlign.Center)
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Up) {
this.text = day
}
})
}
})
}
.columnsTemplate('1fr 1fr 1fr')
.columnsGap(10)
.rowsGap(10)
.onScrollIndex((first: number) => {
console.info(first.toString())
})
.width('90%')
.backgroundColor(0xFAEEE0)
.height(300)
.editMode(true) // Set whether the grid enters the editing mode. In the editing mode, you can drag grid items.
.onItemDragStart((event: ItemDragInfo, itemIndex: number) => { // Triggered when a grid item starts to be dragged.
return this.pixelMapBuilder() // Set the image displayed during dragging.
})
.onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => { // Triggered when the dragged item is dropped on the drop target of the grid.
console.info('beixiang' + itemIndex + '', insertIndex + '') // itemIndex indicates the initial position of the dragged item; insertIndex indicates the index of the position to which the dragged item will be dropped.
this.changeIndex(itemIndex, insertIndex)
})
}.width('100%').margin({ top: 5 })
}
}
```
## Which API is used for URL encoding?
......
# ArkUI Component Development (ArkTS)
## Can custom dialog boxes be defined or used in .ts files?
## Can custom dialog boxes be defined and used in .ts files?
Applicable to: OpenHarmony 3.2 Beta 5 (API version 9)
Unfortunately, no. ArkTS syntax is required for defining and initializing custom dialog boxes. Therefore, they can be defined and used only in .ets files.
Unfortunately not. Custom dialog boxes require ArkTS syntax for definition and initialization. Therefore, they can be defined and used only in .ets files.
**Reference**
......@@ -245,8 +245,8 @@ When a custom dialog box contains a child component whose area size can be chang
**Solution**
- Method 1: Use the default style of the custom dialog box. In this case, the dialog box automatically adapts its width to the grid system and its height to the child components; the maximum height is 90% of the container height.
- Method 2: Use a custom style of the custom dialog box. In this case, the dialog box automatically adapts its width and height to the child components.
- Method 1: Set the custom dialog box to the default style. In this style, the dialog box automatically adapts its width to the grid system and its height to the child components; the maximum height is 90% of the container height.
- Method 2: Set the custom dialog box to a custom style. In this style, the dialog box automatically adapts its width and height to the child components.
**Reference**
......@@ -685,3 +685,64 @@ You can use **focusControl.requestFocus** to control the focus of the text input
**Reference**
[Focus Control](../reference/arkui-ts/ts-universal-attributes-focus.md)
## How do I set the controlButton attribute for the \<SideBarContainer> component?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
Refer to the following sample code:
```
@Entry
@Component
struct SideBarContainerExample {
normalIcon : Resource = $r("app.media.icon")
selectedIcon: Resource = $r("app.media.icon")
@State arr: number[] = [1, 2, 3]
@State current: number = 1
build() {
SideBarContainer(SideBarContainerType.Embed)
{
Column() {
ForEach(this.arr, (item, index) => {
Column({ space: 5 }) {
Image(this.current === item ? this.selectedIcon : this.normalIcon).width(64).height(64)
Text("Index0" + item)
.fontSize(25)
.fontColor(this.current === item ? '#0A59F7' : '#999')
.fontFamily('source-sans-pro,cursive,sans-serif')
}
.onClick(() => {
this.current = item
})
}, item => item)
}.width('100%')
.justifyContent(FlexAlign.SpaceEvenly)
.backgroundColor('#19000000')
Column() {
Text('SideBarContainer content text1').fontSize(25)
Text('SideBarContainer content text2').fontSize(25)
}
.margin({ top: 50, left: 20, right: 30 })
}
.sideBarWidth(150)
.minSideBarWidth(50)
.controlButton({left:32,
top:32,
width:32,
height:32,
icons:{shown: $r("app.media.icon"),
hidden: $r("app.media.icon"),
switching: $r("app.media.icon")}})
.maxSideBarWidth(300)
.onChange((value: boolean) => {
console.info('status:' + value)
})
}
}
```
# Best Practices for Application Performance
This topic outlines some best practices for improving your application performance to live up to user expectations for quick startup, timely response, and no frame freezing.
Following these practices, you can reduce your application's startup time, response time, and frame loss.
- Improving application startup and response time
- [Speeding Up Application Cold Start](../performance/improve-application-startup-and-response/improve-application-cold-start-speed.md)
Application startup latency is a key factor that affects user experience. To speed up the application cold start, you are advised to perform optimization in the following four phases:
​ 1. Application process creation and initialization
​ 2. Application and ability initialization
​ 3. Ability lifecycle
​ 4. Home page loading and drawing
- [Speeding Up Application Response](../performance/improve-application-startup-and-response/improve-application-response.md)
A premium interaction experience requires quick response to user input. To improve your application's response time, you are advised to prevent the main thread from being blocked by non-UI tasks and reduce the number of component to be refreshed.
- Reducing frame loss
- [Reducing Nesting](../performance/reduce-frame-loss-and-frame-freezing/reduce-view-nesting-levels.md)
The smoothness of rendering the layout to the screen affects the user perceived quality. It is recommended that you minimize nesting in your code to shorten the render time.
- [Reducing Frame Loss](../performance/reduce-frame-loss-and-frame-freezing/reduce-animation-frame-loss.md)
Whether animations in your application run smoothly is a key factor that affects user experience. You are advised to use the system-provided animation APIs to reduce frame loss.
# Speeding Up Application Cold Start
Application startup latency is a key factor that affects user experience. When an application is started, the background does not have a process of the application, and therefore the system creates a new process and allocates it to the application. This startup mode is called cold start.
## Analyzing the Time Required for Application Cold Start
The cold start process of OpenHarmony applications can be divided into four phases: application process creation and initialization, application and ability initialization, ability lifecycle, and home page loading and drawing, as shown in the following figure.
![application-cold-start](../figure/application-cold-start.png)
## 1. Shortening Time Required for Application Process Creation And Initialization
In the phase of application process creation and initialization, the system creates and initializes an application process, including decoding the icon of the startup page (specified by **startWindowIcon**).
### Using startWindowIcon of Appropriate Resolution
With regard to the icon of the startup page, the recommended maximum resolution is 256 x 256 pixels. Larger resolutions may result in slow startup.
```json
"abilities": [
{
"name": "EntryAbility",
"srcEntrance": "./ets/entryability/EntryAbility.ts",
"description": "$string:EntryAbility_desc",
"icon": "$media:icon",
"label": "$string:EntryAbility_label",
"startWindowIcon": "$media:startWindowIcon", // Modify the icon of the startup page. It is recommended that the icon be less than or equal to 256 pixels x 256 pixels.
"startWindowBackground": "$color:start_window_background",
"visible": true,
"skills": [
{
"entities": [
"entity.system.home"
],
"actions": [
"action.system.home"
]
}
]
}
]
```
## 2. Shortening Time Required for Application and Ability Initialization
In this phase of application and ability initialization, resources are loaded, VMs are created, application and ability related objects are created and initialized, and dependent modules are loaded.
### Minimizing the Number of Imported Modules
Before the application code is executed, the application must find and load all imported modules. Each additional third-party framework or module to be loaded by the application increases the startup time. The time required depends on the number and size of loaded third-party frameworks or modules. To speed up startup, use system-provided modules when possible and load the modules as required.
## 3. Shortening Time Required for Ability Lifecycle
In this phase of ability lifecycle, the ability lifecycle callbacks are executed.
### Avoiding Time-Consuming Operations in Ability Lifecycle Callbacks
In the application startup process, the system executes the ability lifecycle callbacks. Whenever possible, avoid performing time-consuming operations in these callbacks. You are advised to perform time-consuming operations through asynchronous tasks or execute them in other threads.
In these lifecycle callbacks, perform only necessary operations. For details, see [UIAbility Lifecycle](https://gitee.com/openharmony/docs/blob/master/en/application-dev/application-models/uiability-lifecycle.md).
## 4. Shortening Time Required for Home Page Loading and Drawing
In this phase of home page loading and drawing, the home page content is loaded, the layout is measured, and components are refreshed and drawn.
### Avoid time-consuming operations in the custom component lifecycle callbacks.
When the lifecycle of a custom component changes, the corresponding callback is called.
The **aboutToAppear** function is executed after the custom component instance is created and before the page is drawn. The following code asynchronously processes the time-consuming computing task in **aboutToAppear** to avoid executing the operation in this function and blocking the page drawing.
```javascript
@Entry
@Component
struct Index {
@State private text: string = undefined;
private count: number = undefined;
aboutToAppear() {
this.computeTaskAsync(); // Asynchronous task
this.text = "hello world";
}
build() {
Column({space: 10}) {
Text(this.text).fontSize(50)
}
.width('100%')
.height('100%')
.padding(10)
}
computeTask() {
this.count = 0;
while (this.count < 10000000) {
this.count++;
}
this.text = 'task complete';
}
// Asynchronous processing of the computing task
private computeTaskAsync() {
new Promise((resolved, rejected) => {
setTimeout(() => {// setTimeout is used to implement asynchronous processing.
this.computeTask();
}, 1000)
})
}
}
```
# Speeding Up Application Response
This topic provides the following tips for improving your application's response to user input.
- Prevent the main thread from being blocked by non-UI tasks.
- Reduce the number of components to be refreshed.
## Preventing Main Thread from Being Blocked by Non-UI Tasks
When the application responds to user input, its main thread should execute only UI tasks (such as preparation of data to be displayed and update of visible components). It is recommended that non-UI, time-consuming tasks (such as long-time content loading) be executed through asynchronous tasks or allocated to other threads.
### Using Asynchronous Component Loading
The **\<Image>** component has the asynchronous loading feature enabled by default. When an application loads a batch of local images to be displayed on the page, blank placeholder icons are displayed first, and then replaced by the images when these images have finished loading in other threads. In this way, image loading does not block page display. The following code is recommended only when the image loading takes a short time.
```javascript
@Entry
@Component
struct ImageExample1 {
build() {
Column() {
Row() {
Image('resources/base/media/sss001.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%')
Image('resources/base/media/sss002.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%')
Image('resources/base/media/sss003.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%')
Image('resources/base/media/sss004.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%')
}
// Several <Row> containers are omitted here. Each container contains the preceding <Image> components.
}
}
}
```
Recommendation: If it takes a short time to load an image, the benefits of asynchronous loading will be greatly undermined. In this case, change the value of the syncLoad attribute.
```javascript
@Entry
@Component
struct ImageExample1 {
build() {
Column() {
Row() {
Image('resources/base/media/sss001.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%').syncLoad(true)
Image('resources/base/media/sss002.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%').syncLoad(true)
Image('resources/base/media/sss003.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%').syncLoad(true)
Image('resources/base/media/sss004.jpg')
.border({ width: 1 }).borderStyle(BorderStyle.Dashed).aspectRatio(1).width('25%').height('12.5%').syncLoad(true)
}
// Several <Row> containers are omitted here. Each container contains the preceding <Image> components.
}
}
}
```
### Using TaskPool for Asynchronous Processing
Compared with the worker thread, [TaskPool](https://gitee.com/sqsyqqy/docs/blob/master/en/application-dev/reference/apis/js-apis-taskpool.md) provides the task priority setting and automatic thread pool management mechanism. The following is an example:
```javascript
import taskpool from '@ohos.taskpool';
@Concurrent
function computeTask(arr: string[]): string[] {
// Simulate a compute-intensive task.
let count = 0;
while (count < 100000000) {
count++;
}
return arr.reverse();
}
@Entry
@Component
struct AspectRatioExample {
@State children: string[] = ['1', '2', '3', '4', '5', '6'];
aboutToAppear() {
this.computeTaskInTaskPool();
}
async computeTaskInTaskPool() {
const param = this.children.slice();
let task = new taskpool.Task(computeTask, param);
// @ts-ignore
this.children = await taskpool.execute(task);
}
build() {
// Component layout
}
}
```
### Creating Asynchronous Tasks
The following code shows how to declare a long-running non-UI task as an asynchronous task through **Promise**. This allows the main thread to first focus on providing user feedback and completing the initial render, and then execute the asynchronous task when it is idle. After the asynchronous task is complete, related components are redrawn to refresh the page.
```javascript
@Entry
@Component
struct AspectRatioExample {
@State private children: string[] = ['1', '2', '3', '4', '5', '6'];
private count: number = undefined;
aboutToAppear() {
this.computeTaskAsync(); // Invoke the asynchronous compute function.
}
// Simulate a compute-intensive task.
computeTask() {
this.count = 0;
while (this.count < 100000000) {
this.count++;
}
this.children = this.children.reverse();
}
computeTaskAsync() {
new Promise((resolved, rejected) => {
setTimeout(() => {// setTimeout is used to implement asynchronous processing.
this.computeTask();
}, 1000)
})
}
build() {
// Component layout
}
}
```
## Reducing the Number of Components to Be Refreshed
When an application refreshes a page, the number of components to be refreshed must be reduced as much as possible. If this number is too large, the main thread will take a long time to perform measurement and layout. In addition, the **aboutToAppear()** and **aboutToDisappear()** APIs will be called multiple times during the creation and destruction of custom components, increasing the load of the main thread.
### Limiting the Refresh Scope with Containers
Negative example: If a component in a container is included in the **if** condition, changes in the **if** condition result will trigger the creation and destruction of the component. If the container layout is affected in this case, all components in the container are refreshed. As a result, the UI refresh of the main thread takes a long time.
In the following example, the **Text('New Page')** component is controlled by the state variable **isVisible**. When **isVisible** is set to **true**, the component is created. When **isVisible** is set to **false**, the component is destroyed. This means that, when the value of **isVisible** changes, all components in the **\<Stack>** container are refreshed.
```javascript
@Entry
@Component
struct StackExample {
@State isVisible : boolean = false;
build() {
Column() {
Stack({alignContent: Alignment.Top}) {
Text().width('100%').height('70%').backgroundColor(0xd2cab3)
.align(Alignment.Center).textAlign(TextAlign.Center);
// 100 identical <Text> components are omitted here.
if (this.isVisible) {
Text('New Page').height("100%").height("70%").backgroundColor(0xd2cab3)
.align(Alignment.Center).textAlign(TextAlign.Center);
}
}
Button("press").onClick(() => {
this.isVisible = !(this.isVisible);
})
}
}
}
```
Recommendation: For the component controlled by the state variable, add a container to the **if** statement to reduce the refresh scope.
```javascript
@Entry
@Component
struct StackExample {
@State isVisible : boolean = false;
build() {
Column() {
Stack({alignContent: Alignment.Top}) {
Text().width('100%').height('70%').backgroundColor(0xd2cab3)
.align(Alignment.Center).textAlign(TextAlign.Center);
// 100 identical <Text> components are omitted here.
Stack() {
if (this.isVisible) {
Text('New Page').height("100%").height("70%").backgroundColor(0xd2cab3)
.align(Alignment.Center).textAlign(TextAlign.Center);
}
}.width('100%').height('70%')
}
Button("press").onClick(() => {
this.isVisible = !(this.isVisible);
})
}
}
}
```
### Implementing On-Demand Loading of List Items
Negative example: Each of the 10000 elements in **this.arr** is initialized and loaded. As a result, the execution of the main thread takes a long time.
```javascript
@Entry
@Component
struct MyComponent {
@State arr: number[] = Array.from(Array(10000), (v,k) =>k);
build() {
List() {
ForEach(this.arr, (item: number) => {
ListItem() {
Text(`item value: ${item}`)
}
}, (item: number) => item.toString())
}
}
}
```
Recommendation: In similar cases, replace **ForEach** with **LazyForEach** so that only visible elements are loaded.
```javascript
class BasicDataSource implements IDataSource {
private listeners: DataChangeListener[] = []
public totalCount(): number {
return 0
}
public getData(index: number): any {
return undefined
}
registerDataChangeListener(listener: DataChangeListener): void {
if (this.listeners.indexOf(listener) < 0) {
console.info('add listener')
this.listeners.push(listener)
}
}
unregisterDataChangeListener(listener: DataChangeListener): void {
const pos = this.listeners.indexOf(listener);
if (pos >= 0) {
console.info('remove listener')
this.listeners.splice(pos, 1)
}
}
notifyDataReload(): void {
this.listeners.forEach(listener => {
listener.onDataReloaded()
})
}
notifyDataAdd(index: number): void {
this.listeners.forEach(listener => {
listener.onDataAdd(index)
})
}
notifyDataChange(index: number): void {
this.listeners.forEach(listener => {
listener.onDataChange(index)
})
}
notifyDataDelete(index: number): void {
this.listeners.forEach(listener => {
listener.onDataDelete(index)
})
}
notifyDataMove(from: number, to: number): void {
this.listeners.forEach(listener => {
listener.onDataMove(from, to)
})
}
}
class MyDataSource extends BasicDataSource {
private dataArray: string[] = Array.from(Array(10000), (v, k) => k.toString());
public totalCount(): number {
return this.dataArray.length
}
public getData(index: number): any {
return this.dataArray[index]
}
public addData(index: number, data: string): void {
this.dataArray.splice(index, 0, data)
this.notifyDataAdd(index)
}
public pushData(data: string): void {
this.dataArray.push(data)
this.notifyDataAdd(this.dataArray.length - 1)
}
}
@Entry
@Component
struct MyComponent {
private data: MyDataSource = new MyDataSource()
build() {
List() {
LazyForEach(this.data, (item: string) => {
ListItem() {
Text(item).fontSize(20).margin({ left: 10 })
}
}, item => item)
}
}
}
```
# Reducing Frame Loss
Frame loss in the animation arena is a phenomenon where the frame rate of an animation drops when it is running or being created.
When playing an animation, the system needs to calculate the animation curve and draw the component layout within a refresh period. You are advised to use the system-provided animation APIs. With these APIs, setting the curve type, end point position, and duration is enough for meeting common animation needs, thereby reducing the load of the UI main thread.
Negative example: The application uses a custom animation, which involves animation curve calculation. This calculation process may cause high load of the UI thread and frame loss.
```javascript
@Entry
@Component
struct AttrAnimationExample {
@State widthSize: number = 200
@State heightSize: number = 100
@State flag: boolean = true
computeSize() {
let duration = 2000
let period = 16
let widthSizeEnd = undefined
let heightSizeEnd = undefined
if (this.flag) {
widthSizeEnd = 100
heightSizeEnd = 50
} else {
widthSizeEnd = 200
heightSizeEnd = 100
}
let doTimes = duration / period
let deltaHeight = (heightSizeEnd - this.heightSize) / doTimes
let deltaWeight = (widthSizeEnd - this.widthSize) / doTimes
for (let i = 1; i <= doTimes; i++) {
let t = period * (i);
setTimeout(() => {
this.heightSize = this.heightSize + deltaHeight
this.widthSize = this.widthSize + deltaWeight
}, t)
}
this.flag = !this.flag
}
build() {
Column() {
Button('click me')
.onClick(() => {
let delay = 500
setTimeout(() => { this.computeSize() }, delay)
})
.width(this.widthSize).height(this.heightSize).backgroundColor(0x317aff)
}.width('100%').margin({ top: 5 })
}
}
```
## Using System-Provided Attribute Animation APIs
The following uses the system-provided attribute animation APIs to implement the preceding animation features:
```javascript
@Entry
@Component
struct AttrAnimationExample {
@State widthSize: number = 200
@State heightSize: number = 100
@State flag: boolean = true
build() {
Column() {
Button('click me')
.onClick((event: ClickEvent) => {
if (this.flag) {
this.widthSize = 100
this.heightSize = 50
} else {
this.widthSize = 200
this.heightSize = 100
}
this.flag = !this.flag
})
.width(this.widthSize).height(this.heightSize).backgroundColor(0x317aff)
.animation({
duration: 2000, // Animation duration.
curve: Curve.Linear, // Animation curve.
delay: 500, // Animation delay.
iterations: 1, // Number of playback times.
playMode: PlayMode.Normal // Animation playback mode.
}) // Animation configuration for the width and height attributes of the <Button> component.
}.width('100%').margin({ top: 5 })
}
}
```
For more details, see [Property Animator](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-animatorproperty.md).
## Using System-Provided Explicit Animation APIs
The following uses the system-provided explicit animation APIs to implement the preceding animation features:
```javascript
@Entry
@Component
struct AnimateToExample {
@State widthSize: number = 200;
@State heightSize: number = 100;
@State flag: boolean = true;
build() {
Column() {
Button('click me')
.onClick((event: ClickEvent) => {
if (this.flag) {
animateTo({
duration: 2000, // Animation duration.
curve: Curve.Linear, // Animation curve.
delay: 500, // Animation delay.
iterations: 1, // Number of playback times.
playMode: PlayMode.Normal // Animation playback mode.
}, () => {
this.widthSize = 100;
this.heightSize = 50;
})
} else {
animateTo({
duration: 2000, // Animation duration.
curve: Curve.Linear, // Animation curve.
delay: 500, // Animation delay.
iterations: 1, // Number of playback times.
playMode: PlayMode.Normal // Animation playback mode.
}, () => {
this.widthSize = 200;
this.heightSize = 100;
})
}
this.flag = !this.flag;
})
.width(this.widthSize).height(this.heightSize).backgroundColor(0x317aff)
}.width('100%').margin({ top: 5 })
}
}
```
For more details, see [Explicit Animation](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-explicit-animation.md).
# Reducing Nesting
The view hierarchy can significantly affect application performance. For example, at the 120 Hz refresh rate, a device screen refreshes frames every 8.3 ms. If there are many levels of nested views, the frames may fail to be refreshed within 8.3 ms. As a result, frame loss and frame freezing occur, detracting from user experience. Therefore, it is recommended that you minimize nesting in your code to shorten the refresh time.
## Removing Redundant Levels of Nesting
In the following negative example, the **\<Grid>** component is used to implement a grid, but it is nested inside three levels of **\<Stack>** containers. As a result, the refresh and rendering process takes a long time to complete.
```javascript
@Entry
@Component
struct AspectRatioExample {
@State children: Number[] = Array.from(Array(900), (v, k) => k);
build() {
Scroll() {
Grid() {
ForEach(this.children, (item) => {
GridItem() {
Stack() {
Stack() {
Stack() {
Text(item.toString())
}
}
}
}
}, item => item)
}
.columnsTemplate('1fr 1fr 1fr 1fr')
.columnsGap(0)
.rowsGap(0)
.size({ width: "100%", height: "100%" })
}
}
}
```
Recommendation: Reduce the redundant nesting of **\<Stack>** containers. In this way, the number of components that each grid item needs to pass is three less, shortening the refresh and rendering time.
```javascript
// xxx.ets
@Entry
@Component
struct AspectRatioExample {
@State children: Number[] = Array.from(Array(900), (v, k) => k);
build() {
Scroll() {
Grid() {
ForEach(this.children, (item) => {
GridItem() {
Text(item.toString())
}
}, item => item)
}
.columnsTemplate('1fr 1fr 1fr 1fr')
.columnsGap(0)
.rowsGap(0)
.size({ width: "100%", height: "100%" })
}
}
}
```
......@@ -152,7 +152,7 @@ struct Parent {
```
### Example of Component Initialization Through Trailing Closure
### Component Initialization Through Trailing Closure
In a custom component, the \@BuilderParam decorated attribute can be initialized using a trailing closure. During initialization, the component name is followed by a pair of braces ({}) to form a trailing closure.
......
......@@ -37,6 +37,8 @@ What the internal state is depends on the component. For example, for the [bindP
| [Toggle](../reference/arkui-ts/ts-basic-components-toggle.md) | isOn | 10 |
| [AlphabetIndexer](../reference/arkui-ts/ts-container-alphabet-indexer.md) | selected | 10 |
| [Select](../reference/arkui-ts/ts-basic-components-select.md) | selected, value| 10 |
| [BindSheet](../reference/arkui-ts/ts-universal-attributes-sheet-transition.md) | isShow | 10 |
| [BindContentCover](../reference/arkui-ts/ts-universal-attributes-modal-transition.md) | isShow | 10 |
- When the variable bound to $$ changes, the UI is re-rendered synchronously.
......
......@@ -227,9 +227,9 @@
- [@ohos.distributedMissionManager (Distributed Mission Management)](js-apis-distributedMissionManager.md)
- [@ohos.reminderAgentManager (Reminder Agent Management)](js-apis-reminderAgentManager.md)
- [@ohos.resourceschedule.backgroundTaskManager (Background Task Management)](js-apis-resourceschedule-backgroundTaskManager.md)
- [@ohos.resourceschedule.workScheduler (Work Scheduler)](js-apis-resourceschedule-workScheduler.md)
- [@ohos.resourceschedule.workScheduler (Deferred Task Scheduling)](js-apis-resourceschedule-workScheduler.md)
- [@ohos.resourceschedule.usageStatistics (Device Usage Statistics)](js-apis-resourceschedule-deviceUsageStatistics.md)
- [@ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)](js-apis-WorkSchedulerExtensionAbility.md)
- [@ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)](js-apis-WorkSchedulerExtensionAbility.md)
- application
- [WorkSchedulerExtensionContext](js-apis-inner-application-WorkSchedulerExtensionContext.md)
......
# @ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks)
# @ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)
The **WorkSchedulerExtensionAbility** module provides callbacks for Work Scheduler tasks.
The **WorkSchedulerExtensionAbility** module provides callbacks for deferred task scheduling.
When developing an application, you can override the APIs of this module and add your own task logic to the APIs.
......@@ -28,7 +28,7 @@ import WorkSchedulerExtensionAbility from '@ohos.WorkSchedulerExtensionAbility'
onWorkStart(work: workScheduler.WorkInfo): void
Triggered when the Work Scheduler task starts.
Called when the system starts scheduling the deferred task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -52,7 +52,7 @@ Triggered when the Work Scheduler task starts.
onWorkStop(work: workScheduler.WorkInfo): void
Triggered when the Work Scheduler task stops.
Called when the system stops scheduling the deferred task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......
# WorkSchedulerExtensionContext
The **WorkSchedulerExtensionContext** module, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md), is the context environment of the WorkSchedulerExtensionAbility.
The **WorkSchedulerExtensionContext** module, inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md), provides a context environment for the WorkSchedulerExtensionAbility.
This module provides APIs for accessing the resources of a WorkSchedulerExtensionAbility.
......
# @ohos.resourceschedule.workScheduler (Work Scheduler)
# @ohos.resourceschedule.workScheduler (Deferred Task Scheduling)
The **workScheduler** module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints.
The **workScheduler** module provides the APIs for registering, canceling, and querying deferred tasks.
The system executes Work Scheduler tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more.
The system schedules and executes deferred tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more.
> **NOTE**
>
> - 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 APIs of this module can be used only in the stage model.
> - For details about the restrictions, see [Restrictions on Using Work Scheduler Tasks](../../task-management/background-task-overview.md#restrictions-on-using-work-scheduler-tasks).
## Modules to Import
......@@ -20,7 +19,7 @@ import workScheduler from '@ohos.resourceschedule.workScheduler';
## workScheduler.startWork
startWork(work: WorkInfo): void
Instructs the **WorkSchedulerService** to add the specified task to the execution queue.
Instructs the WorkSchedulerService to add a task to the execution queue.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -71,7 +70,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.stopWork
stopWork(work: WorkInfo, needCancel?: boolean): void
Instructs the **WorkSchedulerService** to stop the specified task.
Instructs the WorkSchedulerService to stop a task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -130,7 +129,7 @@ Obtains the latest task status. This API uses an asynchronous callback to return
| Name | Type | Mandatory | Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------- |
| workId | number | Yes | Task ID. |
| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; throws an exception otherwise.|
| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. If the specified task ID is valid, the task status obtained from the WorkSchedulerService is returned. Otherwise, an exception is thrown.|
**Error codes**
......@@ -178,7 +177,7 @@ Obtains the latest task status. This API uses a promise to return the result.
| Type | Description |
| ------------------------------- | ---------------------------------------- |
| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. Returns the task status obtained from the **WorkSchedulerService** if the specified task ID is valid; throws an exception otherwise.|
| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. If the specified task ID is valid, the task status obtained from the WorkSchedulerService is returned. Otherwise, an exception is thrown.|
**Error codes**
......@@ -210,7 +209,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.obtainAllWorks
obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo>
Obtains all tasks associated with this application. This API uses an asynchronous callback to return the result.
Obtains all tasks associated with the application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -218,13 +217,13 @@ Obtains all tasks associated with this application. This API uses an asynchronou
| Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ------------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. All tasks associated with the current application.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Return value**
| Type | Description |
| ----------------------------- | --------------- |
| Array\<[WorkInfo](#workinfo)> | All tasks associated with the current application.|
| Array\<[WorkInfo](#workinfo)> | All tasks associated with the application.|
**Error codes**
......@@ -255,7 +254,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.obtainAllWorks
obtainAllWorks(): Promise\<Array\<WorkInfo>>
Obtains all tasks associated with this application. This API uses a promise to return the result.
Obtains all tasks associated with the application. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -263,7 +262,7 @@ Obtains all tasks associated with this application. This API uses a promise to r
| Type | Description |
| -------------------------------------- | ------------------------------ |
| Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return the result. All tasks associated with the current application.|
| Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return all tasks associated with the application.|
**Error codes**
......@@ -292,7 +291,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.stopAndClearWorks
stopAndClearWorks(): void
Stops and cancels all tasks associated with the current application.
Stops and cancels all tasks associated with the application.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -320,7 +319,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean
Checks whether the last execution of the specified task timed out. This API uses an asynchronous callback to return the result.
Checks whether the last execution of a task timed out. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -329,13 +328,13 @@ Checks whether the last execution of the specified task timed out. This API uses
| Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ---------------------------------------- |
| workId | number | Yes | Task ID. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Callback used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|
| boolean | Returns **true** if the last execution of the task timed out; returns **false** otherwise.|
**Error codes**
......@@ -367,7 +366,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number): Promise\<boolean>
Checks whether the last execution of the specified task timed out. This API uses a promise to return the result.
Checks whether the last execution of a task timed out. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -381,7 +380,7 @@ Checks whether the last execution of the specified task timed out. This API uses
| Type | Description |
| ----------------- | ---------------------------------------- |
| Promise\<boolean> | Promise used to return the result. Returns **true** if the last execution of the specified task timed out; returns **false** otherwise.|
| Promise\<boolean> | Promise used to return the result. If the last execution of the task timed out, **true** is returned. Otherwise, **false** is returned.|
**Error codes**
......@@ -411,15 +410,15 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## WorkInfo
Provides detailed information about the task. For details about the constraints on configuring **WorkInfo**, see [Restrictions on Using Work Scheduler Tasks](../../task-management/background-task-overview.md#restrictions-on-using-work-scheduler-tasks).
Provides detailed information about the task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name | Type | Mandatory | Description |
| --------------- | --------------------------------- | ---- | ---------------- |
| workId | number | Yes | Task ID. |
| bundleName | string | Yes | Name of the Work Scheduler task bundle. |
| abilityName | string | Yes | Name of the component to be notified by a Work Scheduler callback.|
| bundleName | string | Yes | Bundle name of the application that requests the task. |
| abilityName | string | Yes | Name of the component to be notified by a deferred task scheduling callback. |
| networkType | [NetworkType](#networktype) | No | Network type. |
| isCharging | boolean | No | Whether the device is charging. |
| chargerType | [ChargingType](#chargingtype) | No | Charging type. |
......@@ -435,7 +434,7 @@ Provides detailed information about the task. For details about the constraints
| parameters | {[key: string]: number \| string \| boolean} | No | Carried parameters. |
## NetworkType
Enumerates the network types that can trigger the task.
Enumerates the network types that can trigger task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -449,7 +448,7 @@ Enumerates the network types that can trigger the task.
| NETWORK_TYPE_ETHERNET | 5 | Ethernet. |
## ChargingType
Enumerates the charging types that can trigger the task.
Enumerates the charging types that can trigger task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -461,7 +460,7 @@ Enumerates the charging types that can trigger the task.
| CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. |
## BatteryStatus
Enumerates the battery states that can trigger the task.
Enumerates the battery states that can trigger task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -472,7 +471,7 @@ Enumerates the battery states that can trigger the task.
| BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.|
## StorageRequest
Enumerates the storage states that can trigger the task.
Enumerates the storage states that can trigger task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......
......@@ -67,7 +67,7 @@ struct RichTextExample {
'<h2 style="text-align: center;">h2 heading</h2>' +
'<h3 style="text-align: center;">h3 heading</h3>' +
'<p style="text-align: center;">Regular paragraph</p><hr/>' +
'<div style="width: 500px;height: 500px;border: 1px solid;margin: 0auto;">' +
'<div style="width: 500px;height: 500px;border: 1px solid;margin: 0 auto;">' +
'<p style="font-size: 35px;text-align: center;font-weight: bold; color: rgb(24,78,228)">Font size: 35px; line height: 45px</p>' +
'<p style="background-color: #e5e5e5;line-height: 45px;font-size: 35px;text-indent: 2em;">' +
'<p>This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text. This is text.</p>';
......
......@@ -30,15 +30,15 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Description |
| ----------------------- | ------------------------------------------------ | ---------------------------------------------- |
| searchButton<sup>10+</sup> | value: string,<br>option?: [SearchButtonOptions](#searchbuttonoptions10) | Text on the search button located next to the search text box. By default, there is no search button. |
| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color. |
| placeholderColor | [ResourceColor](ts-types.md#resourcecolor) | Placeholder text color.<br>Default value: **'#99182431'** |
| placeholderFont | [Font](ts-types.md#font) | Placeholder text style, including the font size, font width, font family, and font style. Currently, only the default font family is supported. |
| textFont | [Font](ts-types.md#font) | Style of the text entered in the search box, including the font size, font width, font family, and font style. Currently, only the default font family is supported. |
| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Text alignment mode in the search text box.<br>Default value: **TextAlign.Start** |
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed. |
| copyOption<sup>9+</sup> | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.<br>Default value: **CopyOptions.LocalDevice**<br>If this attribute is set to **CopyOptions.None**, the text can be pasted, but copy or cut is not allowed. |
| searchIcon<sup>10+</sup> | [IconOptions](#iconoptions10) | Style of the search icon on the left. |
| cancelButton<sup>10+</sup> | {<br>style? : [CancelButtonStyle](#cancelbuttonstyle10)<br>icon?: [IconOptions](#iconoptions10) <br>} | Style of the Cancel button on the right. |
| fontColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor) | Font color of the input text. |
| caretStyle<sup>10+</sup> | [CaretStyle](#caretstyle10) | Caret style. |
| cancelButton<sup>10+</sup> | {<br>style? : [CancelButtonStyle](#cancelbuttonstyle10)<br>icon?: [IconOptions](#iconoptions10) <br>} | Style of the Cancel button on the right.<br>Default value:<br>{<br>style: CancelButtonStyle.INPUT<br>} |
| fontColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor) | Font color of the input text.<br>Default value: **'#FF182431'**<br>**NOTE**<br>[Universal text attributes](ts-universal-attributes-text-style.md) **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are set in the **textFont** attribute.|
| caretStyle<sup>10+</sup> | [CaretStyle](#caretstyle10) | Caret style.<br>Default value:<br>{<br>width: 1.5vp<br>color: '#007DFF'<br>} |
| enableKeyboardOnFocus<sup>10+</sup> | boolean | Whether to enable the input method when the component obtains focus.<br>Default value: **true** |
| selectionMenuHidden<sup>10+</sup> | boolean | Whether to display the text selection menu when the text box is long-pressed or right-clicked.<br>Default value: **false**|
## IconOptions<sup>10+</sup>
......
......@@ -31,7 +31,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name | Description |
| -------- | ---------------- |
| Checkbox | Check box type.<br>**NOTE**<br>The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 12 px,<br> right: 12 px,<br> bottom: 12 px,<br> left: 12 px<br> } |
| Checkbox | Check box type.<br>**NOTE**<br>The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 14 px,<br> right: 14 px,<br> bottom: 14 px,<br> left: 14 px<br> } |
| Button | Button type. The set string, if any, will be displayed inside the button. |
| Switch | Switch type.<br>**NOTE**<br>The default value of the universal attribute [margin](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 6px,<br> right: 14px,<br> bottom: 6 px,<br> left: 14 px<br> } |
......
......@@ -29,7 +29,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| count | number | Yes| Number of notifications.<br>**NOTE**<br>If the value is less than or equal to 0, no badge is displayed.<br>Value range: [-2147483648, 2147483647]<br>If the value is not an integer, it is rounded off to the nearest integer. For example, 5.5 is rounded off to 5.|
| position | [BadgePosition](#badgeposition) | No| Position to display the badge relative to the parent component.<br>Default value: **BadgePosition.RightTop**|
| position | [BadgePosition](#badgeposition)\|[Position<sup>10+</sup>](ts-types.md#position8) | No| Position to display the badge relative to the parent component.<br>Default value: **BadgePosition.RightTop**<br>**NOTE**<br> This parameter cannot be set in percentage. If it is set to an invalid value, the default value **(0,0)** will be used.|
| maxCount | number | No| Maximum number of notifications. When the maximum number is reached, only **maxCount+** is displayed.<br>Default value: **99**<br>Value range: [-2147483648, 2147483647]<br>If the value is not an integer, it is rounded off to the nearest integer. For example, 5.5 is rounded off to 5.|
| style | [BadgeStyle](#badgestyle) | Yes| Style of the badge, including the font color, font size, badge color, and badge size.|
......@@ -44,7 +44,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| value | string | Yes| - | Prompt content.|
| position | [BadgePosition](#badgeposition) | No| BadgePosition.RightTop | Position to display the badge relative to the parent component.|
| position | [BadgePosition](#badgeposition)\|[Position<sup>10+</sup>](ts-types.md#position8) | No| BadgePosition.RightTop | Position to display the badge relative to the parent component.|
| style | [BadgeStyle](#badgestyle) | Yes| - | Style of the badge, including the font color, font size, badge color, and badge size.|
## BadgePosition
......
......@@ -23,10 +23,11 @@ The **\<Grid>** component accepts only **\<[GridItem](ts-container-griditem.md)>
>
> If the values of [if/else](../../quick-start/arkts-rendering-control-ifelse.md), [ForEach](../../quick-start/arkts-rendering-control-foreach.md), and [LazyForEach](../../quick-start/arkts-rendering-control-lazyforeach.md) change, the indexes of subnodes are updated.
>
> Child components of **\<Grid>** whose **visibility** attribute is set to **Hidden** or **None** are included in the index calculation.
> The child component that has the **visibility** attribute set to **Hidden** or **None** is included in the index calculation.
>
> Child components of **\<Grid>** whose **visibility** attribute is set to **None** are not displayed, but still take up the corresponding cells.
> The child component that has the **visibility** attribute set to **None** is not displayed, but still takes up the corresponding cell.
>
> The child component that has the **position** attribute set takes up the corresponding cell, and is offset by the distance specified by **position** relative to the upper left corner of the grid. This child component does not scroll with the corresponding cell and is not displayed after the corresponding cell extends beyond the display range of the grid.
## APIs
......@@ -61,6 +62,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| supportAnimation<sup>8+</sup> | boolean | Whether to enable animation. Currently, the grid item drag animation is supported.<br>Default value: **false**|
| edgeEffect<sup>10+</sup> | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. The spring effect and shadow effect are supported.<br>Default value: **EdgeEffect.None**<br>|
| enableScrollInteraction<sup>10+</sup> | boolean | Whether to support scroll gestures. When this attribute is set to **false**, scrolling by finger or mouse is not supported, but the scrolling controller API is not affected.<br>Default value: **true** |
| nestedScroll<sup>10+</sup> | [NestedScrollOptions](ts-container-scroll.md#nestedscrolloptions10) | Nested scrolling options. You can set the nested scrolling mode in the forward and backward directions to implement scrolling linkage with the parent component.|
Depending on the settings of the **rowsTemplate** and **columnsTemplate** attributes, the **\<Grid>** component supports the following layout modes:
......@@ -71,10 +73,6 @@ Depending on the settings of the **rowsTemplate** and **columnsTemplate** attrib
- If the width and height of a grid are not set, the grid adapts to the size of its parent component by default.
- The size of the grid rows and columns is the size of the grid content area minus the gap between rows and columns. It is allocated based on the proportion of each row and column.
- By default, the grid items fill the entire grid.
- In this mode, if a grid item has both **rowStart** and **columnStart** set, it is placed in the position based on the settings. If a grid item already exists in this position, overlapping occurs.
- If a grid item has only **rowStart** or **columnStart** set, the system traverses the previous grid item layout to search for an idle position that meets the settings. If no idle position meets the requirements, the grid item is not laid out.
- If a grid item has neither **rowStart** nor **columnStart** set, the system traverses the previous grid item layout to search for an idle position. If no idle position is available, the grid item is not laid out.
- If a grid item has **rowEnd** set but not **rowStart**, **rowStart** is considered as set to the same value as **rowEnd**. If a grid item has **columnEnd** set but not **columnStart**, **columnStart** is considered as set to the same value as **columnEnd**.
2. Either **rowsTemplate** or **columnsTemplate** is set
......@@ -84,19 +82,14 @@ Depending on the settings of the **rowsTemplate** and **columnsTemplate** attrib
- In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, minCount, and **cellLength**.
- The cross axis size of the grid is the cross axis size of the grid content area minus the gaps along the cross axis. It is allocated based on the proportion of each row and column.
- The main axis size of the grid is the maximum height of all grid items in the cross axis direction of the current grid.
- In this mode, if a grid item has both **rowStart** and **columnStart** set, it is placed in the position based on the settings. If a grid item already exists in this position, overlapping occurs.
- If a grid item has only **rowStart** or **columnStart** set, the system traverses the previous grid item layout to search for an idle position that meets the settings.
- If a grid item has neither **rowStart** nor **columnStart** set, the system traverses the previous grid item layout to search for an idle position.
- If a grid item has **rowEnd** set but not **rowStart**, **rowStart** is considered as set to the same value as **rowEnd**. If a grid item has **columnEnd** set but not **columnStart**, **columnStart** is considered as set to the same value as **columnEnd**.
3. Neither **rowsTemplate** nor **columnsTemplate** is set
- The **\<Grid>** component arranges elements in the direction specified by **layoutDirection**. The number of columns is jointly determined by the grid width, width of the first element, **minCount**, **maxCount**, and **columnsGap**.
- The number of rows is jointly determined by the grid height, height of the first element, **cellLength**, and **rowsGap**. Elements outside the determined range of rows and columns are not displayed and cannot be viewed through scrolling.
- In this mode, only the following attributes take effect: **layoutDirection**, **maxCount**, **minCount**, **cellLength**, **editMode**, **columnsGap**, and **rowsGap**.
- When **layoutDirection** is set to **Row**, elements are arranged from left to right. When a row is full, a new row will be added. If the remaining height is insufficient, no more elements will be laid out, and the top of the content is centered.
- When **layoutDirection** is set to **Column**, elements are arranged from top to bottom. When a column is full, a new column will be added. If the remaining height is insufficient, no more elements will be laid out, and the top of the content is centered.
- In this mode, **rowStart** and **columnStart** of the grid item do not take effect.
- When **layoutDirection** is set to **Row**, elements are arranged row by row from left to right. If the remaining height is insufficient, no more elements will be laid out, and the whole content is centered at the top.
- When **layoutDirection** is set to **Column**, elements are arranged column by column from top to bottom. If the remaining height is insufficient, no more elements will be laid out, and the whole content is centered at the top.
## GridDirection<sup>8+</sup>
......@@ -141,6 +134,8 @@ In addition to the [universal events](ts-universal-events-click.md), the followi
## Example
### Example 1
```ts
// xxx.ets
@Entry
......@@ -196,12 +191,11 @@ struct GridExample {
console.info(first.toString())
})
.onScrollBarUpdate((index: number, offset: number) => {
return {totalOffset: (index / 5) * (80 + 10) - 10 + offset, totalLength: 80 * 5 + 10 * 4}
return {totalOffset: (index / 5) * (80 + 10) - 10 - offset, totalLength: 80 * 5 + 10 * 4}
})
.width('90%')
.backgroundColor(0xFAEEE0)
.height(300)
.scrollBar(BarState.Off)
Button('next page')
.onClick(() => {// Click to go to the next page.
this.scroller.scrollPage({ next: true })
......@@ -212,3 +206,82 @@ struct GridExample {
```
![en-us_image_0000001219744183](figures/en-us_image_0000001219744183.gif)
### Example 2
1. Set **editMode\(true\)** to enable the grid to enter editing mode, where the user can drag the grid items.
2. Through [onItemDragStart](#events), set the image to be displayed during dragging.
3. Through [onItemDrop](#events), obtain the initial position of the dragged item and the position to which the dragged item will be dropped. Through [onDrag](#events), complete the array position exchange logic.
```ts
@Entry
@Component
struct GridExample {
@State numbers: String[] = []
scroller: Scroller = new Scroller()
@State text: string = 'drag'
@Builder pixelMapBuilder () { // Style for the drag event.
Column() {
Text(this.text)
.fontSize(16)
.backgroundColor(0xF9CF93)
.width(80)
.height(80)
.textAlign(TextAlign.Center)
}
}
aboutToAppear() {
for (let i = 1;i <= 15; i++) {
this.numbers.push(i + '')
}
}
changeIndex(index1: number, index2: number) { // Exchange the array position.
[this.numbers[index1], this.numbers[index2]] = [this.numbers[index2], this.numbers[index1]];
}
build() {
Column({ space: 5 }) {
Grid(this.scroller) {
ForEach(this.numbers, (day: string) => {
GridItem() {
Text(day)
.fontSize(16)
.backgroundColor(0xF9CF93)
.width(80)
.height(80)
.textAlign(TextAlign.Center)
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Up) {
this.text = day
}
})
}
})
}
.columnsTemplate('1fr 1fr 1fr')
.columnsGap(10)
.rowsGap(10)
.onScrollIndex((first: number) => {
console.info(first.toString())
})
.width('90%')
.backgroundColor(0xFAEEE0)
.height(300)
.editMode(true) // Enable the grid to enter editing mode, where the user can drag the grid items.
.onItemDragStart((event: ItemDragInfo, itemIndex: number) => { // Triggered when a grid item starts to be dragged.
return this.pixelMapBuilder() // Set the image to be displayed during dragging.
})
.onItemDrop((event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => { // Triggered when the dragged item is dropped on the drop target of the grid.
console.info('beixiang' + itemIndex + '', insertIndex + '') // itemIndex indicates the initial position of the dragged item. insertIndex indicates the position to which the dragged item will be dropped.
this.changeIndex(itemIndex, insertIndex)
})
}.width('100%').margin({ top: 5 })
}
}
```
<!--no_check-->
\ No newline at end of file
......@@ -40,6 +40,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| miniHeight | string \| number | Panel height in the **PanelMode.Mini** mode.<br>Default value: **48**<br>Unit: vp<br>**NOTE**<br>This attribute cannot be set in percentage.|
| show | boolean | Whether to show the panel.|
| backgroundMask<sup>9+</sup>|[ResourceColor](ts-types.md#resourcecolor)|Background mask of the panel.|
| showCloseIcon<sup>10+</sup> | boolean | Whether to display the close icon. The value **true** means to display the close icon, and **false** means the opposite.<br>Default value: **false**|
## PanelType
......@@ -93,6 +94,7 @@ struct PanelExample {
.type(PanelType.Foldable).mode(PanelMode.Half)
.dragBar(true) // The drag bar is enabled by default.
.halfHeight(500) // The panel height is half of the screen height by default.
.showCloseIcon(true) // Display the close icon.
.onChange((width: number, height: number, mode: PanelMode) => {
console.info(`width:${width},height:${height},mode:${mode}`)
})
......
......@@ -8,22 +8,22 @@ You can set the background for a component.
## Attributes
| Name| Type| Description|
| -------- | -------- | -------- |
| background<sup>10+</sup> | builder: [CustomBuilder](ts-types.md#custombuilder8),<br>options?: {align?:[Alignment](ts-appendix-enums.md#alignment)} | Background color of the component.<br>**builder**: custom background.<br>**align**: alignment mode between the custom background and the component.<br>If **background**, **backgroundColor**, and **backgroundImage** are set at the same time, they will all take effect, with **background** at the top layer.|
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component.<br>Since API version 9, this API is supported in ArkTS widgets.|
| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),<br>repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | **src**: image address, which can be the address of an Internet or a local image or a Base64 encoded image. SVG images are not supported.<br>**repeat**: whether the background image is repeated. By default, the background image is not repeated. If the set image has a transparent background and **backgroundColor** is set, the image is overlaid on the background color.<br>Since API version 9, this API is supported in ArkTS widgets.|
| backgroundImageSize | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} \| [ImageSize](ts-appendix-enums.md#imagesize) | Width and height of the background image. If the input is a **{width: Length, height: Length}** object and only one attribute is set, the other attribute is the set value multiplied by the original aspect ratio of the image. By default, the original image aspect ratio remains unchanged.<br>The value range of **width** and **height** is [0, +∞).<br>Default value: **ImageSize.Auto**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>A value less than 0 evaluates to the value **0**. If **height** is set but **width** is not, the image width is adjusted based on the original aspect ratio of the image.|
| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component, that is, the coordinates relative to the upper left corner of the component.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>} <br> When **x** and **y** are set in percentage, the offset is calculated based on the width and height of the component.<br>Since API version 9, this API is supported in ArkTS widgets.|
| Name | Type | Description |
| -------------------------------- | ---------------------------------------- | ---------------------------------------- |
| background<sup>10+</sup> | builder: [CustomBuilder](ts-types.md#custombuilder8),<br>options?: {align?:[Alignment](ts-appendix-enums.md#alignment)} | Background color of the component.<br>**builder**: custom background.<br>**align**: alignment mode between the custom background and the component.<br>If **background**, **backgroundColor**, and **backgroundImage** are set at the same time, they will all take effect, with **background** at the top layer.<br>This attribute cannot be nested.|
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component.<br>Since API version 9, this API is supported in ArkTS widgets.|
| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),<br>repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | **src**: image address, which can be the address of an Internet or a local image or a Base64 encoded image. SVG images are not supported.<br>**repeat**: whether the background image is repeated. By default, the background image is not repeated. If the set image has a transparent background and **backgroundColor** is set, the image is overlaid on the background color.<br>Since API version 9, this API is supported in ArkTS widgets.|
| backgroundImageSize | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} \| [ImageSize](ts-appendix-enums.md#imagesize) | Width and height of the background image. If the input is a **{width: Length, height: Length}** object and only one attribute is set, the other attribute is the set value multiplied by the original aspect ratio of the image. By default, the original image aspect ratio remains unchanged.<br>The value range of **width** and **height** is [0, +∞).<br>Default value: **ImageSize.Auto**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>A value less than 0 evaluates to the value **0**. If **height** is set but **width** is not, the image width is adjusted based on the original aspect ratio of the image.|
| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component, that is, the coordinates relative to the upper left corner of the component.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>} <br> When **x** and **y** are set in percentage, the offset is calculated based on the width and height of the component.<br>Since API version 9, this API is supported in ArkTS widgets.|
| backgroundBlurStyle<sup>9+</sup> | value:[BlurStyle](ts-appendix-enums.md#blurstyle9),<br>options<sup>10+</sup>?:[BackgroundBlurStyleOptions](#backgroundblurstyleoptions10) | Background blur style applied between the content and the background.<br>**value**: settings of the background blur style, including the blur radius, mask color, mask opacity, saturation, and brightness.<br>**options**: background blur options. Optional.<br>This API is supported in ArkTS widgets.|
## BackgroundBlurStyleOptions<sup>10+</sup>
| Name | Type | Mandatory| Description |
| --------------------------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| colorMode<sup>10+</sup> | [ThemeColorMode](ts-appendix-enums.md#themecolormode10) | No | Color mode used for the background blur.<br>Default value: **ThemeColorMode.System**|
| adaptiveColor<sup>10+</sup> | [AdaptiveColor](ts-appendix-enums.md#adaptivecolor10) | No | Adaptive color mode.<br>Default value: **AdaptiveColor.Default**|
| scale<sup>10+</sup> | number | No | Blurredness of the background material. This API is a system API.<br>Default value: **1.0**<br>Value range: [0.0, 1.0]<br>|
| Name | Type | Mandatory | Description |
| ------------- | ---------------------------------------- | ---- | ---------------------------------------- |
| colorMode | [ThemeColorMode](ts-appendix-enums.md#themecolormode10) | No | Color mode used for the background blur.<br>Default value: **ThemeColorMode.System**|
| adaptiveColor | [AdaptiveColor](ts-appendix-enums.md#adaptivecolor10) | No | Adaptive color mode.<br>Default value: **AdaptiveColor.Default**|
| scale | number | No | Blurredness of the background material. This API is a system API.<br>Default value: **1.0**<br>Value range: [0.0, 1.0]<br>|
## Example
......
......@@ -8,22 +8,22 @@ You can draw an image around a component.
## Attributes
| Name | Type | Description |
| ---------- | ---------------------------------------- | --------------------------------------- |
| borderImage | [BorderImageOption](#borderimageoption) | Border image or border gradient.<br>This API is supported in ArkTS widgets.|
| Name | Type | Description |
| ----------- | ---------------------------------------- | -------------------------------------- |
| borderImage | [BorderImageOption](#borderimageoption) | Border image or border gradient.<br>This API is supported in ArkTS widgets.|
## BorderImageOption
This API is supported in ArkTS widgets.
| Name | Type | Description |
| ---------- | ---------------------------------------- | --------------------------------------- |
| source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | Source or gradient color of the border image.<br>**NOTE**<br>The border image source applies only to container components, such as **\<Row>**, **\<Column>**, and **\<Flex>**.|
| slice | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Slice width of the border image.<br>Default value: **0** |
| width | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Width of the border image.<br>Default value: **0** |
| outset | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Amount by which the border image is extended beyond the border box.<br>Default value: **0** |
| repeat | [RepeatMode](#repeatmode) | Repeat mode of the border image.<br>Default value: **RepeatMode.Stretch**|
| fill | boolean | Whether to fill the center of the border image.<br>Default value: **false** |
| Name | Type | Description |
| ------ | ---------------------------------------- | ---------------------------------------- |
| source | string \| [Resource](ts-types.md#resource) \| [linearGradient](ts-universal-attributes-gradient-color.md) | Source or gradient color of the border image.<br>**NOTE**<br>The border image source applies only to container components, such as **\<Row>**, **\<Column>**, and **\<Flex>**.|
| slice | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Slice width of the border image.<br>Default value: **0** |
| width | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Width of the border image.<br>Default value: **0** |
| outset | [Length](ts-types.md#length) \| [EdgeWidths](ts-types.md#edgewidths9) | Amount by which the border image is extended beyond the border box.<br>Default value: **0** |
| repeat | [RepeatMode](#repeatmode) | Repeat mode of the border image.<br>Default value: **RepeatMode.Stretch** |
| fill | boolean | Whether to fill the center of the border image.<br>Default value: **false** |
## RepeatMode
......
......@@ -8,13 +8,13 @@
## Attributes
| Name | Type | Description |
| ---------- | ------------------------------------------- | ------------------------------------------------------------ |
| flexBasis | number \| string | Base size of the component in the main axis of the parent container.<br>Default value: **'auto'** (indicating that the base size of the component in the main axis is the original size of the component)<br>This attribute cannot be set in percentage.<br>Since API version 9, this API is supported in ArkTS widgets.|
| flexGrow | number | Percentage of the parent container's remaining space that is allocated to the component.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.|
| flexShrink | number | Percentage of the parent container's shrink size that is allocated to the component.<br>When the parent container is **\<Row>** or **\<Column>**, the default value is **0**.<br> When the parent container is **\<Flex>**, the default value is **1**.<br>Since API version 9, this API is supported in ArkTS widgets.|
| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | Alignment mode of the child components along the cross axis of the parent container. The setting overwrites the **alignItems** setting of the parent container (**\<Flex>**, **\<Column>**, **\<Row>**, or **\<GridRow>**).<br>**\<GridCol>** can have the **alignsSelf** attribute bound to change its own layout along the cross axis.<br>Default value: **ItemAlign.Auto**<br>Since API version 9, this API is supported in ArkTS widgets.|
| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts.<br>The value can be a number greater than or equal to 0 or a string that can be converted to a number.|
| Name | Type | Description |
| ------------ | ---------------------------------------- | ---------------------------------------- |
| flexBasis | number \| string | Base size of the component in the main axis of the parent container.<br>Default value: **'auto'** (indicating that the base size of the component in the main axis is the original size of the component)<br>This attribute cannot be set in percentage.<br>Since API version 9, this API is supported in ArkTS widgets.|
| flexGrow | number | Percentage of the parent container's remaining space that is allocated to the component.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.|
| flexShrink | number | Percentage of the parent container's shrink size that is allocated to the component.<br>When the parent container is **\<Row>** or **\<Column>**, the default value is **0**.<br> When the parent container is **\<Flex>**, the default value is **1**.<br>Since API version 9, this API is supported in ArkTS widgets.|
| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | Alignment mode of the child components along the cross axis of the parent container. The setting overwrites the **alignItems** setting of the parent container (**\<Flex>**, **\<Column>**, **\<Row>**, or **\<GridRow>**).<br>**\<GridCol>** can have the **alignsSelf** attribute bound to change its own layout along the cross axis.<br>Default value: **ItemAlign.Auto**<br>Since API version 9, this API is supported in ArkTS widgets.|
| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.<br>Default value: **0**<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts.<br>The value can be a number greater than or equal to 0 or a string that can be converted to a number.|
## Example
......
......@@ -9,14 +9,15 @@ Layout constraints refer to constraints on the aspect ratio and display priority
## Attributes
| Name | Type| Description |
| --------------- | -------- | ------------------------------------------------------------ |
| aspectRatio | number | Aspect ratio of the component, which can be obtained using the following formula: Width/Height.<br>Since API version 9, this API is supported in ArkTS widgets.|
| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.<br>The digits after the decimal point are not counted in determining the display priority. That is, numbers in the [x, x + 1) range are considered to represent the same priority. For example, **1.0** and **1.9** represent the same priority.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** (single-row) container components.|
| Name | Type | Description |
| --------------- | ------ | ---------------------------------------- |
| aspectRatio | number | Aspect ratio of the component, which can be obtained using the following formula: Width/Height.<br>Since API version 9, this API is supported in ArkTS widgets.|
| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.<br>The digits after the decimal point are not counted in determining the display priority. That is, numbers in the [x, x + 1) range are considered to represent the same priority. For example, **1.0** and **1.9** represent the same priority.<br>Since API version 9, this API is supported in ArkTS widgets.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** (single-row) container components.|
## Example
### Example 1
```ts
// xxx.ets
@Entry
......@@ -78,6 +79,8 @@ struct AspectRatioExample {
![en-us_image_0000001212218476](figures/en-us_image_0000001212218476.gif)
### Example 2
```ts
class ContainerInfo {
label: string = '';
......
......@@ -12,37 +12,39 @@ A context menu – a vertical list of items – can be bound to a component and
## Attributes
| Name | Type | Description |
| ---------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| bindMenu | content: Array<[MenuItem](#menuitem)&gt; \| [CustomBuilder](ts-types.md#custombuilder8),<br>options: [MenuOptions](#menuoptions10) | Menu bound to the component, which is displayed when you click the component. A menu item can be a combination of text and icons or a custom component.<br>**content**: array of menu item text and icons or custom components.<br>**options**: parameters of the context menu. Optional.|
| bindContextMenu<sup>8+</sup> | content: [CustomBuilder](ts-types.md#custombuilder8),<br>responseType: [ResponseType](ts-appendix-enums.md#responsetype8)<br>options: [ContextMenuOptions](#contextmenuoptions10) | Context menu bound to the component, which is displayed when the user long-presses or right-clicks the component. Only custom menu items are supported.<br>**responseType**: how the context menu triggered, which can be long-press or right-click. Mandatory. <br>**options**: parameters of the context menu. Optional.|
| Name | Type | Description |
| ---------------------------- | ---------------------------------------- | ---------------------------------------- |
| bindMenu | content: Array<[MenuItem](#menuitem)&gt; \| [CustomBuilder](ts-types.md#custombuilder8),<br>options?: [MenuOptions](#menuoptions10) | Menu bound to the component, which is displayed when the user clicks the component. A menu item can be a combination of text and icons or a custom component.<br>**content**: array of menu item icons and text, or custom component.<br>**options**: parameters of the context menu.|
| bindContextMenu<sup>8+</sup> | content: [CustomBuilder](ts-types.md#custombuilder8),<br>responseType: [ResponseType](ts-appendix-enums.md#responsetype8)<br>options?: [ContextMenuOptions](#contextmenuoptions10) | Context menu bound to the component, which is displayed when the user long-presses or right-clicks the component. Only custom menu items are supported.<br>**responseType**: how the context menu is triggered, which can be long-press or right-click.<br>**options**: parameters of the context menu.|
## MenuItem
| Name | Type | Mandatory| Description |
| ------------------ | -------------------------------------- | ---- | ---------------------- |
| value | string | Yes | Menu item text. |
| icon<sup>10+</sup> | [ResourceStr](ts-types.md#resourcestr) | No | Menu item icon. |
| action | () =&gt; void | Yes | Action triggered when a menu item is clicked.|
| Name | Type | Mandatory | Description |
| ------------------ | -------------------------------------- | ---- | ----------- |
| value | string | Yes | Menu item text. |
| icon<sup>10+</sup> | [ResourceStr](ts-types.md#resourcestr) | No | Menu item icon. |
| action | () =&gt; void | Yes | Action triggered when a menu item is clicked.|
## MenuOptions<sup>10+</sup>
| Name | Type | Mandatory| Description |
| ------ | -------------------------------- | ---- | ------------------------------------------------------ |
| title | string | No | Menu title. |
| offset | [Position](ts-types.md#position8) | No | Offset for showing the context menu, which should not cause the menu to extend beyond the screen.|
| placement | [Placement](ts-appendix-enums.md#placement8) | No| Preferred position of the context menu. If the set position is insufficient for holding the component, it will be automatically adjusted.<br>**NOTE**<br>Setting **placement** to **undefined** or **null** is equivalent to not setting it at all.|
| onAppear | () =&gt; void | No| Callback triggered when the menu is displayed.|
| onDisappear | () =&gt; void | No| Callback triggered when the menu is hidden.|
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | ---------------------------------------- |
| title | string | No | Menu title.<br>**NOTE**<br>This parameter is available only when **content** is set to Array<[MenuItem](#menuitem)>.|
| offset | [Position](ts-types.md#position8) | No | Offset for showing the context menu, which should not cause the menu to extend beyond the screen. |
| placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the context menu. If the set position is insufficient for holding the component, it will be automatically adjusted.<br>**NOTE**<br>If **placement** is set to **undefined** or **null** or is not set, the default value [BottomLeft](ts-appendix-enums.md#placement8) is used, and the position is relative to the parent component.|
| onAppear | () =&gt; void | No | Callback triggered when the menu is displayed. |
| onDisappear | () =&gt; void | No | Callback triggered when the menu is hidden. |
## ContextMenuOptions<sup>10+</sup>
| Name | Type | Mandatory| Description |
| ----------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| offset | [Position](ts-types.md#position8) | No | Offset for showing the context menu, which should not cause the menu to extend beyond the screen. |
| placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the context menu. If the set position is insufficient for holding the component, it will be automatically adjusted.<br>**NOTE**<br>Setting **placement** to **undefined** or **null** is equivalent to not setting it at all.|
| onAppear | () =&gt; void | No | Callback triggered when the menu is displayed. |
| onDisappear | () =&gt; void | No | Callback triggered when the menu is hidden. |
| Name | Type | Mandatory | Description |
| ----------- | ---------------------------------------- | ---- | ---------------------------------------- |
| offset | [Position](ts-types.md#position8) | No | Offset for showing the context menu, which should not cause the menu to extend beyond the screen. |
| placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the context menu. If the set position is insufficient for holding the component, it will be automatically adjusted.<br>**NOTE**<br>Setting **placement** to **undefined** or **null** is equivalent to not setting it at all, and the context menu is displayed where the mouse is clicked.|
| enableArrow | boolean | No | Whether to display an arrow. If the size and position of the context menu are insufficient for holding an arrow, no arrow is displayed.<br>Default value: **false**, indicating that no arrow is displayed<br>**NOTE**<br>An arrow is displayed in the position specified by **placement**. If **placement** is not set or its value is invalid, the arrow is displayed above the target. If the position is insufficient for holding the arrow, it is automatically adjusted.|
| arrowOffset | [Length](ts-types.md#length) | No | Offset of the arrow relative to the context menu. When the arrow is placed in a horizontal position with the context menu: The value indicates the distance from the arrow to the leftmost; the arrow is centered by default. When the arrow is placed in a vertical position with the context menu: The value indicates the distance from the arrow to the top; the arrow is centered by default. The offset settings take effect only when the value is valid, can be converted to a number greater than 0, and does not cause the arrow to extend beyond the safe area of the context menu. The value of **placement** determines whether the offset is horizontal or vertical.|
| onAppear | () =&gt; void | No | Callback triggered when the menu is displayed. |
| onDisappear | () =&gt; void | No | Callback triggered when the menu is hidden. |
## Example
......@@ -133,7 +135,7 @@ struct MenuExample {
### Example 3
Context Menu (Displayed Upon Right-Clicking)
Context Menu (Displayed Upon Right-Click)
```ts
// xxx.ets
......@@ -166,3 +168,46 @@ struct ContextMenuExample {
}
}
```
### Example 4
Directive Menu (Displayed Upon Right-Click)
```ts
// xxx.ets
@Entry
@Component
struct DirectiveMenuExample {
@Builder MenuBuilder() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('Options')
Divider().strokeWidth(2).margin(5).color('#F0F0F0')
Text('Hide')
Divider().strokeWidth(2).margin(5).color('#F0F0F0')
Text('Exit')
}
.width(200)
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Column() {
Text("DirectiveMenuExample")
.fontSize(20)
.width('100%')
.height("25%")
.backgroundColor('#F0F0F0')
.textAlign(TextAlign.Center)
.bindContextMenu(this.MenuBuilder, ResponseType.RightClick, {
enableArrow: true,
placement: Placement.Bottom
})
}
}
.width('100%')
.height('100%')
}
}
```
![en-us_image_0000001689126950](figures/en-us_image_0000001689126950.png)
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册