未验证 提交 8c512bd4 编写于 作者: O openharmony_ci 提交者: Gitee

!12715 翻译完成 10356+10479+10530+10335+10008+11808+11740+11583

Merge pull request !12715 from ester.zhou/TR-10356
......@@ -30,9 +30,8 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| flex-direction | string | row | No | Main axis direction of the flex container, which defines how items are placed in the container. Available values are as follows:<br>- **column**: Items are placed vertically from top to bottom.<br>- **row**: Items are placed horizontally from left to right.|
| flex-wrap | string | nowrap | No | Whether items in the flex container are displayed in a single line or multiple lines. The value cannot be dynamically updated. Available values are as follows:<br>- **nowrap**: Flex items are displayed in a single line.<br>- **wrap**: Flex items are displayed in multiple lines.|
| justify-content | string | flex-start | No | How items are aligned along the main axis of the flex container. Available values are as follows:<br>- **flex-start**: Items are packed toward the start edge of the container along the main axis.<br>- **flex-end**: Items are packed toward the end edge of the container along the main axis.<br>- **center**: Items are packed toward the center of the container along the main axis.<br>- **space-between**: Items are positioned with space between the rows.<br>- **space-around**: Items are positioned with space before, between, and after the rows.<br>- **space-evenly**<sup>5+</sup>: Items are distributed within the container along the main axis, with even space between each two.|
| align-items | string | stretch<br>| No | How items are aligned along the cross axis of the flex container. Available values are as follows:<br>- **stretch**: Items are stretched to the same height or width as the container along the cross axis.<br>- **flex-start**: Items are packed toward the start edge of the cross axis.<br>- **flex-end**: Items are packed toward the end edge of the cross axis.<br>- **center**: Items are packed toward the center of the cross axis.<br>- **baseline**: In a vertical layout, items are aligned to the start of the cross axis, which means that this value is equivalent of **flex-start**. In a horizontal layout, items are aligned with the text baseline if there is text involved, and aligned to the bottom otherwise.|
| align-items | string | stretch<br>| No | How items are aligned along the cross axis in a flex container. Available values are as follows:<br>- **stretch**: Items are stretched to the same height or width as the container along the cross axis.<br>- **flex-start**: Items are packed toward the start edge of the cross axis.<br>- **flex-end**: Items are packed toward the end edge of the cross axis.<br>- **center**: Items are packed toward the center of the cross axis.<br>- **baseline**: In a vertical layout, items are aligned to the start of the cross axis, which means that this value is equivalent of **flex-start**. In a horizontal layout, items are aligned with the text baseline if there is text involved, and aligned to the bottom otherwise.|
| align-content | string | flex-start | No | Multi-row alignment mode when there is extra space in the cross axis. Available values are as follows:<br>- **flex-start**: All rows are packed toward the start edge of the cross axis. The start edge of the cross axis of the first row is aligned with the start edge of the cross axis of the container. All subsequent rows are aligned with the previous row.<br>- **flex-end**: All rows are packed toward the end edge of the cross axis. The end of the cross axis of the last row is aligned with the end of the cross axis of the container. All subsequent rows are aligned with the previous row.<br>- **center**: All rows are packed toward the center of the cross axis. Rows are close to each other and aligned with the center of the container. The spacing between the start edge of the container's cross axis and the first row is equal to the spacing between the end edge of the container's cross axis and the last row.<br>- **space-between**: All rows are evenly distributed in the container. The spacing between two adjacent rows is the same. The start and end edges of the container's cross axis are aligned with the edges of the first and last rows, respectively.<br>- **space-around**: All rows are evenly distributed in the container. The spacing between two adjacent rows is the same. The spacing between the start edge of the container's cross axis and the first row and that between the end edge and the last row are half of the spacing between two adjacent rows.|
| display | string | flex | No | Type of the view box of the item. The value cannot be dynamically updated. Available values are as follows:<br>- **flex**: flexible layout<br>- **grid**: grid layout<br>- **none**: not rendered<br>- **inline-flex**<sup>9+</sup>: layout with the **flex** and **inline-block** effects.|
| grid-template-[columns\|rows] | string | 1 row, 1 column | No | Number of rows and columns in the current grid layout. If this attribute is not set, one row and one column are displayed by default. This attribute is valid only when **display** is set to **grid**.<br>Below are some example values of **grid-template-columns**:<br>- **50px 100px 60px**: There are three columns. The first column is 50 px, the second column is 100 px, and the third column is 60 px.<br>- **1fr 1fr 2fr**: There are three columns, and the width allowed by the parent component is divided into four equal shares. The first column occupies one share, the second column occupies one share, and the third column occupies two shares.<br>- **30% 20% 50%**: There are three columns. The first column occupies 30% of the total width allowed by the parent component, the second column occupies 20%, and the third column occupies 50%.<br>- **repeat (2,100px)**: There are two columns. The first column is 100 px, and the second column is 100 px.<br>- **repeat(auto-fill,100px)**<sup>5+</sup>: Each column is 100 px and repeats to fill the cross axis. The number of columns is calculated based on the column size and the cross axis size.<br>- **auto 1fr 1fr**: There are three columns. The first column is adaptive to the width required by its child components. The remaining space is divided into two equal shares, one share occupied by each of the rest two columns.|
| grid-[columns\|rows]-gap | &lt;length&gt; | 0 | No | Size of the gap between two consecutive rows or columns in a grid layout. You can also use **grid-gap** to set the same size of the gap between rows and columns. This attribute is valid only when **display** is set to **grid**.|
| grid-row-[start\|end] | number | - | No | Start and end row numbers of the current item in the grid layout. This attribute is valid only when the item's parent component is a **\<div>** container whose **display** style is set to **grid**.|
......@@ -47,6 +46,8 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
## Events
In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported.
| Name | Parameter | Description |
......@@ -246,26 +247,28 @@ In addition to the [universal methods](js-components-common-methods.md), the fol
```html
<!-- xxx.hml -->
<div class="container">
<div class="content" ondragstart="dragstart" ondrag="drag" ondragend="dragend" style="position: absolute;left: {{left}};top:{{top}};">
<div class="content" ondragstart="dragstart" ondrag="drag" ondragend="dragend" style="position: absolute;left: {{left}};top: {{top}};">
</div>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
}
.content{
width: 200px;
height: 200px;
background-color: red;
}
/* xxx.css */
.container {
flex-direction: column;
width: 100%;
height: 100%;
}
.content {
width: 200px;
height: 200px;
background-color: red;
}
```
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
data:{
left:0,
......@@ -281,10 +284,10 @@ In addition to the [universal methods](js-components-common-methods.md), the fol
this.top = e.globalY;
},
dragend(e){
prompt.showToast({
promptAction.showToast({
message: 'End Drag'
})
},
}
}
```
......@@ -318,7 +321,7 @@ In addition to the [universal methods](js-components-common-methods.md), the fol
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
data:{
left:0,
......@@ -329,22 +332,22 @@ In addition to the [universal methods](js-components-common-methods.md), the fol
this.top = e.globalY;
},
dragenter(e){
prompt.showToast({
promptAction.showToast({
message: 'enter'
})
},
dragover(e){
prompt.showToast({
promptAction.showToast({
message: 'over'
})
},
dragleave(e){
prompt.showToast({
promptAction.showToast({
message: 'leave'
})
},
drop(e){
prompt.showToast({
promptAction.showToast({
message: 'drop'
})
}
......@@ -357,8 +360,8 @@ In addition to the [universal methods](js-components-common-methods.md), the fol
```html
<!-- xxx.hml -->
<div class="container">
<div class="content "onpinchstart="pinchstart" onpinchend="pinchend" onpinchupdate="pinchupdate"
onpinchcancel=" pinchcancel">
<div class="content" onpinchstart="pinchstart" onpinchend="pinchend" onpinchupdate="pinchupdate"
onpinchcancel="pinchcancel">
</div>
</div>
```
......@@ -370,12 +373,13 @@ In addition to the [universal methods](js-components-common-methods.md), the fol
justify-content: center;
align-items: center;
width: 454px;
height: 454px;}
.content{
height: 454px;
}
.content {
width: 400px;
height: 400px;
background-color: aqua;
margin:30px
margin: 30px;
}
```
......
# Blank
The **\<Blank>** component is able to automatically fill the empty spaces in the container along the main axis. It is valid only when the parent component is **\<Row>** or **\<Column>**.
The **\<Blank>** component is able to automatically fill the empty spaces in the container along the main axis. It is valid only when the parent container is **\<Row>** or **\<Column>**.
> **NOTE**
>
......@@ -32,7 +32,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
## Example
### Example 1
The sample below shows how the **\<Blank>** component fills the empty spaces in the container in landscape and portrait modes.
```ts
// xxx.ets
@Entry
......@@ -57,3 +58,36 @@ Portrait mode
Landscape mode
![en-us_image_0000001212378418](figures/en-us_image_0000001212378418.gif)
### Example 2
Set the **min** parameter when the width of the parent container of the **\<Blank>** component is not set.
```ts
// xxx.ets
@Entry
@Component
struct BlankExample {
build() {
Column({ space: 20 }) {
// If the width of the parent container is not set, the \<Blank> component becomes invalid. In this case, you can set min to specify the minimum width of the \<Blank> component.
Row() {
Text('Bluetooth').fontSize(18)
Blank().color(Color.Yellow)
Toggle({ type: ToggleType.Switch })
}.backgroundColor(0xFFFFFF).borderRadius(15).padding({ left: 12 })
Row() {
Text('Bluetooth').fontSize(18)
// Set the minimum width to 160.
Blank('160').color(Color.Yellow)
Toggle({ type: ToggleType.Switch })
}.backgroundColor(0xFFFFFF).borderRadius(15).padding({ left: 12 })
}.backgroundColor(0xEFEFEF).padding(20).width('100%')
}
}
```
If the width of the parent container is not set, set **min** to specify the minimum width of the **\<Blank>** component.
![blankmin](figures/blankmin.png)
......@@ -110,4 +110,4 @@ struct CheckboxExample {
}
}
```
![checkboxGroup](figures/checkboxGroup.gif)
![checkboxgroup](figures/checkboxgroup.gif)
......@@ -41,28 +41,63 @@ The universal events are not supported.
@Component
struct DividerExample {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
Column() {
// Use horizontal dividers.
Text('Horizontal divider').fontSize(9).fontColor(0xCCCCCC)
Row().width('100%').height(40).backgroundColor(0xF1F3F5)
Divider()
Row().width('100%').height(40).backgroundColor(0xF1F3F5)
List() {
ForEach([1, 2, 3], (item) => {
ListItem() {
Text('list' + item).width('100%').fontSize(14).fontColor('#182431').textAlign(TextAlign.Start)
}.width(244).height(48)
}, item => item.toString())
}.padding({ left: 24, bottom: 8 })
Divider().strokeWidth(8).color('#F1F3F5')
List() {
ForEach([4, 5], (item) => {
ListItem() {
Text('list' + item).width('100%').fontSize(14).fontColor('#182431').textAlign(TextAlign.Start)
}.width(244).height(48)
}, item => item.toString())
}.padding({ left: 24, top: 8 })
// Use vertical dividers.
Text('Vertical divider').fontSize(9).fontColor(0xCCCCCC)
Flex({ alignItems: ItemAlign.Center, wrap: FlexWrap.Wrap }) {
Text('bravery')
Divider().vertical(true).margin(20).height(15)
Text('effort')
Divider().vertical(true).margin(20).height(15)
Text('upward')
}.width(250)
Text('Custom Styles').fontSize(9).fontColor(0xCCCCCC)
Row().width('100%').height(40).backgroundColor(0xF1F3F5)
Divider().vertical(false).strokeWidth(5).color(0x2788D9).lineCap(LineCapStyle.Round)
Row().width('100%').height(40).backgroundColor(0xF1F3F5)
}.width('100%').height(350).padding({ left: 35, right: 35, top: 35 })
Column() {
Column() {
Row().width(288).height(64).backgroundColor('#30C9F0').opacity(0.3)
Row() {
Button('Button')
.width(136)
.height(22)
.fontSize(16)
.fontColor('#007DFF')
.fontWeight(500)
.backgroundColor(Color.Transparent)
Divider().vertical(true).height(22).color('#182431').opacity(0.6).margin({ left: 8, right: 8 })
Button('Button')
.width(136)
.height(22)
.fontSize(16)
.fontColor('#007DFF')
.fontWeight(500)
.backgroundColor(Color.Transparent)
}.margin({ top: 17 })
}
.width(336)
.height(152)
.backgroundColor('#FFFFFF')
.borderRadius(24)
.padding(24)
}
.width('100%')
.height(168)
.backgroundColor('#F1F3F5')
.justifyContent(FlexAlign.Center)
.margin({ top: 8 })
}.width('100%').padding({ top: 24 })
}
}
```
![en-us_image_0000001257058407](figures/en-us_image_0000001257058407.png)
![en-us_image_0000001174422926](figures/en-us_image_0000001174422926.png)
......@@ -12,9 +12,9 @@ Not supported
## APIs
Select(options: Array\<SelectOption\>)
Select(options: Array\<[SelectOption](#selectoption)\>)
**SelectOption**
## SelectOption
| Name| Type | Mandatory| Description |
| ------ | ----------------------------------- | ---- | -------------- |
......@@ -27,20 +27,20 @@ Select(options: Array\<SelectOption\>)
| ----------------------- | ------------------------------------- | --------------------------------------------- |
| selected | number | Index of the initial selected option in the drop-down list box. The index of the first option is **0**.|
| value | string | Text of the drop-down button. |
| font | [Font](ts-types.md#font) | Text font of the drop-down button. |
| font | [Font](ts-types.md#font) | Text font of the drop-down button. |
| fontColor | [ResourceColor](ts-types.md#resourcecolor) | Text color of the drop-down button. |
| selectedOptionBgColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected option in the drop-down list box. |
| selectedOptionFont | [Font](ts-types.md#font) | Text font of the selected option in the drop-down list box. |
| selectedOptionFont | [Font](ts-types.md#font) | Text font of the selected option in the drop-down list box. |
| selectedOptionFontColor | [ResourceColor](ts-types.md#resourcecolor) | Text color of the selected option in the drop-down list box. |
| optionBgColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of an option in the drop-down list box. |
| optionFont | [Font](ts-types.md#font) | Text font of an option in the drop-down list box. |
| optionFont | [Font](ts-types.md#font) | Text font of an option in the drop-down list box. |
| optionFontColor | [ResourceColor](ts-types.md#resourcecolor) | Text color of an option in the drop-down list box. |
## Events
| Name | Description |
| ---------------------------------------------------------- | ------------------------------------------------------------ |
| onSelect(callback: (index: number, value?:string) => void) | Invoked when an option in the drop-down list box is selected.<br>**index**: index of the selected option.<br/>**value**: value of the selected option. |
| Name | Description |
| ----------------------------------------------------------- | ------------------------------------------------------------ |
| onSelect(callback: (index: number, value?: string) => void) | Invoked when an option in the drop-down list box is selected.<br>**index**: index of the selected option.<br>**value**: value of the selected option. |
## Example
......@@ -51,19 +51,20 @@ Select(options: Array\<SelectOption\>)
struct SelectExample {
build() {
Column() {
Select([{ value: 'aaa', icon: "/common/1.png" },
{ value: 'bbb', icon: "/common/2.png" },
{ value: 'ccc', icon: "/common/3.png" },
{ value: 'ddd', icon: "/common/4.png" }])
Select([{ value: 'aaa', icon: "/common/public_icon.svg" },
{ value: 'bbb', icon: "/common/public_icon.svg" },
{ value: 'ccc', icon: "/common/public_icon.svg" },
{ value: 'ddd', icon: "/common/public_icon.svg" }])
.selected(2)
.value('TTT')
.font({ size: 30, weight: 400, family: 'serif', style: FontStyle.Normal })
.selectedOptionFont({ size: 40, weight: 500, family: 'serif', style: FontStyle.Normal })
.optionFont({ size: 30, weight: 400, family: 'serif', style: FontStyle.Normal })
.value('TTTTT')
.font({ size: 16, weight: 500 })
.fontColor('#182431')
.selectedOptionFont({ size: 16, weight: 400 })
.optionFont({ size: 16, weight: 400 })
.onSelect((index: number) => {
console.info("Select:" + index)
console.info('Select:' + index)
})
}
}.width('100%')
}
}
```
......
# TextClock
The **<TextClock\>** component displays the current system time in text format for different time zones. The time is accurate to seconds.
The **\<TextClock>** component displays the current system time in text format for different time zones. The time is accurate to seconds.
>**NOTE**
>
......@@ -19,7 +19,7 @@ TextClock(options?: { timeZoneOffset?: number, controller?: TextClockController
| Name | Type | Mandatory | Description |
| -------------- | -------- | ------ | --------------------------------------------------------------------------- |
| timeZoneOffset | number | No | Time zone offset.<br>The value range is [-14, 12], indicating UTC+12 to UTC-12. A negative value indicates Eastern Standard Time, and a positive value indicates Western Standard Time. For example, **-8** indicates UTC+8.<br>For countries or regions crossing the International Date Line, use -13 (UTC+13) and -14 (UTC+14) to ensure consistent time within the entire country or region. If the set value is not within the valid range, the time zone offset of the current system will be used.<br>Default value: time zone offset of the current system|
| controller | [TextClockController](#textclockcontroller) | No | Controller to control the status of the **<TextClock\>** component. |
| controller | [TextClockController](#textclockcontroller) | No | Controller to control the status of the **<TextClock\>** component.|
## Attributes
......@@ -27,7 +27,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Description |
| ------ | --------------- | ------------------------------------------------------------ |
| format | string | Time format.<br>The date separator is a slash (/), and the time separator is a colon (:).<br>For example, yyyyMMdd and yyyy-MM-dd are displayed as yyyy/MM/dd,<br>and hhmmss is displayed as hh:mm:ss.<br>Only one digit is required for the time format. This means that hhmmss is equivalent to hms.<br>Supported time format strings:<br>- YYYY/yyyy: four-digit year<br>- YY/yy: last two digits of year<br>- M: one-digit month (MM for two-digit month, for example, 01)<br>- d: one-digit day (dd for two-digit day, for example, 01)<br>- D: number of days that have elapsed in the year<br>- H: 24-hour format<br>- h: 12-hour format<br>- m: minute<br>- s: second<br>- SSS: millisecond<br>Default value: **'hms'**|
| format | string | Time format.<br>The date separator is a slash (/), and the time separator is a colon (:).<br>For example, yyyyMMdd and yyyy-MM-dd are displayed as yyyy/MM/dd,<br>and hhmmss is displayed as hh:mm:ss.<br>Only one digit is required for the time format. This means that **"hhmmss"** is equivalent to **"hms"**.<br>Supported time format strings:<br>- YYYY/yyyy: four-digit year<br>- YY/yy: last two digits of year<br>- M: one-digit month (MM for two-digit month, for example, 01)<br>- d: one-digit day (dd for two-digit day, for example, 01)<br>- D: number of days that have elapsed in the year<br>- H: 24-hour format<br>- h: 12-hour format<br>- m: minute<br>- s: second<br>- SSS: millisecond<br>If the specified format does not match the supported formats, the default value is used.<br>Default value: **'hms'**|
## Events
......@@ -35,16 +35,16 @@ In addition to the [universal events](ts-universal-events-click.md), the followi
| Name | Description |
| -------------------------------------------- | ------------------------------------------------------------ |
| onDateChange(event: (value: number) => void) | Called when the time changes in seconds at minimum.<br> - **value**: Unix time stamp, which is the number of milliseconds that have elapsed since the Unix epoch.|
| onDateChange(event: (value: number) => void) | Called when the time changes in seconds at minimum.<br>- **value**: Unix time stamp, which is the number of milliseconds that have elapsed since the Unix epoch.|
## TextClockController
Defines the controller of the **<TextClock\>** component, which can be bound to the component for status control. A **\<TextClock>** component can be bound to only one controller.
Implements the controller of the **\<TextClock>** component. You can bind the controller to the component to control its start and stop. A **\<TextClock>** component can be bound to only one controller.
### Objects to Import
```ts
controller: TextClockController = new TextClockController()
controller: TextClockController = new TextClockController();
```
### start
......@@ -59,7 +59,6 @@ stop()
Stops the **<TextClock\>** component.
## Example
```ts
......@@ -67,8 +66,8 @@ Stops the **<TextClock\>** component.
@Component
struct Second {
@State accumulateTime: number = 0
// Objects to import
controller: TextClockController = new TextClockController()
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('Current milliseconds is ' + this.accumulateTime)
......@@ -84,10 +83,12 @@ struct Second {
Button("start TextClock")
.margin({ bottom: 10 })
.onClick(() => {
// Start the text clock.
this.controller.start()
})
Button("stop TextClock")
.onClick(() => {
// Stop the text clock.
this.controller.stop()
})
}
......@@ -96,4 +97,4 @@ struct Second {
}
}
```
![](figures/text_clock.png)
![text_clock](figures/text_clock.gif)
......@@ -4,43 +4,39 @@ The **\<TextTimer>** component displays timing information and is controlled in
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Not supported
## APIs
TextTimer(options?: { isCountDown?: boolean, count?: number, controller?: TextTimerController })
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| isCountDown | boolean | No| Whether to count down.<br/>Default value: **false** |
| count | number | No| Countdown time, in milliseconds. This parameter is valid only when **isCountDown** is set to **true**.<br>If the value of **count** is less than or equal to 0, the default value is used.<br>If the value of **count** is greater than 0, it is used.<br/>Default value: **60000** |
| controller | [TextTimerController](#texttimercontroller) | No| **\<TextTimer>** controller.|
| Name | Type | Mandatory | Description |
| ----------- | -------- | -------- | -------- |
| isCountDown | boolean | No | Whether to count down.<br>Default value: **false**|
| count | number | No | Countdown time, in milliseconds. This parameter is valid only when **isCountDown** is set to **true**. The maximum value is 86400000 ms (24 hours). In the case of 0 < Value of **count** < 86400000, the value of **count** is used as the initial countdown value. In other cases, the default value is used as the initial countdown value.<br>Default value: **60000**|
| controller | [TextTimerController](#texttimercontroller) | No | **\<TextTimer>** controller.|
## Attributes
| Name| Type| Description|
| -------- | -------- | -------- |
| format | string | Custom format. The value must contain at least one of the following keywords: **hh**, **mm**, **ss**, and **ms**.<br>Default value: **'hh:mm:ss.ms'** |
| Name | Type | Description |
| -------- | ---------------------- | ---------------------- |
| format | string | Custom format. The value must contain at least one of the following keywords: **HH**, **mm**, **ss**, and **SS**. If the specified date format is yy, MM, or dd, the default value is used instead.<br>Default value: **'HH:mm:ss.SS'**|
## Events
| Name| Description|
| -------- | -------- |
| onTimer(event: (utc: number, elapsedTime: number) =&gt; void) | Triggered when the time text changes.<br>**utc**: currently displayed time, in milliseconds.<br>**elapsedTime**: elapsed time of the timer, in milliseconds.|
| Name | Description |
| ---------------------------------------- | ---------------------------------------- |
| onTimer(event: (utc: number, elapsedTime: number) =&gt; void) | Triggered when the time text changes.<br>**utc**: Unix time stamp, which is the number of milliseconds that have elapsed since the Unix epoch.<br>**elapsedTime**: elapsed time of the timer, in milliseconds.|
## TextTimerController
Defines the controller for controlling the **\<TextTimer>** component. A **\<TextTimer>** component can be bound to only one controller.
Implements the controller for controlling the **\<TextTimer>** component. A **\<TextTimer>** component can be bound to only one controller.
### Objects to Import
......@@ -67,7 +63,6 @@ reset()
Resets the timer.
## Example
```ts
......@@ -76,11 +71,11 @@ Resets the timer.
@Component
struct TextTimerExample {
textTimerController: TextTimerController = new TextTimerController()
@State format: string = 'hh:mm:ss.ms'
@State format: string = 'mm:ss.SS'
build() {
Column() {
TextTimer({controller: this.textTimerController})
TextTimer({ controller: this.textTimerController, isCountDown: true, count: 30000 })
.format(this.format)
.fontColor(Color.Black)
.fontSize(50)
......@@ -89,14 +84,14 @@ struct TextTimerExample {
})
Row() {
Button("start").onClick(() => {
this.textTimerController.start();
});
this.textTimerController.start()
})
Button("pause").onClick(() => {
this.textTimerController.pause();
});
this.textTimerController.pause()
})
Button("reset").onClick(() => {
this.textTimerController.reset();
});
this.textTimerController.reset()
})
}
}
}
......
......@@ -50,14 +50,7 @@ SideBarContainer( type?: SideBarContainerType )
| top | number | No| Spacing between the sidebar control button and the top of the container.<br>Default value: **48**, in vp|
| width | number | No| Width of the sidebar control button.<br>Default value: **32**, in vp|
| height | number | No| Height of the sidebar control button.<br>Default value: **32**, in vp|
| icons | {<br>shown: string \| PixelMap \| [Resource](ts-types.md#resource) ,<br>hidden: string \| PixelMap \| [Resource](ts-types.md#resource) ,<br>switching?: string \| PixelMap \| [Resource](ts-types.md#resource) <br>} | No| Icons of the sidebar control button.<br> </p> - **shown**: icon of the control button when the sidebar is shown.<br>- **hidden**: icon of the control button when the sidebar is hidden.<br>- **switching**: icon of the control button when the sidebar is switching between the shown and hidden states.|
## SideBarPosition<sup>9+</sup>
| Name| Description|
| -------- | -------- |
| Start | The sidebar is on the left side of the container.|
| End | The sidebar is on the right side of the container.|
| icons | {<br>shown: string \| PixelMap \| [Resource](ts-types.md) ,<br>hidden: string \| PixelMap \| [Resource](ts-types.md) ,<br>switching?: string \| PixelMap \| [Resource](ts-types.md) <br>} | No| Icons of the sidebar control button.<br> </p> - **shown**: icon of the control button when the sidebar is shown.<br>- **hidden**: icon of the control button when the sidebar is hidden.<br>- **switching**: icon of the control button when the sidebar is switching between the shown and hidden states.|
## SideBarPosition<sup>9+</sup>
......
......@@ -40,9 +40,9 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| displayMode | SwiperDisplayMode | Mode in which elements are displayed along the main axis. This attribute takes effect only when **displayCount** is not set.<br>Default value: **SwiperDisplayMode.Stretch**|
| cachedCount<sup>8+</sup> | number | Number of child components to be cached.<br>Default value: **1** |
| disableSwipe<sup>8+</sup> | boolean | Whether to disable the swipe feature.<br>Default value: **false** |
| curve<sup>8+</sup> | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves (interpolation curve objects) by using the API provided by the interpolation calculation module.<br>Default value: **Curve.Ease**|
| indicatorStyle<sup>8+</sup> | {<br>left?: [Length](ts-types.md#length),<br>top?: [Length](ts-types.md#length),<br>right?: [Length](ts-types.md#length),<br>bottom?: [Length](ts-types.md#length),<br>size?: [Length](ts-types.md#length),<br>mask?: boolean,<br>color?: [ResourceColor](ts-types.md#resourcecolor),<br>selectedColor?: [ResourceColor](ts-types.md#resourcecolor)<br>} | Style of the navigation dots indicator.<br>\- **left**: distance between the navigation dots indicator and the left edge of the **\<Swiper>** component.<br>\- **top**: distance between the navigation dots indicator and the top edge of the **\<Swiper>** component.<br>\- **right**: distance between the navigation dots indicator and the right edge of the **\<Swiper>** component.<br>\- **bottom**: distance between the navigation dots indicator and the bottom edge of the **\<Swiper>** component.<br>\- **size**: diameter of the navigation dots indicator.<br>\- **mask**: whether to enable the mask for the navigation dots indicator.<br>\- **color**: color of the navigation dots indicator.<br>\- **selectedColor**: color of the selected navigation dot.|
| displayCount<sup>8+</sup> | number\|string | Number of elements to display.<br>Default value: **1** |
| curve<sup>8+</sup> | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves (interpolation curve objects) by using the API provided by the [interpolation calculation](../apis/js-apis-curve.md) module.<br>Default value: **Curve.Ease**|
| indicatorStyle<sup>8+</sup> | {<br>left?: [Length](ts-types.md#length),<br>top?: [Length](ts-types.md#length),<br>right?: [Length](ts-types.md#length),<br>bottom?: [Length](ts-types.md#length),<br>size?: [Length](ts-types.md#length),<br>mask?: boolean,<br>color?: [ResourceColor](ts-types.md),<br>selectedColor?: [ResourceColor](ts-types.md)<br>} | Style of the navigation dots indicator.<br>\- **left**: distance between the navigation dots indicator and the left edge of the **\<Swiper>** component.<br>\- **top**: distance between the navigation dots indicator and the top edge of the **\<Swiper>** component.<br>\- **right**: distance between the navigation dots indicator and the right edge of the **\<Swiper>** component.<br>\- **bottom**: distance between the navigation dots indicator and the bottom edge of the **\<Swiper>** component.<br>\- **size**: diameter of the navigation dots indicator.<br>\- **mask**: whether to enable the mask for the navigation dots indicator.<br>\- **color**: color of the navigation dots indicator.<br>\- **selectedColor**: color of the selected navigation dot.|
| displayCount<sup>8+</sup> | number\|string | Number of elements to display per page.<br>Default value: **1** |
| effectMode<sup>8+</sup> | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Swipe effect. For details, see **EdgeEffect**.<br>Default value: **EdgeEffect.Spring**|
## SwiperDisplayMode
......@@ -52,17 +52,9 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Stretch | The slide width of the **\<Swiper>** component is equal to the width of the component.|
| AutoLinear | The slide width of the **\<Swiper>** component is equal to that of the child component with the maximum width.|
## EdgeEffect
| Name | Description |
| ------ | ------------------------------------------------------------------------- |
| Spring | Spring effect. When sliding to one edge, the component can move beyond the bounds through touches, and produce a bounce effect when the user releases their finger. |
| Fade | Fade effect. When sliding to one edge, the component can move beyond the bounds through touches, and produce a fade effect along the way; when the user releases their finger, the fade changes. |
| None | No effect. When sliding to one edge, the component cannot move beyond the bounds. |
## SwiperController
Controller of the **\<Swiper>** component. You can bind this object to the **\<Swiper>** component and use it to control page switching.
Controller of the **\<Swiper>** component. You can bind this object to the **<Swiper>** component and use it to control page switching.
### showNext
......@@ -86,7 +78,7 @@ Stops an animation.
| Name | Type | Mandatory.| Description|
| --------- | ---------- | ------ | -------- |
| callback | () => void | Yes | Callback invoked when the animation stops.|
| callback | () => void | No | Callback invoked when the animation stops.|
## Events
......@@ -96,11 +88,11 @@ onChange(event: (index: number) => void)
Triggered when the index of the currently displayed child component changes.
**Parameters**
**Return value**
| Name | Type | Mandatory.| Description|
| --------- | ---------- | ------ | -------- |
| index | number | Yes | Index of the currently displayed element.|
| Name | Type | Description|
| --------- | ---------- | -------- |
| index | number | Index of the currently displayed element.|
## Example
......@@ -149,36 +141,36 @@ struct SwiperExample {
Column({ space: 5 }) {
Swiper(this.swiperController) {
LazyForEach(this.data, (item: string) => {
Text(item).width('90%').height(160).backgroundColor(0xAFEEEE).textAlign(TextAlign.Center).fontSize(20)
Text(item).width('90%').height(160).backgroundColor(0xAFEEEE).textAlign(TextAlign.Center).fontSize(30)
}, item => item)
}
.cachedCount(2)
.index(1)
.autoPlay(true)
.interval(4000)
.indicator(true) // Navigation dots are enabled by default.
.loop(false) // Loop playback is enabled by default.
.indicator(true)
.loop(true)
.duration(1000)
.vertical(false) // Horizontal swiping is enabled by default.
.itemSpace(0)
.curve(Curve.Linear) // Animation curve.
.curve(Curve.Linear)
.onChange((index: number) => {
console.info(index.toString())
})
Flex({ justifyContent: FlexAlign.SpaceAround }) {
Button('next')
Row({ space: 12 }) {
Button('showNext')
.onClick(() => {
this.swiperController.showNext()
})
Button('preview')
Button('showPrevious')
.onClick(() => {
this.swiperController.showPrevious()
})
}
}.margin({ top: 5 })
}.margin(5)
}.width('100%')
.margin({ top: 5 })
}
}
```
![en-us_image_0000001211898474](figures/en-us_image_0000001211898474.gif)
![swiper](figures/swiper.gif)
......@@ -7,10 +7,6 @@ An action sheet is a dialog box that displays actions a user can take.
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## ActionSheet.show
......@@ -22,21 +18,21 @@ Defines and shows the action sheet.
| Name | Type | Mandatory | Description |
| ---------- | -------------------------- | ------- | ----------------------------- |
| title | string \| [Resource](ts-types.md#resource) | Yes | Title of the dialog box.|
| message | string \| [Resource](ts-types.md#resource) | Yes | Content of the dialog box. |
| title | [Resource](ts-types.md#resource) \| string | Yes | Title of the dialog box.|
| message | [Resource](ts-types.md#resource) \| string | Yes | Content of the dialog box. |
| autoCancel | boolean | No | Whether to close the dialog box when the overlay is clicked.<br>Default value: **true**|
| confirm | {<br>value: string \| [Resource](ts-types.md#resource),<br>action: () =&gt; void<br>} | No | Text content of the confirm button and callback upon button clicking.<br>Default value:<br>**value**: button text.<br>**action**: callback upon button clicking.|
| confirm | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>action: () =&gt; void<br>} | No | Text content of the confirm button and callback upon button clicking.<br>Default value:<br>**value**: button text.<br>**action**: callback upon button clicking.|
| cancel | () =&gt; void | No | Callback invoked when the dialog box is closed after the overlay is clicked. |
| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.<br>Default value: **DialogAlignment.Default**|
| offset | {<br>dx: Length,<br>dy: Length<br>} | No | Offset of the dialog box relative to the alignment position.<br/>Default value: **{<br>dx: 0,<br>dy: 0<br>}** |
| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.<br>Default value: **DialogAlignment.Bottom**|
| offset | {<br>dx: Length,<br>dy: Length<br>} | No | Offset of the dialog box relative to the alignment position.<br>Default value: {<br>dx: 0,<br>dy: 0<br>} |
| sheets | Array&lt;SheetInfo&gt; | Yes | Options in the dialog box. Each option supports the image, text, and callback.|
## SheetInfo
| Name| Type | Mandatory| Description |
| ------ | ------------------------------------------------------------ | ---- | ----------------- |
| title | string \| [Resource](ts-types.md#resource) | Yes | Sheet text. |
| icon | string \| [Resource](ts-types.md#resource) | No | Sheet icon. By default, no icon is displayed. |
| title | [ResourceStr](ts-types.md#resourcestr) | Yes | Sheet text. |
| icon | [ResourceStr](ts-types.md#resourcestr) | No | Sheet icon. By default, no icon is displayed. |
| action | ()=&gt;void | Yes | Callback when the sheet is selected.|
......@@ -44,11 +40,9 @@ Defines and shows the action sheet.
```ts
// xxx.ets
@Entry
@Component
struct ActionSheetExample {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button('Click to Show ActionSheet')
......@@ -56,29 +50,35 @@ struct ActionSheetExample {
ActionSheet.show({
title: 'ActionSheet title',
message: 'message',
autoCancel: true,
confirm: {
value: 'Confirm button',
action: () => {
console.log('Get Alert Dialog handled')
}
},
cancel: () => {
console.log('actionSheet canceled')
},
alignment: DialogAlignment.Bottom,
offset: { dx: 0, dy: -10 },
sheets: [
{
title: 'apples',
action: () => {
console.error('apples')
console.log('apples')
}
},
{
title: 'bananas',
action: () => {
console.error('bananas')
console.log('bananas')
}
},
{
title: 'pears',
action: () => {
console.error('pears')
console.log('pears')
}
}
]
......@@ -90,4 +90,4 @@ struct ActionSheetExample {
}
```
![en-us_image_0000001212058508](figures/en-us_image_0000001212058508.gif)
![en-us_image_0000001241668363](figures/en-us_image_0000001241668363.gif)
......@@ -11,7 +11,7 @@ You can set the text content and response callback for an alert dialog box.
| Name | Type | Description|
| ---- | --------------- | -------- |
| show | AlertDialogParamWithConfirm \| AlertDialogParamWithButtons | Shows the **\<AlertDialog>** component. |
| show | [AlertDialogParamWithConfirm](#alertdialogparamwithconfirm) \| [AlertDialogParamWithButtons](#alertdialogparamwithbuttons) | Defines and displays the **<AlertDialog>** component.|
## AlertDialogParamWithConfirm
| Name | Type | Mandatory | Description |
......@@ -19,11 +19,11 @@ You can set the text content and response callback for an alert dialog box.
| title | [ResourceStr](ts-types.md#resourcestr) | No | Title of the dialog box.|
| message | [ResourceStr](ts-types.md#resourcestr) | Yes | Content of the dialog box.|
| autoCancel | boolean | No | Whether to close the dialog box when the overlay is clicked.<br>Default value: **true**|
| confirm | {<br>value: string \| [Resource](ts-types.md#resource),<br>fontColor?: Color \| number \| string \| [Resource](ts-types.md#resource),<br>backgroundColor?: Color \| number \| string \| [Resource](ts-types.md#resource),<br>action: () =&gt; void<br>} | No | Text content, text color, background color, and click callback of the confirm button.|
| confirm | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>fontColor?: [ResourceColor](ts-types.md#resourcecolor),<br>backgroundColor?: [ResourceColor](ts-types.md#resourcecolor),<br>action: () =&gt; void<br>} | No | Text content, text color, background color, and click callback of the confirm button.|
| cancel | () =&gt; void | No | Callback invoked when the dialog box is closed after the overlay is clicked.|
| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.<br>Default value: **DialogAlignment.Default**|
| alignment | [DialogAlignment](#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.<br>Default value: **DialogAlignment.Default**|
| offset | [Offset](ts-types.md#offset) | No | Offset of the dialog box relative to the alignment position.|
| gridCount | number | No | Number of grid columns occupied by the width of the dialog box. |
| gridCount | number | No | Number of grid columns occupied by the width of the dialog box.|
## AlertDialogParamWithButtons
| Name | Type | Mandatory | Description |
......@@ -31,12 +31,27 @@ You can set the text content and response callback for an alert dialog box.
| title | [ResourceStr](ts-types.md#resourcestr) | No | Title of the dialog box. |
| message | [ResourceStr](ts-types.md#resourcestr) | Yes | Content of the dialog box. |
| autoCancel | boolean | No | Whether to close the dialog box when the overlay is clicked.<br>Default value: **true** |
| primaryButton | {<br>value: string \| [Resource](ts-types.md#resource),<br>fontColor?: Color \| number \| string \| [Resource](ts-types.md#resource),<br>backgroundColor?: Color \| number \| string \| [Resource](ts-types.md#resource),<br>action: () =&gt; void;<br>} | No| Text content, text color, background color, and click callback of the primary button.|
| secondaryButton | {<br>value: string \| [Resource](ts-types.md#resource),<br>fontColor?: Color \| number \| string \| [Resource](ts-types.md#resource),<br>backgroundColor?: Color \| number \| string \| [Resource](ts-types.md#resource),<br>action: () =&gt; void;<br>} | No | Text content, text color, background color, and click callback of the primary button.|
| primaryButton | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>fontColor?: [ResourceColor](ts-types.md#resourcecolor),<br>backgroundColor?: [ResourceColor](ts-types.md#resourcecolor),<br>action: () =&gt; void;<br>} | No| Text content, text color, background color, and click callback of the primary button.|
| secondaryButton | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>fontColor?: [ResourceColor](ts-types.md#resourcecolor),<br>backgroundColor?: [ResourceColor](ts-types.md#resourcecolor),<br>action: () =&gt; void;<br>} | No | Text content, text color, background color, and click callback of the primary button.|
| cancel | () =&gt; void | No | Callback invoked when the dialog box is closed after the overlay is clicked. |
| alignment | [DialogAlignment](ts-methods-custom-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.<br>Default value: **DialogAlignment.Default**|
| alignment | [DialogAlignment](#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.<br>Default value: **DialogAlignment.Default**|
| offset | [Offset](ts-types.md#offset) | No | Offset of the dialog box relative to the alignment position.|
| gridCount | number | No | Number of grid columns occupied by the width of the dialog box. |
| gridCount | number | No | Number of grid columns occupied by the width of the dialog box.|
## DialogAlignment
| Name | Description |
| ------------------------ | ------- |
| Top | Vertical top alignment.|
| Center | Vertical center alignment.|
| Bottom | Vertical bottom alignment.|
| Default | Default alignment. |
| TopStart<sup>8+</sup> | Top left alignment. |
| TopEnd<sup>8+</sup> | Top right alignment. |
| CenterStart<sup>8+</sup> | Center left alignment. |
| CenterEnd<sup>8+</sup> | Center right alignment. |
| BottomStart<sup>8+</sup> | Bottom left alignment. |
| BottomEnd<sup>8+</sup> | Bottom right alignment. |
## Example
......@@ -45,7 +60,6 @@ You can set the text content and response callback for an alert dialog box.
@Entry
@Component
struct AlertDialogExample {
build() {
Column({ space: 5 }) {
Button('one button dialog')
......@@ -54,6 +68,10 @@ struct AlertDialogExample {
{
title: 'title',
message: 'text',
autoCancel: true,
alignment: DialogAlignment.Bottom,
offset: { dx: 0, dy: -20 },
gridCount: 3,
confirm: {
value: 'button',
action: () => {
......@@ -65,7 +83,7 @@ struct AlertDialogExample {
}
}
)
})
})
.backgroundColor(0x317aff)
Button('two button dialog')
.onClick(() => {
......@@ -73,6 +91,10 @@ struct AlertDialogExample {
{
title: 'title',
message: 'text',
autoCancel: true,
alignment: DialogAlignment.Bottom,
gridCount: 4,
offset: { dx: 0, dy: -20 },
primaryButton: {
value: 'cancel',
action: () => {
......@@ -90,10 +112,10 @@ struct AlertDialogExample {
}
}
)
}).backgroundColor(0x317aff)
}).backgroundColor(0x317aff)
}.width('100%').margin({ top: 5 })
}
}
```
![en-us_image_0000001256978387](figures/en-us_image_0000001256978387.gif)
![en-us_image_0000001174582844](figures/en-us_image_0000001174582844.gif)
......@@ -4,7 +4,8 @@ A date picker dialog box is a dialog box that allows users to select a date from
> **NOTE**
>
> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## DatePickerDialog.show
......@@ -12,84 +13,71 @@ show(options?: DatePickerDialogOptions)
Shows a date picker dialog box.
- DatePickerDialogOptions
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| start | Date | No| Date('1970-1-1') | Start date of the picker.|
| end | Date | No| Date('2100-12-31') | End date of the picker.|
| selected | Date | No| Current system date| Date of the selected item.|
| lunar | boolean | No| false | Whether to display the lunar calendar.|
| onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| - | Callback invoked when the OK button in the dialog box is clicked.|
| onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked.|
| onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| - | Callback invoked when the selected item in the picker changes.|
**DatePickerDialogOptions**
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| start | Date | No| Date('1970-1-1') | Start date of the picker.|
| end | Date | No| Date('2100-12-31') | End date of the picker.|
| selected | Date | No| Current system date| Selected date.|
| lunar | boolean | No| false | Whether to display the lunar calendar.|
| onAccept | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| - | Callback invoked when the OK button in the dialog box is clicked.|
| onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked.|
| onChange | (value: [DatePickerResult](ts-basic-components-datepicker.md#DatePickerResult)) => void | No| - | Callback invoked when the selected item in the picker changes.|
## Example
### Date Picker Sample Code (With Lunar Calendar)
```ts
// xxx.ets
@Entry
@Component
struct DatePickerDialogExample01 {
@State isLunar: boolean = true
selectedDate: Date = new Date("2000-1-1")
struct DatePickerDialogExample {
selectedDate: Date = new Date("2010-1-1")
build() {
Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center }) {
Button("DatePickerDialog").onClick(() => {
DatePickerDialog.show({
start: new Date("2000-1-1"),
end: new Date("2005-1-1"),
selected: this.selectedDate,
lunar: this.isLunar,
onAccept: (value: DatePickerResult) => {
this.selectedDate.setFullYear(value.year, value.month, value.day)
console.info("DatePickerDialog:onAccept()" + JSON.stringify(value))
},
onCancel: () => {
console.info("DatePickerDialog:onCancel()")
},
onChange: (value: DatePickerResult) => {
console.info("DatePickerDialog:onChange()" + JSON.stringify(value))
}
Column() {
Button("DatePickerDialog")
.margin(20)
.onClick(() => {
DatePickerDialog.show({
start: new Date("2000-1-1"),
end: new Date("2100-12-31"),
selected: this.selectedDate,
onAccept: (value: DatePickerResult) => {
// Use the setFullYear method to set the date when the OK button is touched. In this way, when the date picker dialog box is displayed again, the selected date is the date last confirmed.
this.selectedDate.setFullYear(value.year, value.month, value.day)
console.info("DatePickerDialog:onAccept()" + JSON.stringify(value))
},
onCancel: () => {
console.info("DatePickerDialog:onCancel()")
},
onChange: (value: DatePickerResult) => {
console.info("DatePickerDialog:onChange()" + JSON.stringify(value))
}
})
})
})
}
}
}
```
### Date Picker Sample Code (No Lunar Calendar)
```ts
// xxx.ets
@Entry
@Component
struct DatePickerDialogExample02 {
@State isLunar: boolean = false
selectedDate: Date = new Date("2000-1-1")
build() {
Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center }) {
Button("DatePickerDialog").onClick(() => {
DatePickerDialog.show({
start: new Date("2000-1-1"),
end: new Date("2005-1-1"),
selected: this.selectedDate,
lunar: this.isLunar,
onAccept: (value: DatePickerResult) => {
this.selectedDate.setFullYear(value.year, value.month, value.day)
console.info("DatePickerDialog:onAccept()" + JSON.stringify(value))
},
onCancel: () => {
console.info("DatePickerDialog:onCancel()")
},
onChange: (value: DatePickerResult) => {
console.info("DatePickerDialog:onChange()" + JSON.stringify(value))
}
Button("Lunar DatePickerDialog")
.margin(20)
.onClick(() => {
DatePickerDialog.show({
start: new Date("2000-1-1"),
end: new Date("2100-12-31"),
selected: this.selectedDate,
lunar: true,
onAccept: (value: DatePickerResult) => {
this.selectedDate.setFullYear(value.year, value.month, value.day)
console.info("DatePickerDialog:onAccept()" + JSON.stringify(value))
},
onCancel: () => {
console.info("DatePickerDialog:onCancel()")
},
onChange: (value: DatePickerResult) => {
console.info("DatePickerDialog:onChange()" + JSON.stringify(value))
}
})
})
})
}
}.width('100%')
}
}
```
......@@ -4,7 +4,8 @@ A text picker dialog box is a dialog box that allows users to select text from t
> **NOTE**
>
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## TextPickerDialog.show
......@@ -12,22 +13,24 @@ show(options?: TextPickerDialogOptions)
Shows a text picker in the given settings.
- TextPickerDialogOptions
| Name | Type | Mandatory | Default Value | Description |
| ----------------------- | ---------------------------------------- | --------- | ------------- | ---------------------------------------- |
| range | string[] \| [Resource](ts-types.md#resource) | Yes | - | Data selection range of the picker. |
| selected | number | No | 0 | Index of the selected item in the range. |
| value | string | No | - | Value of the selected item. This parameter does not take effect when the **selected** parameter is set. If the value is not within the range, the first item in the range is used instead. |
| defaultPickerItemHeight | number \| string | No | - | Default height of an item in the picker. |
| onAccept | (value: TextPickerResult) => void | No | - | Callback invoked when the OK button in the dialog box is clicked. |
| onCancel | () => void | No | - | Callback invoked when the Cancel button in the dialog box is clicked. |
| onChange | (value: TextPickerResult) => void | No | - | Callback invoked when the selected item in the picker changes. |
**TextPickerDialogOptions**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| range | string[] \| [Resource](ts-types.md#resource) | Yes| Data selection range of the picker.|
| selected | number | No| Index of the selected item.<br>Default value: **0**|
| value | string | No | Text of the selected item. This parameter does not take effect when the **selected** parameter is set. If the value is not within the range, the first item in the range is used instead.|
| defaultPickerItemHeight | number \| string | No| Height of the picker item.|
| onAccept | (value: [TextPickerResult](#textpickerresult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.|
| onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.|
| onChange | (value: [TextPickerResult](#textpickerresult)) => void | No| Callback invoked when the selected item changes.|
## TextPickerResult
- TextPickerResult
| Name | Type | Description |
| ----- | ------ | ---------------------------------------- |
| value | string | Value of the selected item. |
| index | number | Index of the selected item in the range. |
| Name| Type| Description|
| -------- | -------- | -------- |
| value | string | Text of the selected item.|
| index | number | Index of the selected item in the range.|
## Example
......@@ -36,29 +39,31 @@ Shows a text picker in the given settings.
@Entry
@Component
struct TextPickerDialogExample {
@State select: number = 1
private fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4']
@State select: number = 2
private fruits: string[] = ['apple1', 'orange2', 'peach3', 'grape4', 'banana5']
build() {
Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center,
justifyContent: FlexAlign.Center }) {
Button("TextPickerDialog").onClick(() => {
TextPickerDialog.show({
range: this.fruits,
selected: this.select,
onAccept: (value: TextPickerResult) => {
console.info("TextPickerDialog:onAccept()" + JSON.stringify(value))
this.select = value.index
},
onCancel: () => {
console.info("TextPickerDialog:onCancel()")
},
onChange: (value: TextPickerResult) => {
console.info("TextPickerDialog:onChange()" + JSON.stringify(value))
}
Column() {
Button("TextPickerDialog")
.margin(20)
.onClick(() => {
TextPickerDialog.show({
range: this.fruits,
selected: this.select,
onAccept: (value: TextPickerResult) => {
// Set select to the index of the item selected when the OK button is touched. In this way, when the text picker dialog box is displayed again, the selected item is the one last confirmed.
this.select = value.index
console.info("TextPickerDialog:onAccept()" + JSON.stringify(value))
},
onCancel: () => {
console.info("TextPickerDialog:onCancel()")
},
onChange: (value: TextPickerResult) => {
console.info("TextPickerDialog:onChange()" + JSON.stringify(value))
}
})
})
})
}
}.width('100%')
}
}
```
# Time Picker Dialog Box
A time picker dialog box is a dialog box that allows users to select a time from the 24-hour range.
A time picker dialog box is a dialog box that allows users to select a time from the 24-hour range through scrolling.
> **NOTE**
>
......@@ -12,15 +12,16 @@ show(options?: TimePickerDialogOptions)
Shows a time picker dialog box.
- TimePickerDialogOptions
**TimePickerDialogOptions**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| selected | Date | No| Selected time.<br>Default value: current system time|
| useMilitaryTime | boolean | No| Whether to display time in 24-hour format. The 12-hour format is used by default.<br>Default value: **false**|
| onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.|
| onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.|
| onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the selected time changes.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| selected | Date | No| Selected time.<br>Default value: current system time|
| useMilitaryTime | boolean | No| Whether to display time in 24-hour format. The 12-hour format is used by default.<br>Default value: **false**|
| onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.|
| onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.|
| onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the selected time changes.|
## Example
......@@ -41,13 +42,13 @@ struct TimePickerDialogExample {
onAccept: (value: TimePickerResult) => {
//Set selectTime to the time when the OK button is clicked. In this way, when the dialog box is displayed again, the selected time is the time when the operation was confirmed last time.
this.selectTime.setHours(value.hour, value.minute)
console.info("TimePickerDialog:onAccept()" + JSON.stringify(value));
console.info("TimePickerDialog:onAccept()" + JSON.stringify(value))
},
onCancel: () => {
console.info("TimePickerDialog:onCancel()");
console.info("TimePickerDialog:onCancel()")
},
onChange: (value: TimePickerResult) => {
console.info("TimePickerDialog:onChange()" + JSON.stringify(value));
console.info("TimePickerDialog:onChange()" + JSON.stringify(value))
}
})
})
......@@ -59,13 +60,13 @@ struct TimePickerDialogExample {
useMilitaryTime: true,
onAccept: (value: TimePickerResult) => {
this.selectTime.setHours(value.hour, value.minute)
console.info("TimePickerDialog:onAccept()" + JSON.stringify(value));
console.info("TimePickerDialog:onAccept()" + JSON.stringify(value))
},
onCancel: () => {
console.info("TimePickerDialog:onCancel()");
console.info("TimePickerDialog:onCancel()")
},
onChange: (value: TimePickerResult) => {
console.info("TimePickerDialog:onChange()" + JSON.stringify(value));
console.info("TimePickerDialog:onChange()" + JSON.stringify(value))
}
})
})
......
# Grid
> **NOTE**
> - The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>
> - The column width and column gap in the grid layout are determined by the nearest parent component **GridContainer**. The component tree that uses grid attributes must contain one **GridContainer** or more.
>
> - The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>
> - The column width and column gap in the grid layout are determined by the nearest parent component **GridContainer**. The component tree that uses grid attributes must contain one **GridContainer** or more.
## Attributes
| Name | Type | Description |
| ----------- | --------------------------| ----------------------------------------------- |
| Name | Type | Description |
| ----------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| useSizeType | {<br>xs?: number \| { span: number, offset: number },<br>sm?: number \| { span: number, offset: number },<br>md?: number \| { span: number, offset: number },<br>lg?: number \| { span: number, offset: number }<br>} | Number of occupied columns and offset columns for a specific device width type. **span** indicates the number of occupied columns, and **offset** indicates the number of offset columns.<br>If the value is of the number type, only the number of columns can be set. If the value is in the format of {"span": 1, "offset": 0}, both the number of occupied columns and the number of offset columns need to be set.<br>- **xs** indicates that the device width type is **SizeType.XS**.<br>- **sm** indicates that the device width type is **SizeType.SM**.<br>- **md** indicates that the device width type is **SizeType.MD**.<br>- **lg** indicates that the device width type is **SizeType.LG**.|
| gridSpan | number | Default number of occupied columns, that is, the number of occupied columns when **span** in **useSizeType** is not set.<br>**NOTE**<br>If the **span** attribute is set, the component width is determined by the grid layout.<br>Default value: **1**|
| gridOffset | number | Default number of offset columns, that is, the number of offset columns in the start direction of the parent component (which is also the nth column that the component is in) when **offset** in **useSizeType** is not set.<br>**NOTE**<br>- After this attribute is set, the horizontal layout of the current component does not follow the original layout of the parent component. Instead, it offsets along the start direction of the parent component.<br>- Offset = (Column width + Gap) \* Number of columns.<br>- After this attribute is set, sibling components will be arranged relatively to this component, as in the relative layout.<br>Default value: **0**|
| gridSpan | number | Default number of occupied columns, that is, the number of occupied columns when **span** in **useSizeType** is not set.<br>**NOTE**<br>If the **span** attribute is set, the component width is determined by the grid layout.<br>Default value: **1**|
| gridOffset | number | Default number of offset columns, that is, the number of offset columns in the start direction of the parent component (which is also the nth column that the component is in) when **offset** in **useSizeType** is not set.<br>**NOTE**<br>- After this attribute is set, the horizontal layout of the current component does not follow the original layout of the parent component. Instead, it offsets along the start direction of the parent component.<br>- Offset = (Column width + Gap) \* Number of columns.<br>- After this attribute is set, sibling components will be arranged relatively to this component, as in the relative layout.<br>Default value: **0**|
## Example
......@@ -23,42 +24,76 @@
@Entry
@Component
struct GridContainerExample1 {
build() {
Column() {
Text('useSizeType').fontSize(15).fontColor(0xCCCCCC).width('90%')
GridContainer() {
Row({}) {
Row() {
Text('Left').fontSize(25)
}
.useSizeType({
xs: { span: 1, offset: 0 }, sm: { span: 1, offset: 0 },
md: { span: 1, offset: 0 }, lg: { span: 2, offset: 0 }
})
.height("100%")
.backgroundColor(0x66bbb2cb)
build(){
GridContainer() {
Row({}) {
Row() {
Text('Left').fontSize(25)
}
.useSizeType({
xs: { span: 1, offset: 0 }, sm: { span: 1, offset: 0 },
md: { span: 1, offset: 0 }, lg: { span: 2, offset: 0 }
})
.height("100%")
.backgroundColor(0x66bbb2cb)
Row() {
Text('Center').fontSize(25)
Row() {
Text('Center').fontSize(25)
}
.useSizeType({
xs: { span: 1, offset: 0 }, sm: { span: 2, offset: 1 },
md: { span: 5, offset: 1 }, lg: { span: 7, offset: 2 }
})
.height("100%")
.backgroundColor(0x66b6c5d1)
Row() {
Text('Right').fontSize(25)
}
.useSizeType({
xs: { span: 1, offset: 0 }, sm: { span: 1, offset: 3 },
md: { span: 2, offset: 6 }, lg: { span: 3, offset: 9 }
})
.height("100%")
.backgroundColor(0x66bbb2cb)
}
.useSizeType({
xs: { span: 1, offset: 0 }, sm: { span: 2, offset: 1 },
md: { span: 5, offset: 1 }, lg: { span: 7, offset: 2 }
})
.height("100%")
.backgroundColor(0x66b6c5d1)
.height(200)
}
.backgroundColor(0xf1f3f5)
.margin({ top: 10 })
// Set the span and offset of the component separately. The resultant effect is equivalent to that achieved by using sm in useSizeType on the device of the sm type.
Text('gridSpan,gridOffset').fontSize(15).fontColor(0xCCCCCC).width('90%')
GridContainer() {
Row() {
Text('Right').fontSize(25)
}
.useSizeType({
xs: { span: 1, offset: 0 }, sm: { span: 1, offset: 3 },
md: { span: 2, offset: 6 }, lg: { span: 3, offset: 9 }
})
.height("100%")
.backgroundColor(0x66bbb2cb)
Row() {
Text('Left').fontSize(25)
}
.gridSpan(1)
.height("100%")
.backgroundColor(0x66bbb2cb)
Row() {
Text('Center').fontSize(25)
}
.gridSpan(2)
.gridOffset(1)
.height("100%")
.backgroundColor(0x66b6c5d1)
Row() {
Text('Right').fontSize(25)
}
.gridSpan(1)
.gridOffset(3)
.height("100%")
.backgroundColor(0x66bbb2cb)
}.height(200)
}
.height(200)
}
.backgroundColor(0xf1f3f5)
.margin({ top: 10 })
}
}
```
......@@ -74,3 +109,7 @@ struct GridContainerExample1 {
**Figure 3** Device width type LG
![en-us_image_0000001212378416](figures/en-us_image_0000001212378416.png)
**Figure 4** Setting gridSpan and gridOffset separately has the same effect as using SizeType for a specific device width type
![gridSpan](figures/gridSpan.png)
......@@ -12,7 +12,7 @@ A menu – a vertical list of items – can be bound to a component and displaye
| Name | Type | Description |
| ---------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| bindMenu | Array<MenuItem&gt; \| [CustomBuilder](ts-types.md#custombuilder8) | Menu bound to the component, which is displayed when you click the component. Textual and custom menu items are supported.|
| bindMenu | Array<[MenuItem](#menuitem)&gt; \| [CustomBuilder](ts-types.md#custombuilder8) | Menu bound to the component, which is displayed when you click the component. Textual and custom menu items are supported.|
| bindContextMenu<sup>8+</sup> | content: [CustomBuilder](ts-types.md#custombuilder8),<br>responseType: [ResponseType](ts-appendix-enums.md#responsetype8) | Context menu bound to the component, which is displayed when you long-press or right-click the component. Only custom menu items are supported.|
## MenuItem
......@@ -25,7 +25,9 @@ A menu – a vertical list of items – can be bound to a component and displaye
## Example
#### Menu with Textual Menu Items
### Example 1
Menu with Textual Menu Items
```ts
// xxx.ets
......@@ -58,58 +60,59 @@ struct MenuExample {
![en_image_0000001174582862](figures/en_image_0000001174582862.gif)
#### Menu with Custom Menu Items
### Example 2
```ts
// xxx.ets
import router from '@system.router';
Menu with Custom Menu Items
```ts
@Entry
@Component
struct MenuExample {
@State listData: number[] = [0, 0, 0]
@Builder MenuBuilder() {
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
Text('text1')
.fontSize(20)
.width(100)
.height(50)
.textAlign(TextAlign.Center)
Divider().height(10)
Text('text2')
.fontSize(20)
.width(100)
.height(50)
.textAlign(TextAlign.Center)
Divider().height(10)
Button('Next')
.fontSize(20)
.width(100)
.height(50)
.onClick(() => {
router.push({ uri: 'pages/details' })
})
ForEach(this.listData, (item, index) => {
Column() {
Row() {
Image($r("app.media.icon")).width(20).height(20).margin({ right: 5 })
Text(`Menu${index + 1}`).fontSize(20)
}
.width('100%')
.height(30)
.justifyContent(FlexAlign.Center)
.align(Alignment.Center)
.onClick(() => {
console.info(`Menu${index + 1} Clicked!`)
})
if (index != this.listData.length - 1) {
Divider().height(10).width('80%').color('#ccc')
}
}.padding(5).height(40)
})
}.width(100)
}
build() {
Column() {
Text('click for menu')
.fontSize(20)
.margin({ top: 20 })
.bindMenu(this.MenuBuilder)
}
.height('100%')
.width('100%')
.margin({ top: 5 })
.bindMenu(this.MenuBuilder)
.backgroundColor('#f0f0f0')
}
}
```
![en_image_0000001186807708](figures/en_image_0000001186807708.gif)
#### Context Menu (Displayed Upon Right-Clicking)
### Example 3
Context Menu (Displayed Upon Right-Clicking)
```ts
// xxx.ets
......
......@@ -2,6 +2,7 @@
You can set the touch target for components that support universal click events, touch events, and gestures.
> **NOTE**
>
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
......@@ -12,22 +13,22 @@ You can set the touch target for components that support universal click events,
| Name | Type | Description |
| -------------- | --------------------------------------------- | ----------------------------------------- |
| responseRegion | Array&lt;Rectangle&gt; \| Rectangle | One or more touch targets, including their location and size.<br>Default value:<br>{<br>x: 0,<br>y: 0,<br>width: '100%',<br>height: '100%'<br>} |
| responseRegion | Array&lt;[Rectangle](#rectangle)&gt; \| [Rectangle](#rectangle) | One or more touch targets, including their location and size.<br>The default touch target is the entire component. Default value:<br>{<br>x: 0,<br>y: 0,<br>width: '100%',<br>height: '100%'<br>} |
### Rectangle
## Rectangle
| Name | Type | Mandatory | Description |
| ------ | ----------------------------- | -----| -------------------------------- |
| x | [Length](ts-types.md#length) | No | X coordinate of the touch point relative to the left edge of the component.<br>Default value: **0vp**|
| y | [Length](ts-types.md#length) | No | Y coordinate of the touch point relative to the left edge of the component.<br>Default value: **0vp**|
| width | [Length](ts-types.md#length) | No | Width of the touch target.<br>Default value: **100%**|
| height | [Length](ts-types.md#length) | No | Height of the touch target.<br>Default value: **100%**|
| x | [Length](ts-types.md#length) | No | X coordinate of the touch point relative to the upper left corner of the component.<br>Default value: **0vp**|
| y | [Length](ts-types.md#length) | No | Y coordinate of the touch point relative to the upper left corner of the component.<br>Default value: **0vp**|
| width | [Length](ts-types.md#length) | No | Width of the touch target.<br>Default value: **'100%'**|
| height | [Length](ts-types.md#length) | No | Height of the touch target.<br>Default value: **'100%'**|
> **NOTE**<br>
>
> **x** and **y** can be set to a positive or negative percentage value. For example, when **x** is set to **'100%'**, the touch target is the offset from the right edge of the component by the component's width. When **x** is set to **'-100%'**, the touch target is the offset from the left edge of the component by the component's width. When **y** is set to **'100%'**, the touch target is the offset from the bottom edge of the component by the component's height. When **y** is set to **'-100%'**, the touch target is the offset from the top edge of the component by the component's height.
>
> **width** and **height** can only be set to positive percentage values. When **width** is set to **'100%'**, the width of the touch target is equal to that of the component; when **height** is set to **'100%'**, the height of the touch target is equal to that of the component.
> **width** and **height** can only be set to positive percentage values. When **width** is set to **'100%'**, the width of the touch target is equal to that of the component. For example, if the width of a component is 100 vp, **'100%'** indicates that the width of the touch target is also 100 vp. when **height** is set to **'100%'**, the height of the touch target is equal to that of the component.
>
> The percentage is measured relative to the component itself.
......@@ -38,19 +39,38 @@ You can set the touch target for components that support universal click events,
// xxx.ets
@Entry
@Component
struct ResponseRegionExample {
struct TouchTargetExample {
@State text: string = ""
build() {
Column() {
Toggle({ type: ToggleType.Checkbox, isOn: true })
.selectedColor(0x39a2db)
.backgroundColor(0xAFEEEE)
.responseRegion({ x: 1.0, y: 1.0, width: 400, height: 400 })
.onChange((isOn: boolean) => {
console.info('Component status:' + isOn)
})
}.width('100%').margin({ top: 5 })
Column({ space: 20 }) {
Text("{x:0,y:0,width:'50%',height:'100%'}")
// The width of the touch target is half of that of the button. The user will get no response if they touch the right of the button.
Button("button1")
.responseRegion({ x: 0, y: 0, width: '50%', height: '100%' })
.onClick(() => {
this.text = 'button1 clicked'
})
// The touch target is located rightward by one button width, with its width half of the button width. The touch event is triggered if the left of the right part of button2 is touched.
Text("{x:'100%',y:0,width:'50%',height:'100%'}")
Button("button2")
.responseRegion({ x: '100%', y: 0, width: '50%', height: '100%' })
.onClick(() => {
this.text = 'button2 clicked'
})
// The touch target is located downward by one button height, with its size equal to the button size. The touch event is triggered if the lower part of button3 is touched.
Text("{x:0,y:'100%',width:'100%',height:'100%'}")
Button("button3")
.responseRegion({ x: 0, y: '100%', width: '100%', height: '100%' })
.onClick(() => {
this.text = 'button3 clicked'
})
Text(this.text).margin({ top: 50 })
}.width('100%').margin({ top: 10 })
}
}
```
![en-us_image_0000001212218468](figures/en-us_image_0000001212218468.gif)
![touchtarget.gif](figures/touchtarget.gif)
# Focus Event
A focus event is triggered when the page focus moves between components. It can be used to change the content of a component.
A focus event is triggered when the page focus moves between components. It can be used to process related logic within the component.
> **NOTE**
>
> - The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
>
> - Currently, only the Tab button and arrow buttons on the external keyboard can be used to trigger the focus event.
>
> - Components that have default interaction logic, such as **\<Button>** and **\<TextInput>**, are focusable by default. Other components, such as **\<Text>** and **\<Image>**, are not focusable by default. Only focusable components can trigger a focus event. To enable a component to be focusable, set its **focusable** attribute to **true**.
## Events
| Name | Bubbling Supported| Description |
| ---------------------------------------- | -------- | --------------- |
| onFocus(event: () =&gt; void) | No | Triggered when the current component obtains focus.|
| onFocus(event: () =&gt; void) | No | Triggered when the current component obtains focus.|
| onBlur(event:() =&gt; void) | No | Triggered when the current component loses focus.|
> **NOTE**
>
> The following components support focus events: **\<Button>**, **\<Text>**, **\<Image>**, **\<List>**, and **\<Grid>**.
## Example
......@@ -27,44 +26,52 @@ A focus event is triggered when the page focus moves between components. It can
@Entry
@Component
struct FocusEventExample {
@State textOne: string = ''
@State textTwo: string = ''
@State textThree: string = ''
@State oneButtonColor: string = '#FF0000'
@State oneButtonColor: string = '#FFC0CB'
@State twoButtonColor: string = '#87CEFA'
@State threeButtonColor: string = '#90EE90'
build() {
Column({ space:20 }){
Button(this.textOne)
Column({ space: 20 }) {
// You can use the up and down arrow keys on an external keyboard to move the focus between the three buttons. When a button gains focus, its color changes. When it loses focus, its color changes back.
Button('First Button')
.backgroundColor(this.oneButtonColor)
.width(260).height(70).fontColor(Color.Black)
.width(260)
.height(70)
.fontColor(Color.Black)
.focusable(true)
.onFocus(() => {
this.textOne = 'First Button onFocus'
this.oneButtonColor = '#AFEEEE'
this.oneButtonColor = '#FF0000'
})
.onBlur(() => {
this.textOne = 'First Button onBlur'
this.oneButtonColor = '#FFC0CB'
})
Button(this.textTwo)
Button('Second Button')
.backgroundColor(this.twoButtonColor)
.width(260).height(70).fontColor(Color.Black)
.width(260)
.height(70)
.fontColor(Color.Black)
.focusable(true)
Button(this.textThree)
.onFocus(() => {
this.twoButtonColor = '#FF0000'
})
.onBlur(() => {
this.twoButtonColor = '#87CEFA'
})
Button('Third Button')
.backgroundColor(this.threeButtonColor)
.width(260).height(70).fontColor(Color.Black)
.width(260)
.height(70)
.fontColor(Color.Black)
.focusable(true)
.onFocus(() => {
this.textThree = 'Third Button onFocus'
this.threeButtonColor = '#AFEEEE'
this.threeButtonColor = '#FF0000'
})
.onBlur(() => {
this.textThree = 'Third Button onBlur'
this.threeButtonColor = '#FFC0CB'
this.threeButtonColor = '#90EE90'
})
}.width('100%').margin({ top:20 })
}.width('100%').margin({ top: 20 })
}
}
```
![focus](figures/focus.png)
......@@ -19,16 +19,16 @@ If an action triggers multiple events, the order of these events is fixed. By de
| Name | Type | Description |
| --------- | ------------------------------- | -------------------- |
| screenX | number | X coordinate of the click point relative to the upper left corner of the application window.|
| screenY | number | Y coordinate of the click point relative to the upper left corner of the application window.|
| x | number | X coordinate of the click point relative to the upper left corner of the component being clicked.|
| y | number | Y coordinate of the click point relative to the upper left corner of the component being clicked.|
| screenX | number | X coordinate of the cursor position relative to the upper left corner of the application window.|
| screenY | number | Y coordinate of the cursor position relative to the upper left corner of the application window.|
| x | number | X coordinate of the cursor position relative to the upper left corner of the component being clicked.|
| y | number | Y coordinate of the mouse position relative to the upper left corner of the component being clicked.|
| button | [MouseButton](ts-appendix-enums.md#mousebutton) | Mouse button. |
| action | [MouseAction](ts-appendix-enums.md#mouseaction) | Event action. |
| action | [MouseAction](ts-appendix-enums.md#mouseaction) | Mouse action. |
| stopPropagation | () => void | Stops the event from bubbling upwards or downwards. |
| timestamp<sup>8+</sup> | number | Timestamp of the event. It is interval between the time when the event is triggered and the time when the system starts, in nanoseconds. |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md) | Display area of the component that triggers the event.|
| source<sup>8+</sup> | [SourceType](ts-gesture-settings.md) | Event input device. |
| timestamp<sup>8+</sup> | number | Timestamp of the event. It is interval between the time when the event is triggered and the time when the system starts, in nanoseconds.|
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8) | Display area of the component that triggers the event.|
| source<sup>8+</sup> | [SourceType](ts-gesture-settings.md#sourcetype)| Event input device.|
## Example
......@@ -37,31 +37,80 @@ If an action triggers multiple events, the order of these events is fixed. By de
@Entry
@Component
struct MouseEventExample {
@State hoverText: string = 'no hover'
@State mouseText: string = 'MouseText'
@State color: Color = Color.Blue
@State hoverText: string = 'no hover';
@State mouseText: string = '';
@State action: string = '';
@State mouseBtn: string = '';
@State color: Color = Color.Blue;
build() {
Column({ space:20 }) {
Column({ space: 20 }) {
Button(this.hoverText)
.width(180).height(80)
.backgroundColor(this.color)
.onHover((isHover: boolean) => {
// Use the onHover event to dynamically change the text content and background color of a button when the mouse pointer is hovered on it.
if (isHover) {
this.hoverText = 'on hover'
this.color = Color.Pink
this.hoverText = 'hover';
this.color = Color.Pink;
} else {
this.hoverText = 'no hover'
this.color = Color.Blue
this.hoverText = 'no hover';
this.color = Color.Blue;
}
})
.backgroundColor(this.color)
Button('onMouse')
.width(180).height(80)
.onMouse((event: MouseEvent) => {
console.log(this.mouseText = 'onMouse:\nButton = ' + event.button +
'\nAction = ' + event.action + '\nlocalXY=(' + event.x + ',' + event.y + ')' +
'\nscreenXY=(' + event.screenX + ',' + event.screenY + ')')
switch (event.button) {
case MouseButton.None:
this.mouseBtn = 'None';
break;
case MouseButton.Left:
this.mouseBtn = 'Left';
break;
case MouseButton.Right:
this.mouseBtn = 'Right';
break;
case MouseButton.Back:
this.mouseBtn = 'Back';
break;
case MouseButton.Forward:
this.mouseBtn = 'Forward';
break;
case MouseButton.Middle:
this.mouseBtn = 'Middle';
break;
}
switch (event.action) {
case MouseAction.Hover:
this.action = 'Hover';
break;
case MouseAction.Press:
this.action = 'Press';
break;
case MouseAction.Move:
this.action = 'Move';
break;
case MouseAction.Release:
this.action = 'Release';
break;
}
this.mouseText = 'onMouse:\nButton = ' + this.mouseBtn +
'\nAction = ' + this.action + '\nXY=(' + event.x + ',' + event.y + ')' +
'\nscreenXY=(' + event.screenX + ',' + event.screenY + ')';
})
Text(this.mouseText)
}.padding({ top: 20 }).width('100%')
}.padding({ top: 30 }).width('100%')
}
}
```
The figure below shows how the button looks like when hovered on.
![mouse](figures/mouse.png)
The figure below shows how the button looks like when clicked.
![mouse1](figures/mouse1.png)
......@@ -12,7 +12,7 @@ Create a **&lt;switch&gt;** component in the .hml file under **pages/index**.
```html
<!-- xxx.hml -->
<div class="container">
<switch></switch>
<switch checked="true"></switch>
</div>
```
......@@ -21,8 +21,6 @@ Create a **&lt;switch&gt;** component in the .hml file under **pages/index**.
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #F1F3F5;
}
```
......@@ -63,15 +61,15 @@ switch {
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
switchChange(e){
if(e.checked){
prompt.showToast({
promptAction.showToast({
message: "open"
});
}else{
prompt.showToast({
promptAction.showToast({
message: "close"
});
}
......
# Building a Food Category List Layout
Use the **\<List>** component and **ForEach** loop to build the food category list layout.
Use the List component and ForEach loop to build the food category list layout.
1. Create a page file named **FoodCategoryList.ets** in the **pages** directory, rename the **index.ets** file **FoodDetail.ets**, and add the renamed file to the "pages" tag in the **config.json** file. The first page under the tag is the home page.
```json
"js": [
{
"pages": [
"pages/FoodCategoryList",
"pages/FoodDetail"
],
]
```
1. Create a page file named **FoodCategoryList.ets** in the **pages** directory and rename the **index.ets** file **FoodDetail.ets**.
2. Create a **\<List>** component named **FoodList** as the page entry point. Then, add a **\<ListItem>** component named **FoodListItem** as its child component. The **\<List>** component is used to display data of the same type. Its child component **\<ListItem>** is used to display specific items in the list.
```
```ts
@Component
struct FoodListItem {
build() {}
}
@Entry
@Component
struct FoodList {
......@@ -38,24 +26,28 @@ Use the List component and ForEach loop to build the food category list layout.
```
3. Import the **FoodData** class and **initializeOnStartup** method.
There are two file access methods in application code:
- Use a relative path to reference the code file: Use **"../"** for referencing the upper-level directory and **"./"** (which can also be omitted) for referencing the current directory.
- Use the absolute path, which is the root path of the current module, to reference the code file, for example, **common/utils/utils**.
In this example, a relative path is used for access.
```
import { FoodData } from '../model/FoodData'
import { initializeOnStartup } from '../model/FoodDataModels'
```
4. Configure the **FoodList** and **FoodListItem** components to pass values. Create a member variable named **foodItems** of the FoodData[] type in the **FoodList** component and invoke the **initializeOnStartup** method to assign a value to the variable. Create a member variable foodItem of the FoodData type in the FoodListItem component. Pass the **foodItems[0]** of the first element in the parent **foodItems** array as a parameter to **FoodListItem**.
```
4. Configure the **FoodList** and **FoodListItem** components to pass values. Create a member variable named **foodItems** of the **FoodData[]** type in the **FoodList** component and invoke the **initializeOnStartup** method to assign a value to the variable. Create a member variable **foodItem** of the **FoodData** type in the **FoodListItem** component. Pass the **foodItems[0]** of the first element in the parent **foodItems** array as a parameter to **FoodListItem**.
```ts
import { FoodData } from '../model/FoodData'
import { initializeOnStartup } from '../model/FoodDataModels'
@Component
struct FoodListItem {
private foodItem: FoodData
build() {}
}
@Entry
@Component
struct FoodList {
......@@ -70,22 +62,65 @@ Use the List component and ForEach loop to build the food category list layout.
}
```
5. Declare the UI layout of the **FoodListItem** child component. Create a Flex component, including the food image thumbnail, food name, and calories in the food.
5. Declare the UI layout of the **FoodListItem** child component. Create a **\<Flex>** component, including the food image thumbnail, food name, and calories in the food.
```ts
import { FoodData } from '../model/FoodData'
import { initializeOnStartup } from '../model/FoodDataModels'
@Component
struct FoodListItem {
private foodItem: FoodData
build() {
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Image(this.foodItem.image)
.objectFit(ImageFit.Contain)
.height(40)
.width(40)
.margin({ right: 16 })
Text(this.foodItem.name)
.fontSize(14)
.flexGrow(1)
Text(this.foodItem.calories + ' kcal')
.fontSize(14)
}
.height(64)
.margin({ right: 24, left:32 })
}
}
@Entry
@Component
struct FoodList {
private foodItems: FoodData[] = initializeOnStartup()
build() {
List() {
ListItem() {
FoodListItem({ foodItem: this.foodItems[0] })
}
}
}
}
```
![en-us_image_0000001204776353](figures/en-us_image_0000001204776353.png)
6. Create two **FoodListItem** objects. Create two **FoodListItem** objects in the **List** component and pass the first element **this.foodItems[0]** and the second element **foodItem: this.foodItems[1]** to the **FoodListItem**.
```ts
import { FoodData } from '../model/FoodData'
import { initializeOnStartup } from '../model/FoodDataModels'
@Component
struct FoodListItem {
private foodItem: FoodData
build() {
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Image(this.foodItem.image)
.objectFit(ImageFit.Contain)
.height(40)
.width(40)
.backgroundColor('#FFf1f3f5')
.margin({ right: 16 })
Text(this.foodItem.name)
.fontSize(14)
......@@ -94,7 +129,7 @@ Use the List component and ForEach loop to build the food category list layout.
.fontSize(14)
}
.height(64)
.margin({ right: 24, left:32 })
.margin({ right: 24, left: 32 })
}
}
......@@ -102,55 +137,13 @@ Use the List component and ForEach loop to build the food category list layout.
@Component
struct FoodList {
private foodItems: FoodData[] = initializeOnStartup()
build() {
List() {
ListItem() {
FoodListItem({ foodItem: this.foodItems[0] })
}
}
}
}
```
![en-us_image_0000001267887833](figures/en-us_image_0000001267887833.png)
6. Create two **FoodListItem** objects. Create two **FoodListItem** objects in the **\<List>** component and pass the first element **this.foodItems[0]** and the second element **foodItem: this.foodItems[1]** to the **FoodListItem**.
```
import { FoodData } from '../model/FoodData'
import { initializeOnStartup } from '../model/FoodDataModels'
@Component
struct FoodListItem {
private foodItem: FoodData
build() {
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Image(this.foodItem.image)
.objectFit(ImageFit.Contain)
.height(40)
.width(40)
.backgroundColor('#FFf1f3f5')
.margin({ right: 16 })
Text(this.foodItem.name)
.fontSize(14)
.flexGrow(1)
Text(this.foodItem.calories + ' kcal')
.fontSize(14)
}
.height(64)
.margin({ right: 24, left:32 })
}
}
@Entry
@Component
struct FoodList {
private foodItems: FoodData[] = initializeOnStartup()
build() {
List() {
ListItem() {
FoodListItem({ foodItem: this.foodItems[0] })
}
ListItem() {
FoodListItem({ foodItem: this.foodItems[1] })
}
......@@ -158,36 +151,13 @@ Use the List component and ForEach loop to build the food category list layout.
}
}
```
![en-us_image_0000001267767849](figures/en-us_image_0000001267767849.png)
7. Import **ForEach** so that you do not need to create **FoodListItem** objects one by one.
```
ForEach(
arr: any[], // Array to be iterated
itemGenerator: (item: any) => void, // child component generator
keyGenerator?: (item: any) => string // (optional) Unique key generator, which is recommended.
)
```
The **ForEach** group has three parameters. The first parameter is the array to be traversed, the second parameter is the lambda function for generating child components, and the third parameter is the key value generator. The third parameter is optional. Yet, for performance reasons, it is strongly recommended that you provide it. keyGenerator enables the development framework to better recognize array changes without having to rebuild all nodes after item changes.
Traverse the foodItems array to cyclically create the ListItem component. Pass each item in foodItems as a parameter to the FoodListItem component.
```
ForEach(this.foodItems, item => {
ListItem() {
FoodListItem({ foodItem: item })
}
}, item => item.id.toString())
```
The code is as follows:
![en-us_image1_0000001204776353](figures/en-us_image1_0000001204776353.png)
```
7. Import [ForEach](../quick-start/arkts-rendering-control.md#loop-rendering) so that you do not need to create **FoodListItem** objects one by one.
```ts
import { FoodData } from '../model/FoodData'
import { initializeOnStartup } from '../model/FoodDataModels'
......@@ -199,8 +169,7 @@ Use the List component and ForEach loop to build the food category list layout.
Image(this.foodItem.image)
.objectFit(ImageFit.Contain)
.height(40)
.width(40)
.backgroundColor('#FFf1f3f5')
.width(40)
.margin({ right: 16 })
Text(this.foodItem.name)
.fontSize(14)
......@@ -228,23 +197,25 @@ Use the List component and ForEach loop to build the food category list layout.
}
}
```
8. Add a title for the FoodList.
8. Add a title for the **FoodList**.
```
@Entry
@Component
struct FoodList {
private foodItems: FoodData[] = initializeOnStartup()
build() {
Column() {
Flex({justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center}) {
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Text('Food List')
.fontSize(20)
.margin({ left:20 })
.margin({ left: 20 })
}
.height('7%')
.backgroundColor('#FFf1f3f5')
List() {
ForEach(this.foodItems, item => {
ListItem() {
......@@ -258,4 +229,4 @@ Use the List component and ForEach loop to build the food category list layout.
}
```
![en-us_image_0000001267607877](figures/en-us_image_0000001267607877.png)
![en-us_image_0000001169678922](figures/en-us_image_0000001169678922.png)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册