“201d4f2a85e8e25ae753f2cb4781363f4fc10adb”上不存在“git@gitcode.net:s920243400/PaddleDetection.git”
提交 87d7254c 编写于 作者: G Gloria

replaced application-dev (en) folder with that in master

Signed-off-by: wusongqing<wusongqing@huawei.com>
上级 a7c7ada2
# Development References
- [SysCap List](syscap-list.md)
- [SystemCapability](syscap.md)
- [SystemCapability List](syscap-list.md)
- [Component Reference (ArkTS-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md)
- [Component Reference (JavaScript-compatible Web-like Development Paradigm)](arkui-js/Readme-EN.md)
- [API Reference (JS and TS APIs)](apis/Readme-EN.md)
- [JS Service Widget UI Component Reference](js-service-widget-ui/Readme-EN.md)
- [API Reference (ArkTS and JS APIs)](apis/Readme-EN.md)
- [Error Codes](errorcodes/Readme-EN.md)
- API Reference (Native APIs)
- [Standard Libraries Supported by Native APIs](native-lib/Readme-EN.md)
......@@ -93,13 +93,11 @@
- [animateMotion](js-components-svg-animatemotion.md)
- [animateTransform](js-components-svg-animatetransform.md)
- Custom Components
- [Basic Usage](js-components-custom-basic-usage.md)
- [Style Inheritance](js-components-custom-style.md)
- [Custom Events](js-components-custom-events.md)
- [props](js-components-custom-props.md)
- [Event Parameter](js-components-custom-event-parameter.md)
- [Style Inheritance](js-components-custom-style.md)
- [slot](js-components-custom-slot.md)
- [Lifecycle Definition](js-components-custom-lifecycle.md)
- [Dynamic Component Creation](js-components-create-elements.md)
- [Data Type Attributes](js-appendix-types.md)
......@@ -18,7 +18,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| Name | Type | Default Value | Mandatory | Description |
| ---------------------- | ------- | ----- | ---- | ---------------------------------------- |
| type | string | - | No | Button type. The value cannot be dynamically updated. If this attribute is not set, a capsule-like button is displayed. Unlike the capsule button, the capsule-like button allows its corners to be configured using **border-radius**. Available button types are as follows:<br>- **capsule**: capsule button with fillets, background color, and text.<br>- **circle**: circle button that can accommodate icons.<br>- **text**: text button, which displays only text.<br>- **arc**: arc button. This value is applicable to wearables only.<br>- **download**: download button, with an extra download progress bar.|
| type | string | - | No | Button type. The value cannot be dynamically updated. By default, a capsule-like button is displayed. Unlike the capsule button, the capsule-like button allows its corners to be configured using **border-radius**. The options are as follows:<br>- **capsule**: capsule button with fillets, background color, and text.<br>- **circle**: circle button that can accommodate icons.<br>- **text**: text button, which displays only text.<br>- **arc**: arc button. This value is applicable to wearables only.<br>- **download**: download button, with an extra download progress bar.|
| value | string | - | No | Text value of the button. |
| icon | string | - | No | Path of the button icon. The supported icon formats are JPG, PNG, and SVG. |
| placement<sup>5+</sup> | string | end | No | Position of the button icon in text. This attribute is valid only when **type** is not set. Available values are as follows:<br>- **start**: The button icon is at the beginning of the text.<br>- **end**: The button icon is at the end of the text.<br>- **top**: The button icon is at the top of the text.<br>- **bottom**: The button icon is at the bottom of the text.|
......@@ -39,7 +39,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.|
| font-style | string | normal | No | Font style of the button. |
| font-weight | number \| string | normal | No | Font weight of the button. For details, see **font-weight** of the [**\<text>** component](../arkui-js/js-components-basic-text.md#styles).|
| font-family | &lt;string&gt; | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. |
| font-family | &lt;string&gt; | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.|
| icon-width | &lt;length&gt; | - | No | Width of the internal icon of a circle button. The entire circle button is filled by default.<br>This style must be set when the icon uses the SVG image.|
| icon-height | &lt;length&gt; | - | No | Height of the internal icon of a circle button. The entire circle button is filled by default.<br>This style must be set when the icon uses the SVG image.|
| radius | &lt;length&gt; | - | No | Corner radius of the button. For a circle button, this style takes precedence over **width** and **height** in the universal styles.|
......@@ -55,8 +55,8 @@ In addition to the **background-color**, **opacity**, **display**, **visibility*
| font-size | &lt;length&gt; | 37.5px | No | Font size of the arc button. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings. |
| font-style | string | normal | No | Font style of the arc button. |
| font-weight | number \| string | normal | No | Font weight of the arc button. For details, see **font-weight** of the [**\<text>** component](../arkui-js/js-components-basic-text.md#styles).|
| font-family | &lt;string&gt; | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. |
| font-weight | number \| string | normal | No | Font weight of the arc button. For details, see **font-weight** of the [**\<text>**](../arkui-js/js-components-basic-text.md#styles) component. |
| font-family | &lt;string&gt; | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.|
## Events
......
......@@ -22,7 +22,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| Name | Type | Default Value | Mandatory | Description |
| ------------------------------ | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| type | string | line | No | Chart type. Dynamic modification is not supported. Available values include:<br>- **bar**: bar chart.<br>- **line**: line chart.<br>- **gauge**: gauge chart.<br>- **progress**<sup>5+</sup>: circle chart of progresses.<br>- **loading**<sup>5+</sup>: circle chart of loading processes.<br>- **rainbow**<sup>5+</sup>: circle chart of proportions.|
| type | string | line | No | Chart type. Dynamic modification is not supported. Available values include:<br>- **bar**: bar chart<br>- **line**: line chart<br>- **gauge**: gauge chart<br>- **progress**<sup>5+</sup>: circle chart of progresses<br>- **loading**<sup>5+</sup>: circle chart of loading processes<br>- **rainbow**<sup>5+</sup>: circle chart of proportions|
| options | ChartOptions | - | No | Chart parameters. You must set parameters for bar charts and line charts. Parameter settings for gauge charts do not take effect. You can set the minimum value, maximum value, scale, and line width of the x-axis or y-axis, whether to display the x-axis and y-axis, and whether the line is smooth. Dynamic modification is not supported.|
| datasets | Array&lt;ChartDataset&gt; | - | No | Data sets. You must set data sets for bar charts and line charts. Data sets for a gauge chart do not take effect. You can set multiple datasets and their background colors.|
| segments<sup>5+</sup> | DataSegment \| Array&lt;DataSegment&gt; | - | No | Data structures used by **progress**, **loading**, and **rainbow** charts.<br>**DataSegment** is available for **progress** and **loading** charts.<br>**Array&lt;DataSegment&gt;** is available for **rainbow** charts. A maximum of nine **DataSegment**s are supported in the array.|
......@@ -99,7 +99,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| description | string | - | No | Description text of the point. |
| textLocation | string | - | No | Position of the description text relative to the point. Available values are as follows: **top**: above the point<br>**bottom**: below the point<br>**none**: not displayed|
| textColor | &lt;color&gt; | \#000000 | No | Color of the description text. |
| lineDash | string | solid | No | Dashed line pattern. You can set the dash length and space length between the dashes. For example, **"dashed, 5, 5"** indicates a dashed line with each dash in 5 px and a 5 px space between each two dashes. Default value **"solid"** indicates a solid line.|
| lineDash | string | solid | No | Dashed line pattern. You can set the dash length and space length between the dashes. - **"dashed, 5, 5"**: dashed line with each dash in 5 px and a 5 px space between each two dashes. Default value **"solid"** indicates a solid line.|
| lineColor | &lt;color&gt; | \#000000 | No | Line color. If this attribute is not set, the value of **strokeColor** is used. |
**Table 9** DataSegment<sup>5+</sup>
......@@ -144,7 +144,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| center-x | &lt;length&gt; | - | No | Center of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **position** style in the common styles, and must be used together with **center-y** and **radius**. This style is supported by the gauge chart only.|
| center-y | &lt;length&gt; | - | No | Center of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **position** style in the common styles, and must be used together with **center-x** and **radius**. This style is supported by the gauge chart only.|
| radius | &lt;length&gt; | - | No | Radius of the scale bar of the gauge component. This style is supported by the gauge chart only. This style takes precedence over the **width** and **height** in the common styles, and must be used together with **center-x** and **center-y**. This style is supported by the gauge chart only.|
| colors | Array | - | No | Color of each section for the scale bar of the gauge component.<br>For example, **colors: \#ff0000, #00ff00**. This style is supported by the gauge chart only.|
| colors | Array | - | No | Color of each section for the scale bar of the gauge component.<br>For example, **colors: \#ff0000, \#00ff00**. This style is supported by the gauge chart only.|
| weights | Array | - | No | Weight of each section for the scale bar of the gauge component.<br>For example, **weights: 2, 2**. This style is supported by the gauge chart only.|
| font-family<sup>5+</sup> | Array | - | No | Font style of the description text. You can use a [custom font](../arkui-js/js-components-common-customizing-font.md).|
| font-size<sup>5+</sup> | &lt;length&gt; | - | No | Font size of the description text. |
......@@ -161,7 +161,7 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
| Name | Parameter | Description |
| ------ | ---------------------------------------- | ---------------------------------------- |
| append | {<br>serial: number, // Set the data subscript of the line chart to be updated.<br>data: Array&lt;number&gt;, // Set the new data.<br>} | Data is dynamically added to an existing data sequence. The target sequence is specified based on **serial**, which is the subscript of the datasets array and starts from 0. **datasets[index].data** is not updated. Only line charts support this attribute. The value is incremented by 1 based on the horizontal coordinate and is related to the **xAxis min/max** setting.|
| append | {<br>serial: number, <br>data: Array&lt;number&gt;, <br>} | Data is dynamically added to an existing data sequence. The target sequence is specified based on **serial**, which is the subscript of the datasets array and starts from 0. For example, if the value of **serial** is **index**, use **data** to update **datasets[index].data**. Only line charts support this attribute. The value is incremented by 1 based on the horizontal coordinate and is related to the **xAxis min/max** setting.|
## Example
......@@ -212,24 +212,24 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
strokeColor: '#0081ff',
fillColor: '#cce5ff',
data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628, 791, 505, 613, 575, 475, 553, 491, 680, 657, 716],
gradient: true,
gradient: true
}
],
lineOps: {
xAxis: {
min: 0,
max: 20,
display: false,
display: false
},
yAxis: {
min: 0,
max: 1000,
display: false,
display: false
},
series: {
lineStyle: {
width: "5px",
smooth: true,
smooth: true
},
headPoint: {
shape: "circle",
......@@ -237,14 +237,14 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
strokeWidth: 5,
fillColor: '#ffffff',
strokeColor: '#007aff',
display: true,
display: true
},
loop: {
margin: 2,
gradient: true,
gradient: true
}
}
}
},
},
addData() {
this.$refs.linechart.append({
......@@ -295,15 +295,15 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
barData: [
{
fillColor: '#f07826',
data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628],
data: [763, 550, 551, 554, 731, 654, 525, 696, 595, 628]
},
{
fillColor: '#cce5ff',
data: [535, 776, 615, 444, 694, 785, 677, 609, 562, 410],
data: [535, 776, 615, 444, 694, 785, 677, 609, 562, 410]
},
{
fillColor: '#ff88bb',
data: [673, 500, 574, 483, 702, 583, 437, 506, 693, 657],
data: [673, 500, 574, 483, 702, 583, 437, 506, 693, 657]
},
],
barOps: {
......@@ -311,14 +311,14 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
min: 0,
max: 20,
display: false,
axisTick: 10,
axisTick: 10
},
yAxis: {
min: 0,
max: 1000,
display: false,
},
},
display: false
}
}
}
}
```
......@@ -353,3 +353,76 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
```
![en-us_image_0000001127125264](figures/en-us_image_0000001127125264.png)
4. Circle chart of progresses, loading progresses, or proportions
```html
<!-- xxx.hml -->
<div class="container">
<text class="text">progress Example</text>
<stack class="chart-region">
<chart class="" type="progress" segments="{{ progressdata }}"></chart>
</stack>
<text class="text">loading Example</text>
<stack class="chart-region">
<chart class="" type="loading" segments="{{ loadingdata }}"></chart>
</stack>
<text class="text">rainbow Example</text>
<stack class="chart-region">
<chart class="" type="rainbow" segments="{{ rainbowdata }}" effects="true" animationduration="5000"></chart>
</stack>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
}
.chart-region {
height: 400px;
width: 700px;
margin-top: 10px;
}
.text {
margin-top: 30px;
}
```
```js
// xxx.js
export default {
data: {
progressdata: {
value: 50,
name: 'progress'
},
loadingdata: {
startColor: "#ffc0cb",
endColor: "#00bfff",
},
rainbowdata: [
{
value: 50,
name: 'item1'
},
{
value: 10,
name: 'item2'
},
{
value: 20,
name: 'item3'
},
{
value: 10,
name: 'item4'
},
{
value: 10,
name: 'item5'
}
]
}
}
```
![rainbow](figures/rainbow.gif)
......@@ -31,7 +31,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| object-fit | string | cover | No | Image scale type. This style is not supported for SVG images. For details about available values, see **object-fit**.|
| match-text-direction | boolean | false | No | Whether image orientation changes with the text direction. This style is not supported for SVG images. |
| fit-original-size | boolean | false | No | Whether the **\<image>** component adapts to the image source size when its width and height are not set. If this style is set to **true**, **object-fit** will not take effect. This style is not supported for SVG images.|
| object-position<sup>7+</sup> | string | 0px 0px | No | Position of an image in the component.<br>The options are as follows:<br>1. Pixels. For example, **15px 15px** indicates the moving position along the x-axis or y-axis.<br>2. Characters. Optional values are as follows:<br>- **left**: The image is displayed on the left of the component.<br>- **top** The image is displayed on the top of the component.<br>- **right** The image is displayed on the right of the component.<br>- **bottom** The image is displayed at the bottom of the component.|
| object-position<sup>7+</sup> | string | 0px 0px | No | Position of the image in the component.<br>The options are as follows:<br>1. Pixels, in px. For example, **15px 15px** indicates the position to move along the x-axis or y-axis.<br>2. Characters. Optional values are as follows:<br>- **left**: The image is displayed on the left of the component.<<br>- **top**: The image is displayed on the top of the component.<br>- **right**: The image is displayed on the right of the component.<br>- **bottom**: The image is displayed at the bottom of the component.|
**Table 1** object-fit
......@@ -56,6 +56,8 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
> 1. If the **\<image>** component is too small to afford the SVG image, the SVG image is cropped and only its upper left part is displayed in the component.
>
> 2. If the **\<image>** component is big enough to afford the SVG image, this SVG image is displayed in the upper left corner of the component.
>
> - For SVG images, only the following tags are included in the supported list: **svg**, **rect**, **circle**, **ellipse**, **path**, **line**, **polyline**, **polygon**, **animate**, **animateMotion**, and **animateTransform**.
## Events
......@@ -63,9 +65,9 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported.
| Name | Parameter | Description |
| -------------- | ---------------------------------------- | ------------------------- |
| complete(Rich) | {<br> width: width,<br> height: height<br> } | Triggered when an image is successfully loaded. The loaded image size is returned.|
| error(Rich) | {<br> width: width,<br> height: height<br> } | Triggered when an exception occurs during image loading. In this case, the width and height are **0**. |
| -------- | ---------------------------------------- | ------------------------- |
| complete | {<br> width: width,<br> height: height<br> } | Triggered when an image is successfully loaded. The loaded image size is returned.|
| error | {<br> width: width,<br> height: height<br> } | Triggered when an exception occurs during image loading. In this case, the width and height are **0**. |
## Methods
......
......@@ -21,18 +21,18 @@ Not supported
In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported.
| Name | Type | Default Value | Mandatory | Description |
| -------------------------------- | ----------------------- | ------------- | --------- | ---------------------------------------- |
| type | string | text<br> | No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.<br>The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.<br>The **button**, **checkbox**, and **radio** types cannot be dynamically modified. <br>- **button**: a button that can be clicked.<br>- **checkbox**: a check box.<br>- **radio**: a radio button that allows users to select one from multiple others with the same name.<br>- **text**: a single-line text field.<br>- **email**: a field used for an email address.<br>- **date**: date component, including the year, month, and day, but excluding time.<br>- **time**: time component, without the time zone.<br>- **number**: field for entering digits.<br>- **password**: password field, in which characters will be shielded. |
| -------------------------------- | ----------------------- | --------- | ---- | ---------------------------------------- |
| type | string | text<br>| No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.<br>The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.<br>The **button**, **checkbox**, and **radio** types cannot be dynamically modified. <br>- **button**: a button that can be clicked.<br>- **checkbox**: a check box.<br>- **radio**: a radio button that allows users to select one from multiple others with the same name.<br>- **text**: a single-line text field.<br>- **email**: a field used for an email address.<br>- **date**: date component, including the year, month, and day, but excluding time.<br>- **time**: time component, without the time zone.<br>- **number**: field for entering digits.<br>- **password**: password field, in which characters will be shielded.|
| checked | boolean | false | No | Whether the **\<input>** component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**. |
| name | string | - | No | Name of the **\<input>** component.<br>This attribute is mandatory when **type** is set to **radio**. |
| value | string | - | No | Value of the **\<input>** component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name. |
| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text** \|email\|date\|time\|number\|**password**. |
| value | string | - | No | Value of the **\<input>** component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name.|
| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text** \|email\|date\|time\|number\|**password**.|
| maxlength | number | - | No | Maximum number of characters that can be entered in the input box. The empty value indicates no limit. |
| enterkeytype | string | default | No | Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.<br>Available values include:<br>- default<br>- next<br>- go<br>- done<br>- send<br>- search<br>Except for the **next** type, clicking the Enter key hides the soft keyboard. |
| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG. |
| enterkeytype | string | default | No | Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.<br>Available values include:<br>- default<br>- next<br>- go<br>- done<br>- send<br>- search<br>Except for the **next** type, clicking the Enter key hides the soft keyboard.|
| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG.|
| showcounter<sup>5+</sup> | boolean | false | No | Whether to display the character counter for an input box. This attribute takes effect only when **maxlength** is set. |
| menuoptions<sup>5+</sup> | Array&lt;MenuOption&gt; | - | No | Menu options displayed after users click the **More** button. |
| autofocus<sup>6+</sup> | boolean | false | No | Whether to automatically obtain focus.<br>This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**. |
| autofocus<sup>6+</sup> | boolean | false | No | Whether to automatically obtain focus.<br>This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**.|
| selectedstart<sup>6+</sup> | number | -1 | No | Start position for text selection. |
| selectedend<sup>6+</sup> | number | -1 | No | End position for text selection. |
| softkeyboardenabled<sup>6+</sup> | boolean | true | No | Whether to display the soft keyboard during editing. |
......@@ -41,9 +41,9 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
**Table 1** MenuOption<sup>5+</sup>
| Name | Type | Description |
| ------- | ------ | ----------------------------------- |
| icon | string | Path of the icon for a menu option. |
| content | string | Text content of a menu option. |
| ------- | ------ | ----------- |
| icon | string | Path of the icon for a menu option.|
| content | string | Text content of a menu option.|
## Styles
......@@ -51,11 +51,11 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported.
| Name | Type | Default Value | Mandatory | Description |
| ------------------------ | ---------------- | ------------- | --------- | ---------------------------------------- |
| ------------------------ | -------------------------- | ---------- | ---- | ---------------------------------------- |
| color | &lt;color&gt; | \#e6000000 | No | Font color of the single-line text box or button. |
| font-size | &lt;length&gt; | 16px | No | Font size of the single-line text box or button. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart. |
| placeholder-color | &lt;color&gt; | \#99000000 | No | Color of the hint text in the single-line text box. This attribute is available only when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.|
| placeholder-color | &lt;color&gt; | \#99000000 | No | Color of the hint text in the single-line text box. This attribute is available only when the component type is set to **text**, **email**, **date**, **time**, **number**, or **password**. |
| font-weight | number \| string | normal | No | Font weight of the single-line text box or button. For details, see **font-weight** of the [**\<text>**](../arkui-js/js-components-basic-text.md) component. |
| caret-color<sup>6+</sup> | &lt;color&gt; | - | No | Color of the caret. |
......@@ -68,19 +68,19 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md
| Name | Parameter | Description |
| ------------------------- | ---------------------------------------- | ---------------------------------------- |
| change | {<br> value: inputValue<br> } | Triggered when the content entered in the input box changes. The most recent content entered by the user is returned.<br>If you change the **value** attribute directly, this event will not be triggered. |
| enterkeyclick | {<br> value: enterKey<br> } | Triggered when the **Enter** key on the soft keyboard is clicked. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:<br>- **2**: returned if **enterkeytype** is **go**.<br>- **3**: returned if **enterkeytype** is **search**.<br>- **4**: returned if **enterkeytype** is **send**.<br>- **5**: returned if **enterkeytype** is **next**.<br>- **6**: returned if **enterkeytype** is **default**, **done**, or is not set. |
| translate<sup>5+</sup> | {<br> value: selectedText<br> } | Triggered when users click the translate button in the menu displayed after they select a text segment. The selected text content is returned. |
| share<sup>5+</sup> | {<br> value: selectedText<br> } | Triggered when users click the share button in the menu displayed after they select a text segment. The selected text content is returned. |
| search<sup>5+</sup> | {<br> value: selectedText<br> } | Triggered when users click the search button in the menu displayed after they select a text segment. The selected text content is returned. |
| optionselect<sup>5+</sup> | {<br> index: optionIndex,<br> value: selectedText<br> } | Triggered when users click a menu option in the menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned. |
| change | {<br> value: inputValue<br> } | Triggered when the content entered in the input box changes. The most recent content entered by the user is returned.<br>If you change the **value** attribute directly, this event will not be triggered.|
| enterkeyclick | {<br> value: enterKey<br> } | Triggered when the **Enter** key on the soft keyboard is clicked. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:<br>- **2**: returned if **enterkeytype** is **go**.<br>- **3**: returned if **enterkeytype** is **search**.<br>- **4**: returned if **enterkeytype** is **send**.<br>- **5**: returned if **enterkeytype** is **next**.<br>- **6**: returned if **enterkeytype** is **default**, **done**, or is not set.|
| translate<sup>5+</sup> | {<br> value: selectedText<br> } | Triggered when users click the translate button in the menu displayed after they select a text segment. The selected text content is returned.|
| share<sup>5+</sup> | {<br> value: selectedText<br> } | Triggered when users click the share button in the menu displayed after they select a text segment. The selected text content is returned.|
| search<sup>5+</sup> | {<br> value: selectedText<br> } | Triggered when users click the search button in the menu displayed after they select a text segment. The selected text content is returned.|
| optionselect<sup>5+</sup> | {<br> index: optionIndex,<br> value: selectedText<br> } | Triggered when users click a menu option in the menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned.|
| selectchange<sup>6+</sup> | {<br>start: number,<br>end: number<br> } | Triggered when the text selection changes. |
- When **type** is set to **checkbox** or **radio**, the following events are supported.
| Name | Parameter | Description |
| ------ | --------------------------------- | ---------------------------------------- |
| change | {<br> checked:true \| false <br>} | Triggered when the checked status of the **checkbox** or **radio** button changes. |
| ------ | ---------------------------------------- | ---------------------------------------- |
| change | {<br> checked:true \| false <br>} | Triggered when the checked status of the **checkbox** or **radio** button changes.|
## Methods
......@@ -102,21 +102,23 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
headericon="/common/search.svg" placeholder="Please input text" onchange="change"
onenterkeyclick="enterkeyClick">
</input>
<input class="button" type="button" value="Submit" onclick="buttonClick"></input>
<input class="button" type="button" value="Submit" onclick="buttonClick" style="color: blue"></input>
</div>
```
```css
/* xxx.css */
.content {
width: 60%;
width: 100%;
flex-direction: column;
align-items: center;
}
.input {
width: 60%;
placeholder-color: gray;
}
.button {
width: 60%;
background-color: gray;
margin-top: 20px;
}
......@@ -124,16 +126,16 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
```js
// xxx.js
import prompt from '@system.prompt'
import promptAction from '@ohos.promptAction'
export default {
change(e){
prompt.showToast({
promptAction.showToast({
message: "value: " + e.value,
duration: 3000,
});
},
enterkeyClick(e){
prompt.showToast({
promptAction.showToast({
message: "enterkey clicked",
duration: 3000,
});
......@@ -190,10 +192,10 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
```js
// xxx.js
import prompt from '@system.prompt'
import promptAction from '@ohos.promptAction'
export default {
checkboxOnChange(e) {
prompt.showToast({
promptAction.showToast({
message:'checked: ' + e.checked,
duration: 3000,
});
......@@ -225,11 +227,11 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
```js
// xxx.js
import prompt from '@system.prompt'
import promptAction from '@ohos.promptAction'
export default {
onRadioChange(inputValue, e) {
if (inputValue === e.value) {
prompt.showToast({
promptAction.showToast({
message: 'The chosen radio is ' + e.value,
duration: 3000,
});
......
......@@ -35,8 +35,8 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| font-size | &lt;length&gt; | 30px | No | Font size. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>For details about how to make the configuration take effect dynamically, see the **config-changes** attribute in the **config.json** file.|
| letter-spacing | &lt;length&gt; | 0px | No | Character spacing (px). |
| font-style | string | normal | No | Font style. Available values are as follows:<br>- **normal**: standard font style<br>- **italic**: italic font style|
| font-weight | number \| string | normal | No | Font width. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a larger font width.<br>The value of the number type must be an integer multiple of 100.<br>The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.|
| font-style | string | normal | No | Font style. Available values are as follows:<br>- **normal**: standard font style.<br>- **italic**: italic font style.|
| font-weight | number \| string | normal | No | Font weight. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a heavier font weight.<br>The value of the number type must be an integer multiple of 100.<br>The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.|
| text-decoration | string | none | No | Text decoration. Available values are as follows:<br>- **underline**: An underline is used.<br>- **line-through**: A strikethrough is used.<br>- **none**: The standard text is used.|
| text-align | string | start<br>| No | Text alignment mode. Available values are as follows:<br>- **left**: The text is left-aligned.<br>- **center**: The text is center-aligned.<br>- **right**: The text is right-aligned.<br>- **start**: The text is aligned with the direction in which the text is written.<br>- **end**: The text is aligned with the opposite direction in which the text is written.<br>If the text width is not specified, the alignment effect may not be obvious when the text width is the same as the width of the parent container.|
| line-height | &lt;length&gt; | 0px | No | Text line height. When this parameter is set to **0px**, the text line height is not limited and the font size is adaptive. |
......@@ -46,7 +46,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| min-font-size | &lt;length&gt; | - | No | Minimum font size in the text. This style must be used together with **max-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.|
| max-font-size | &lt;length&gt; | - | No | Maximum font size in the text. This style must be used together with **min-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.|
| font-size-step | &lt;length&gt; | 1px | No | Step for dynamically adjusting the font size in the text. The minimum and maximum font sizes must be set. |
| prefer-font-sizes | &lt;array&gt; | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.<br>Example values: **12px,14px,16px**|
| prefer-font-sizes | &lt;array&gt; | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.<br>Example: prefer-font-sizes: 12px,14px,16px|
## Events
......@@ -83,7 +83,7 @@ Not supported
/*xxx.css */
.container {
flex-direction: column;
align-items: center;
margin-left: 20px;
}
.row {
flex-direction: row;
......
......@@ -37,7 +37,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| color | &lt;color&gt; | \#e5000000 | No | Font color of the scrolling text. |
| font-size | &lt;length&gt; | 37.5 | No | Font size of the scrolling text. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.|
| font-weight | number&nbsp;\|&nbsp;string | normal | No | Font weight of the scrolling text. For details, see **font-weight** of the **[\<text> component](../arkui-js/js-components-basic-text.md#styles)**.|
| font-weight | number \| string | normal | No | Font weight of the scrolling text. For details, see **font-weight** of the **[\<text> component](../arkui-js/js-components-basic-text.md#styles)**.|
| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.|
......@@ -46,10 +46,10 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported.
| Name | Parameter | Description |
| ------------ | ---- | ---------------------------------------- |
| bounce(Rich) | - | Triggered when the marquee scrolls to the end. |
| finish(Rich) | - | Triggered when the marquee finishes the specified number of scrollings (value of the **loop** attribute). It can be triggered only when the **loop** attribute is set to a number greater than 0.|
| start(Rich) | - | Triggered when the marquee starts to scroll. |
| ------ | ---- | ---------------------------------------- |
| bounce | - | Triggered when the marquee scrolls to the end. |
| finish | - | Triggered when the marquee finishes the specified number of scrollings (value of the **loop** attribute). It can be triggered only when the **loop** attribute is set to a number greater than 0.|
| start | - | Triggered when the marquee starts to scroll. |
## Methods
......@@ -65,72 +65,75 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
```html
<!-- xxx.hml -->
<div class="container">
<marquee id="customMarquee" class="customMarquee" scrollamount="{{scrollAmount}}" loop="{{loop}}"direction="{{marqueeDir}}"
onbounce="onMarqueeBounce" onstart="onMarqueeStart" onfinish="onMarqueeFinish">{{marqueeCustomData}}</marquee>
<div class="content">
<button class="controlButton" onclick="onStartClick">Start</button>
<button class="controlButton" onclick="onStopClick">Stop</button>
<div class="tutorial-page">
<div class="mymarquee">
<marquee style="color: {{color1}}" loop="{{loopval}}" scrollamount="{{scroll}}" direction="{{isleft}}" class="marqueetext"
id="testmarquee" onfinish="setfinish">
Life is a journey, not the destination.
</marquee>
</div>
<div style="width: 600px;height: 150px;flex-direction: row;justify-content: space-around;">
<button onclick="makestart" value="start"></button>
<button onclick="makestop" value="stop"></button>
</div>
</div>
```
```css
/* xxx.css */
.container {
.tutorial-page {
width: 750px;
height: 100%;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #ffffff;
justify-content: center;
}
.customMarquee {
width: 100%;
height: 80px;
padding: 10px;
margin: 20px;
border: 4px solid #ff8888;
border-radius: 20px;
font-size: 40px;
color: #ff8888;
font-weight: bolder;
font-family: serif;
background-color: #ffdddd;
.marqueetext {
font-size: 37px;
}
.content {
flex-direction: row;
.mymarquee {
margin-top: 20px;
width:100%;
height: 100px;
margin-left: 50px;
margin-right: 50px;
border: 1px solid #dc0f27;
border-radius: 15px;
align-items: center;
}
.controlButton {
flex-grow: 1;
background-color: #F2F2F2;
text-color: #0D81F2;
button{
width: 200px;
height: 80px;
margin-top: 100px;
}
```
```js
// xxx.js
export default {
data: {
scrollAmount: 30,
loop: 3,
marqueeDir: 'left',
marqueeCustomData: 'Custom marquee',
},
onMarqueeBounce: function() {
console.log("onMarqueeBounce");
private: {
loopval: 1,
scroll: 8,
color1: 'red'
},
onMarqueeStart: function() {
console.log("onMarqueeStart");
onInit(){
},
onMarqueeFinish: function() {
console.log("onMarqueeFinish");
setfinish(e) {
this.loopval= this.loopval + 1,
this.r = Math.floor(Math.random()*255),
this.g = Math.floor(Math.random()*255),
this.b = Math.floor(Math.random()*255),
this.color1 = 'rgba('+ this.r +','+ this.g +','+ this.b +',0.8)',
this.$element('testmarquee').start(),
this.loopval= this.loopval - 1
},
onStartClick (evt) {
this.$element('customMarquee').start();
makestart(e) {
this.$element('testmarquee').start()
},
onStopClick (evt) {
this.$element('customMarquee').stop();
makestop(e) {
this.$element('testmarquee').stop()
}
}
```
![lite_bar](figures/lite_bar.gif)
![zh-cn_image_0000001176075554](figures/zh-cn_image_0000001176075554.gif)
......@@ -20,7 +20,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| ---- | ------ | ---- | ---- | ---------------------------------------- |
| type | string | text | No | Type of the scrollable selector, which cannot be changed dynamically. Available values are as follows:<br>- **text**: text selector.<br>- **time**: time selector.<br>- **date**: date selector.<br>- **datetime**: date and time selector.<br>- **multi-text**: multi-column text selector.|
Text selector (**type** is **text**)
### Text Selector
| Name | Type | Default Value | Mandatory | Description |
| --------------- | ------ | ---- | ---- | ---------------------------------------- |
......@@ -29,15 +29,15 @@ Text selector (**type** is **text**)
| indicatorprefix | string | - | No | Prefix field added when a value is specified for the text selector. |
| indicatorsuffix | string | - | No | Suffix field added when a value is specified for the text selector. |
Time selector (**type** is **time**)
### Time Selector
| Name | Type | Default Value | Mandatory | Description |
| ------------- | ------- | ----------------------------------- | ---- | ---------------------------------------- |
| containsecond | boolean | false | No | Whether seconds are contained. |
| selected | string | Current time | No | Default value of the time selector, in the format of HH:mm.<br>If seconds are contained, the format is HH:mm:ss.|
| hours | number | 24<sup>1-4</sup> | No | Time format used by the time selector. Available values are as follows:<br>- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.<br>- **24**: displayed in 24-hour format.<br>Since API version 5, the default value is the most commonly-used hour format in the current locale.|
| hours | number | 24<sup>1-4</sup><br>-<sup>5+</sup> | No | Time format used by the time selector. Available values are as follows:<br>- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.<br>- **24**: displayed in 24-hour format.<br>Since API version 5, the default value is the most commonly-used hour format in the current locale.|
Date selector (**type** is **date**)
### Date Selector
| Name | Type | Default Value | Mandatory | Description |
| ------------------ | ------------ | ---------- | ---- | ---------------------------------------- |
......@@ -47,16 +47,16 @@ Date selector (**type** is **date**)
| lunar<sup>5+</sup> | boolean | false | No | Whether the pop-up window displays the lunar calendar. |
| lunarswitch | boolean | false | No | Whether to display the lunar calendar switch in the date selector. When this switch is displayed, the user can switch between the lunar calendar and Gregorian calendar. Turn on the switch to display the lunar calendar, and turn off the switch to hide the lunar calendar.|
Date and time selector (**type** is **datetime**)
### Date and Time Selector
| Name | Type | Default Value | Mandatory | Description |
| ------------------ | ------- | ----------------------------------- | ---- | ---------------------------------------- |
| selected | string | Current date and time | No | Default value of the date and time selector. The value can be in the format of MM-DD-HH-mm or YYYY-MM-DD-HH-mm. If the year is not set, the current year is used by default. The value you set is the date selected by default in the pop-up window.|
| hours | number | 24<sup>1-4</sup> | No | Time format used by the date and time selector. Available values are as follows:<br>- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.<br>- **24**: displayed in 24-hour format.<br>Since API version 5, the default value is the most commonly-used hour format in the current locale.|
| hours | number | 24<sup>1-4</sup><br>-<sup>5+</sup> | No | Time format used by the date and time selector. Available values are as follows:<br>- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.<br>- **24**: displayed in 24-hour format.<br>Since API version 5, the default value is the most commonly-used hour format in the current locale.|
| lunar<sup>5+</sup> | boolean | false | No | Whether the pop-up window displays the lunar calendar. |
| lunarswitch | boolean | false | No | Whether to display the lunar calendar switch in the date and time selector. When this switch is displayed, the user can switch between the lunar calendar and Gregorian calendar. Turn on the switch to display the lunar calendar, and turn off the switch to hide the lunar calendar.|
Multi-column text selector (**type** is **multi-text**)
### Multi-Column Text Selector
| Name | Type | Default Value | Mandatory | Description |
| -------- | ------- | --------- | ---- | ---------------------------------------- |
......@@ -77,42 +77,42 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| selected-font-size | &lt;length&gt; | 20px | No | Font size of the selected item. The value is of the length type, in pixels. |
| disappear-color<sup>5+</sup> | &lt;color&gt; | \#ffffff | No | Font color of the items that gradually disappear. Disappearing items are the top option and bottom option of a column containing five options in total. |
| disappear-font-size<sup>5+</sup> | &lt;length&gt; | 14px | No | Font size of the items that gradually disappear. Disappearing items are the top option and bottom option of a column containing five options in total. |
| font-family | string | sans-serif | No | Font family of the selector, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.|
| font-family | string | sans-serif | No | Font family of the selector, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. |
## Events
The following events are supported.
Text selector (**type** is **text**)
### Text Selector
| Name | Parameter | Description |
| ------ | ---------------------------------------- | --------------- |
| change | {&nbsp;newValue:&nbsp;newValue,&nbsp;newSelected:&nbsp;newSelected&nbsp;} | Triggered when a value is specified for the text selector.|
| change | { newValue: newValue, newSelected: newSelected } | Triggered when a value is specified for the text selector.|
Time selector (**type** is **time**)
### Time Selector
| Name | Parameter | Description |
| ------ | ---------------------------------------- | ------------------------------- |
| change | {&nbsp;hour:&nbsp;hour,&nbsp;minute:&nbsp;minute,&nbsp;[second:second]} | Triggered when a value is specified for the time selector.<br>If seconds are contained, the value contains hour, minute, and second.|
| change | { hour: hour, minute: minute, [second:second]} | Triggered when a value is specified for the time selector.<br>If seconds are contained, the value contains hour, minute, and second.|
Date selector (**type** is **date**)
### Date Selector
| Name | Parameter | Description |
| ------ | ---------------------------------------- | --------------- |
| change | {&nbsp;year:year,&nbsp;month:month,&nbsp;day:day&nbsp;} | Triggered when a value is specified for the date selector.|
| change | { year:year, month:month, day:day } | Triggered when a value is specified for the date selector.|
Date and time selector (**type** is **datetime**)
### Date and Time Selector
| Name | Parameter | Description |
| ------ | ---------------------------------------- | ----------------- |
| change | {&nbsp;year:year,&nbsp;month:month,&nbsp;day:day,&nbsp;&nbsp;hour:hour,&nbsp;minute:minute&nbsp;} | Triggered when a value is specified for the date and time selector.|
| change | { year:year, month:month, day:day, hour:hour, minute:minute } | Triggered when a value is specified for the date and time selector.|
Multi-text selector (**type** is **multi-text**)
### Multi-Column Text Selector
| Name | Parameter | Description |
| ------------ | ---------------------------------------- | ---------------------------------------- |
| columnchange | {&nbsp;column:column,&nbsp;newValue:newValue,&nbsp;newSelected:newSelected&nbsp;} | Triggered when the value of a column in the multi-column selector changes. <br>**column**: column whose value has changed. <br>**newValue**: selected value. <br>**newSelected**: index of the selected value.|
| columnchange | { column:column, newValue:newValue, newSelected:newSelected } | Triggered when the value of a column in the multi-column selector changes. <br>**column**: column whose value has changed. <br>**newValue**: selected value. <br>**newSelected**: index of the selected value.|
## Methods
......@@ -121,20 +121,65 @@ Not supported
## Example
1. Text Selector
```html
<!-- xxx.hml -->
<div class="container">
<text class="title">
Selected value: {{value}} Selected index: {{index}}
</text>
<picker-view class="text-picker" type="text" range="{{options}}" selected="0" indicatorprefix="prefix" indicatorsuffix="suffix" @change="handleChange"></picker-view>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 454px;
height: 454px;
}
.title {
font-size: 30px;
text-align: center;
margin-top: 20px;
}
```
```html
<!-- xxx.hml -->
<div class="container" @swipe="handleSwipe">
```js
/* xxx.js */
export default {
data: {
options: ['Option 1','Option 2','Option 3'],
value: "Option 1",
index: 0
},
handleChange(data) {
this.value = data.newValue;
this.index = data.newSelected;
},
}
```
![](figures/pickerview1.gif)
2. Time Selector
```html
<!-- xxx.hml -->
<div class="container">
<text class="title">
Selected: {{time}}
</text>
<picker-view class="time-picker" type="time" selected="{{defaultTime}}" @change="handleChange"></picker-view>
</div>
```
</div>
```
```css
/* xxx.css */
.container {
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
......@@ -142,21 +187,21 @@ Not supported
top: 0px;
width: 454px;
height: 454px;
}
.title {
}
.title {
font-size: 30px;
text-align: center;
}
.time-picker {
}
.time-picker {
width: 500px;
height: 400px;
margin-top: 20px;
}
```
}
```
```js
/* xxx.js */
export default {
```js
/* xxx.js */
export default {
data: {
defaultTime: "",
time: "",
......@@ -173,15 +218,155 @@ export default {
const minutes = date.getMinutes();
return this.concat(hours, minutes);
},
fill(value) {
return (value > 9 ? "" : "0") + value;
},
concat(hours, minutes) {
return `${this.fill(hours)}:${this.fill(minutes)}`;
},
}
```
}
```
![](figures/pickerview2.gif)
3. Date Selector
```html
<!-- xxx.hml -->
<div class="container">
<text class="title">
Selected: {{time}}
</text>
<picker-view class="time-picker" type="time" selected="{{defaultTime}}" @change="handleChange"></picker-view>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 454px;
height: 454px;
}
.title {
font-size: 30px;
text-align: center;
margin-top: 20px;
}
.date-picker {
width: 500px;
height: 400px;
margin-top: 50px;
}
```
```js
/* xxx.js */
export default {
data: {
date: "",
},
handleChange(data) {
this.date = data.year + "" + data.month + "" + data.day + "";
},
}
```
![lite_bar-4](figures/lite_bar-4.png)
4. Date and Time Selector
```html
<!-- xxx.hml -->
<div class="container">
<text class="title">
Selected: {{datetime}}
</text>
<picker-view class="date-picker" type="datetime" hours="24" lunarswitch="true" @change="handleChange"></picker-view>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 500px;
height: 454px;
}
.title {
font-size: 30px;
text-align: center;
margin-top: 20px;
}
.date-picker {
width: 500px;
height: 400px;
margin-top: 50px;
}
```
```js
/* xxx.js */
export default {
data: {
datetime: "",
},
handleChange(data) {
this.datetime = data.year + "" + data.month + "" + data.day + "" + data.hour + "" + data.minute + "";
},
}
```
5. Multi-Column Text Selector
```html
<!-- xxx.hml -->
<div class="container">
<text class="title">
Selected: {{ value }}
</text>
<picker-view class="multitype-picker" type="multi-text" columns="3" range="{{ multitext }}" @columnchange="handleChange"></picker-view>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
left: 0px;
top: 0px;
width: 500px;
height: 454px;
}
.title {
font-size: 30px;
text-align: center;
margin-top: 20px;
}
```
```js
/* xxx.js */
export default {
data: {
multitext: [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
],
value: ""
},
handleChange(data) {
this.value = "Column: " + data.column + "," + "Value: " + data.newValue + ", Index:" + data.newSelected;
},
}
```
![](figures/pickerview5.gif)
......@@ -58,7 +58,7 @@ When **type** is set to **time**, a time selector is used.
| Name | Type | Default Value | Mandatory | Description |
| ------------- | ------- | ----------------------------------- | ---- | ---------------------------------------- |
| containsecond | boolean | false | No | Whether seconds are contained. |
| selected | string | Current time | No | Default value of the time selector, in format of HH:mm. If seconds are contained, the format is HH:mm:ss. |
| selected | string | Current time | No | Default value of the time selector, in format of HH:mm. If seconds are contained, the format is HH:mm:ss.<br> |
| value | string | - | No | Value of the time selector. |
| hours | number | 24<sup>1-4</sup><br>-<sup>5+</sup> | No | Time format used by the time selector. Available values are as follows:<br>- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.<br>- **24**: displayed in 24-hour format.<br>Since API version 5, the default value is the most commonly-used hour format in the current locale.|
......@@ -171,19 +171,24 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
{{ item }}
</option>
</select>
<picker id="picker0" type="text" value="{{textvalue}}" selected="{{textselect}}" range="{{rangetext}}" onchange="textonchange"
oncancel="textoncancel" class="pickertext"></picker>
<picker id="picker0" type="text" value="{{ textvalue }}" selected="{{ textselect }}" range="{{ rangetext }}"
onchange="textonchange"
oncancel="textoncancel" class="pickertext" show="false"></picker>
<picker id="picker1" type="date" value="{{datevalue}}" start="2002-2-5" end="2030-6-5" selected="{{dateselect}}" lunarswitch="true"
<picker id="picker1" type="date" value="{{ datevalue }}" start="2002-2-5" end="2030-6-5" selected="{{ dateselect }}"
lunarswitch="true"
onchange="dateonchange" oncancel="dateoncancel" class="pickerdate" show="false"></picker>
<picker id="picker2" type="time" value="{{timevalue}}" containsecond="{{containsecond}}" selected="{{timeselect}}" hours="12"
<picker id="picker2" type="time" value="{{ timevalue }}" containsecond="{{ containsecond }}"
selected="{{ timeselect }}" hours="12"
onchange="timeonchange" oncancel="timeoncancel" class="pickertime" show="false"></picker>
<picker id="picker3" type="datetime" value="{{datetimevalue}}" selected="{{datetimeselect}}" hours="24" lunarswitch="true"
<picker id="picker3" type="datetime" value="{{ datetimevalue }}" selected="{{ datetimeselect }}" hours="24"
lunarswitch="true"
onchange="datetimeonchange" oncancel="datetimeoncancel" class="pickerdatetime" show="false"></picker>
<picker id="picker4" type="multi-text" value="{{multitextvalue}}" columns="3" range="{{multitext}}" selected="{{multitextselect}}"
<picker id="picker4" type="multi-text" value="{{ multitextvalue }}" columns="3" range="{{ multitext }}"
selected="{{ multitextselect }}"
onchange="multitextonchange" oncancel="multitextoncancel" class="pickermuitl" show="false"></picker>
</div>
```
......@@ -195,16 +200,18 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
justify-content: center;
align-items: center;
}
picker{
width:60%;
height:80px;
border-radius:20px;
text-color:white;
font-size:15px;
background-color:#4747e3;
margin-left:20%;
picker {
width: 60%;
height: 80px;
border-radius: 20px;
text-color: white;
font-size: 15px;
background-color: #4747e3;
margin-left: 20%;
}
select{
select {
background-color: #efecec;
height: 50px;
width: 60%;
......@@ -219,68 +226,92 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
// xxx.js
import router from '@system.router';
import prompt from '@system.prompt';
export default {
data: {
selectList:["text","data","time","datetime","multitext"],
rangetext:['15', "20", "25"],
multitext:[["a", "b", "c"], ["e", "f", "g"], ["h", "i"], ["k", "l", "m"]],
textvalue:'default textvalue',
datevalue:'default datevalue',
timevalue:'default timevalue',
datetimevalue:'default datetimevalue',
multitextvalue:'default multitextvalue',
containsecond:true,
multitextselect:[1,2,0],
datetimeselect:'2012-5-6-11-25',
timeselect:'11:22:30',
dateselect:'2021-3-2',
textselect:'2'
selectList: ["text", "data", "time", "datetime", "multitext"],
rangetext: ['15', "20", "25"],
multitext: [["a", "b", "c"], ["e", "f", "g"], ["h", "i"], ["k", "l", "m"]],
textvalue: 'default textvalue',
datevalue: 'default datevalue',
timevalue: 'default timevalue',
datetimevalue: 'default datetimevalue',
multitextvalue: 'default multitextvalue',
containsecond: true,
multitextselect: [1, 2, 0],
datetimeselect: '2012-5-6-11-25',
timeselect: '11:22:30',
dateselect: '2021-3-2',
textselect: '2'
},
selectChange(e){
for(let i = 0;i<this.selectList.length;i++){
if(e.newValue == this.selectList[i]){
this.$element("picker"+i).show();
selectChange(e) {
for (let i = 0;i < this.selectList.length; i++) {
if (e.newValue == this.selectList[i]) {
this.$element("picker" + i).show();
}
}
},
textonchange(e) {
this.textvalue = e.newValue;
prompt.showToast({ message:"text:"+e.newValue+",newSelected:"+e.newSelected })
prompt.showToast({
message: "text:" + e.newValue + ",newSelected:" + e.newSelected
})
},
textoncancel(e) {
prompt.showToast({ message:"text: textoncancel" })
prompt.showToast({
message: "text: textoncancel"
})
},
dateonchange(e) {
this.datevalue = e.year + "-" + e.month + "-" + e.day;
prompt.showToast({ message:"date:"+e.year+"-"+(e.month+1)+"-"+e.day })
prompt.showToast({
message: "date:" + e.year + "-" + (e.month + 1) + "-" + e.day
})
},
dateoncancel() {
prompt.showToast({ message:"date: dateoncancel" })
prompt.showToast({
message: "date: dateoncancel"
})
},
timeonchange(e) {
if(this.containsecond){
this.timevalue=e.hour+":"+e.minute+":"+e.second;
prompt.showToast({ message:"Time:" + e.hour + ":" + e.minute + ":" + e.second })
if (this.containsecond) {
this.timevalue = e.hour + ":" + e.minute + ":" + e.second;
prompt.showToast({
message: "Time:" + e.hour + ":" + e.minute + ":" + e.second
})
} else {
this.timevalue=e.hour+":"+e.minute;
prompt.showToast({ message:"Time:" + e.hour + ":" + e.minute })
}},
this.timevalue = e.hour + ":" + e.minute;
prompt.showToast({
message: "Time:" + e.hour + ":" + e.minute
})
}
},
timeoncancel() {
prompt.showToast({ message:"timeoncancel" })
prompt.showToast({
message: "timeoncancel"
})
},
datetimeonchange(e) {
this.datetimevalue=e.year+"-"+e.month+"-"+e.day+" "+e.hour+":"+e.minute;
prompt.showToast({ message:"Time:"+(e.month+1)+"-"+e.day+" "+e.hour+":"+e.minute })
this.datetimevalue = e.year + "-" + e.month + "-" + e.day + " " + e.hour + ":" + e.minute;
prompt.showToast({
message: "Time:" + (e.month + 1) + "-" + e.day + " " + e.hour + ":" + e.minute
})
},
datetimeoncancel() {
prompt.showToast({ message:"datetimeoncancel" })
prompt.showToast({
message: "datetimeoncancel"
})
},
multitextonchange(e) {
this.multitextvalue=e.newValue;
prompt.showToast({ message:"Multi-column text change" + e.newValue })
this.multitextvalue = e.newValue;
prompt.showToast({
message: "Multi-column text change" + e.newValue
})
},
multitextoncancel() {
prompt.showToast({ message:"multitextoncancel" })
prompt.showToast({
message: "multitextoncancel"
})
},
popup_picker() {
this.$element("picker_text").show();
......
# qrcode
The **\<qrcode>** component is used to generate and display a QR code.
> **NOTE**
>
> This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version.
The **\<qrcode>** component is used to generate and display a QR code.
## Required Permissions
......@@ -24,7 +23,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| Name | Type | Default Value | Mandatory | Description |
| ----- | ------ | ---- | ---- | ---------------------------------------- |
| value | string | - | Yes | Content used to generate the QR code. |
| type | string | rect | No | QR code type. Available values are as follows:<br>- **rect**: rectangular QR code<br>- **circle**: round QR code|
| type | string | rect | No | QR code type. Available values are as follows:<br>- **rect**: rectangular QR code.<br>- **circle**: round QR code.|
## Styles
......@@ -60,8 +59,6 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support
<div class="container">
<qrcode value="{{qr_value}}" type="{{qr_type}}"
style="color: {{qr_col}};background-color: {{qr_bcol}};width: {{qr_size}};height: {{qr_size}};margin-bottom: 70px;"></qrcode>
<text class="txt">Value</text>
<input onChange="setValue">123</input>
<text class="txt">Type</text>
<switch showtext="true" checked="true" texton="rect" textoff="circle" onchange="settype"></switch>
<text class="txt">Color</text>
......@@ -98,7 +95,6 @@ select{
/* index.js */
export default {
data: {
qr_value:'',
qr_type: 'rect',
qr_size: '300px',
qr_col: '#87ceeb',
......@@ -113,9 +109,6 @@ export default {
this.qr_type = 'circle'
}
},
setvalue(e) {
this.qr_value = e.newValue
},
setcol(e) {
this.qr_col = e.newValue
},
......
# search
> **NOTE**
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Search>** component provides an input area for users to search.
The **\<search>** component provides an input area for users to search.
## Child Components
......@@ -42,7 +41,7 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| font-size | &lt;length&gt; | 16px | No | Font size of the search box. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.|
| placeholder-color | &lt;color&gt; | \#99000000<br>| No | Color of the hint text. |
| font-weight | number \| string | normal | No | Font weight. For details, see **font-weight** of the **[\<text>](../arkui-js/js-components-basic-text.md#styles)** component.|
| font-weight | number \| string | normal | No | Font weight. For details, see [font-weight](../arkui-js/js-components-basic-text.md#styles) of the **\<text>** component.|
| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.|
| caret-color<sup>6+</sup> | &lt;color&gt; | - | No | Color of the caret. |
......
......@@ -9,7 +9,7 @@ The **<select\>** component provides a drop-down list that allows users to selec
## Child Components
The **<[option](js-components-basic-option.md)\>** child component is supported.
The **[<option\>](js-components-basic-option.md)** child component is supported.
## Attributes
......@@ -49,15 +49,9 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support
```html
<!-- xxx.hml -->
<div class="container">
<select @change="changeFruit">
<option value="bananaValue">
Banana
</option>
<option value="appleValue" selected="true">
Apple
</option>
<option value="pearValue">
Pear
<select @change="onChange">
<option for="{{ array }}" value="{{ $item.value }}">
{{ $item.name }}
</option>
</select>
</div>
......@@ -69,16 +63,51 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
```
```js
// ×××.js
// xxx.js
export default {
changeFruit(e){
console.log("newValue:" + e.newValue)
data: {
array: [
{
"value": "Option 0", "name": "Option 0"
},
{
"value": "Option 1", "name": "Option 1"
},
{
"value": "Option 2", "name": "Option 2"
},
{
"value": "Option 3", "name": "Option 3"
},
]
},
getData() {
let other = [
{
"value": "Option A", "name": "Option A"
},
{
"value": "Option B", "name": "Option B"
},
{
"value": "Option C", "name": "Option C"
},
{
"value": "Option D", "name": "Option D"
},
]
return other
},
onChange() {
this.array = this.getData()
}
}
```
![en-us_image_0000001152588538](figures/en-us_image_0000001152588538.png)
![en-us_image_0000001152588538](figures/en-us_image_0000001152588538.gif)
......@@ -4,7 +4,7 @@
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Slider>** component is used to quickly adjust settings, such as the volume and brightness.
The **\<slider>** component is used to quickly adjust settings, such as the volume and brightness.
## Child Components
......@@ -22,7 +22,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| max | number | 100 | No| Maximum value of the slider.|
| step | number | 1 | No| Step of each slide.|
| value | number | 0 | No| Initial value of the slider.|
| mode<sup>5+</sup> | string | outset | No| Slider style. Available values are as follows:<br>- **outset**: The slider is on the sliding bar.<br>- **inset**: The slider is inside the sliding bar.|
| mode<sup>5+</sup> | string | outset | No| Slider style. Available values are as follows:<br>- **outset**: The slider is on the slider track.<br>- **inset**: The slider is in the slider track.|
| showsteps<sup>5+</sup> | boolean | false | No| Whether to display slider scales.|
| showtips<sup>5+</sup> | boolean | false | No| Whether a tooltip is displayed to show the percentage value on the slider.|
......@@ -51,7 +51,7 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md
| Attribute| Type| Description|
| -------- | -------- | -------- |
| value<sup>5+</sup> | number | Current value of the slider.|
| mode<sup>5+</sup> | string | Type of the change event. Available values are as follows:<br>- **start**: The **value** starts to change.<br>- **move**: The **value** is changing with users' dragging.<br>- **end**: The **value** stops changing.|
| mode<sup>5+</sup> | string | Type of the change event. Available values are as follows:<br>- **start**: The **value** starts to change.<br>- **move**: The **value** is changing with users' dragging.<br>- **end**: The **value** stops changing.<br>- **click**: The **value** changes upon a touch on the slider.|
## Example
......@@ -59,10 +59,9 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md
```html
<!-- xxx.hml -->
<div class="container">
<text>slider start value is {{startValue}}</text>
<text>slider current value is {{currentValue}}</text>
<text>slider end value is {{endValue}}</text>
<slider min="0" max="100" value="{{value}}" onchange="setvalue" ></slider>
<slider min="0" max="100" value="{{ value }}" mode="outset" showtips="true"></slider>
<slider class="" min="0" max="100" value="{{ value }}" step="20" mode="inset" showtips="true"></slider>
<slider class="" min="0" max="100" value="{{ value }}" showsteps="true" step="20" mode="inset" showtips="false"></slider>
</div>
```
......@@ -72,35 +71,11 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md
flex-direction: column;
justify-content: center;
align-items: center;
}
```
```js
// xxx.js
export default {
data: {
value: 0,
startValue: 0,
currentValue: 0,
endValue: 0,
},
setvalue(e) {
if (e.mode == "start") {
this.value = e.value;
this.startValue = e.value;
} else if (e.mode == "move") {
this.value = e.value;
this.currentValue = e.value;
} else if (e.mode == "end") {
this.value = e.value;
this.endValue = e.value;
} else if (e.mode == "click) {
this.value = e.value;
this.currentValue = e.value;
}
}
slider{
margin-top: 100px;
}
```
![slider](figures/slider.png)
......@@ -30,18 +30,20 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
## Styles
In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported.
| Name | Type | Default Value | Mandatory | Description |
| ------------------- | -------------------------- | ---------- | ---- | ---------------------------------------- |
| texton-color(Rich) | &lt;color&gt; | \#000000 | No | Text color displayed when the component is checked. |
| textoff-color(Rich) | &lt;color&gt; | \#000000 | No | Text color displayed when the component is not checked. |
| text-padding(Rich) | number | 0px | No | Distance between the two sides of the longest text in **texton** and **textoff** and the border of the slider. |
| font-size(Rich) | &lt;length&gt; | - | No | Font size. This attribute is available only when **texton** and **textoff** are set. |
| allow-scale(Rich) | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.|
| font-style(Rich) | string | normal | No | Font style. This attribute is available only when **texton** and **textoff** are set. For details, see **font-style** of the [**\<text>**](../arkui-js/js-components-basic-text.md#styles) component.|
| font-weight(Rich) | number \| string | normal | No | Font weight. This attribute is available only when **texton** and **textoff** are set. For details, see **font-weight** of the [**\<text>**](../arkui-js/js-components-basic-text.md#styles) component.|
| font-family(Rich) | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. This attribute is available only when **texton** and **textoff** are set.|
| ------------- | -------------------------- | ---------- | ---- | ---------------------------------------- |
| texton-color | &lt;color&gt; | \#000000 | No | Text color displayed when the component is checked. This attribute is available only when **texton** and **textoff** are set. |
| textoff-color | &lt;color&gt; | \#000000 | No | Text color displayed when the component is not checked. This attribute is available only when **texton** and **textoff** are set. |
| text-padding | number | 0px | No | Distance between the two sides of the longest text in **texton** and **textoff** and the border of the slider. |
| font-size | &lt;length&gt; | - | No | Font size. This attribute is available only when **texton** and **textoff** are set. |
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.|
| font-style | string | normal | No | Font style. This attribute is available only when **texton** and **textoff** are set. For details, see [font-style](../arkui-js/js-components-basic-text.md#styles) of the **\<text>** component.|
| font-weight | number \| string | normal | No | Font weight. This attribute is available only when **texton** and **textoff** are set. For details, see [font-weight](../arkui-js/js-components-basic-text.md#styles) of the **\<text>** component.|
| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. This attribute is available only when **texton** and **textoff** are set.|
## Events
......@@ -61,7 +63,11 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support
```html
<!-- xxx.hml -->
<div class="container">
<switch showtext="true" texton="On" textoff="Off" checked="true" @change="switchChange">
<switch @change="normalswitchChange">
</switch>
<switch class="switch" showtext="true" texton="On" textoff="Off" @change="switchChange">
</switch>
<switch class="switch text" showtext="true" texton="Switch on" textoff="Switch off" checked="true" @change="switchChange">
</switch>
</div>
```
......@@ -73,33 +79,47 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support
justify-content: center;
align-items: center;
}
switch{
texton-color:#002aff;
textoff-color:silver;
text-padding:20px;
.switch {
texton-color: red;
textoff-color: forestgreen;
}
.text {
text-padding: 20px;
font-size: 30px;
font-weight: 700;
}
```
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
data: {
title: 'World'
},
switchChange(e){
console.log(e.checked);
if(e.checked){
prompt.showToast({
switchChange(e) {
if (e.checked) {
promptAction.showToast({
message: "Switch on."
});
}else{
prompt.showToast({
} else {
promptAction.showToast({
message: "Switch off."
});
}
},
normalswitchChange(e) {
if (e.checked) {
promptAction.showToast({
message: "switch on"
});
} else {
promptAction.showToast({
message: "switch off"
});
}
}
}
```
![en-us_image_0000001152862510](figures/en-us_image_0000001152862510.gif)
![en-us_image_0000001152862510](figures/switch.gif)
......@@ -15,7 +15,7 @@ None
## Child Components
Only the **[\<span>](../arkui-js/js-components-basic-span.md)** component is supported.
The **[\<span>](../arkui-js/js-components-basic-span.md)** child component is supported.
## Attributes
......@@ -34,19 +34,19 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.<br>For details about how to make the configuration take effect dynamically, see the **config-changes** attribute in the **config.json** file.|
| letter-spacing | &lt;length&gt; | 0px | No | Character spacing (px). |
| word-spacing<sup>7+</sup> | &lt;length&gt; \| &lt;percentage&gt; \| string | normal | No | Spacing between texts. If the input is a string, the options are as follows:<br>**normal**: default spacing.|
| font-style | string | normal | No | Font style. Available values are as follows:<br>- **normal**: standard font style<br>- **italic**: italic font style|
| font-weight | number \| string | normal | No | Font width. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a larger font width. The value of the number type must be an integer multiple of 100.<br>The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.|
| font-style | string | normal | No | Font style. Available values are as follows:<br>- **normal**: standard font style.<br>- **italic**: italic font style.|
| font-weight | number \| string | normal | No | Font weight. For the number type, the value ranges from 100 to 900. The default value is 400. A larger value indicates a heavier font weight. The value of the number type must be an integer multiple of 100.<br>The value of the string type can be **lighter**, **normal**, **bold**, or **bolder**.|
| text-decoration | string | none | No | Text decoration. Available values are as follows:<br>- **underline**: An underline is used.<br>- **line-through**: A strikethrough is used.<br>- **none**: The standard text is used.|
| text-decoration-color<sup>7+</sup> | &lt;color&gt; | - | No | Color of the text decoration. |
| text-align | string | start<br> | No | Text alignment mode. Available values are as follows:<br>- **left**: The text is left-aligned.<br>- **center**: The text is center-aligned.<br>- **right**: The text is right-aligned.<br>- **start**: The text is aligned with the direction in which the text is written.<br>- **end**: The text is aligned with the opposite direction in which the text is written.<br>If the text width is not specified, the alignment effect may not be obvious when the text width is the same as the width of the parent container.|
| line-height | &lt;length&gt; \| &lt;percentage&gt;<sup>7+</sup> \| string<sup>7+</sup> | 0px<sup>1-6</sup><br>normal<sup>7+</sup> | No | Text line height. When this parameter is set to **0px**, the text line height is not limited and the font size is adaptive. The value of the string type is as follows:<br>**normal**<sup>7+</sup>: default line height |
| line-height | &lt;length&gt; \| &lt;percentage&gt;<sup>7+</sup> \| string<sup>7+</sup> | 0px<sup>1-6</sup><br>normal<sup>7+</sup> | No | Text line height. When this parameter is set to **0px**, the text line height is not limited and the font size is adaptive. The value of the string type is as follows:<br>**normal**<sup>7+</sup>: default line height|
| text-overflow | string | clip | No | Display mode when the text is too long. This style takes effect when the maximum number of lines is specified. Available values are as follows:<br>- **clip**: The text is clipped and displayed based on the size of the parent container.<br>- **ellipsis**: The text is displayed based on the size of the parent container. The text that cannot be displayed is replaced with ellipsis. This style must be used together with **max-lines**.|
| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.|
| max-lines | number \| string<sup>7+</sup> | - | No | Maximum number of text lines. The value of the string type is as follows:<br>- **auto**<sup>7+</sup>: The number of text lines adapts to the container height. |
| max-lines | number \| string<sup>7+</sup> | - | No | Maximum number of text lines. The value of the string type is as follows:<br>- **auto**<sup>7+</sup>: The number of text lines adapts to the container height.|
| min-font-size | &lt;length&gt; | - | No | Minimum font size in the text. This style must be used together with **max-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.|
| max-font-size | &lt;length&gt; | - | No | Maximum font size in the text. This style must be used together with **min-font-size**. The font size can be changed dynamically. After the maximum and minimum font sizes are set, **font-size** does not take effect.|
| font-size-step | &lt;length&gt; | 1px | No | Step for dynamically adjusting the font size in the text. The minimum and maximum font sizes must be set. |
| prefer-font-sizes | &lt;array&gt; | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.<br>Example values: **12px,14px,16px**|
| prefer-font-sizes | &lt;array&gt; | - | No | Preset preferred font sizes. For dynamic font size adjustment, the preset sizes are used to match the maximum number of lines in the text. If the preferred font sizes were not set, the font size will be adjusted based on the maximum and minimum font sizes and the step you have set. If the maximum number of lines in the text cannot be met, **text-overflow** is used to truncate the text. If this parameter is set, **font-size**, **max-font-size**, **min-font-size**, and **font-size-step** do not take effect.<br>Example: prefer-font-sizes: 12px,14px,16px|
| word-break<sup>6+</sup> | string | normal | No | Text line breaking mode. The options are as follows:<br>- **normal**: Allows text line breaks between words as appropriate to the relevant language writing systems. This is the default mode.<br>- **break-all**: Allows text line breaks between any characters for writing systems other than Chinese, Japanese, and Korean.<br>- **break-word**: Works in the same way as **break-all**, except that it does not break unbreakable words.|
| text-indent<sup>7+</sup> | &lt;length&gt; | - | No | Indentation of the first line. |
| white-space<sup>7+</sup> | string | pre | No | Mode for processing blanks in the component. The options are as follows:<br>- **normal**: All spaces, carriage returns, and tabs are combined into one space, and the text is automatically wrapped.<br>- **nowrap**: All spaces, carriage returns, and tabs are combined into one space, and the text is not wrapped.<br>- **pre**: All contents are output as-is.<br>- **pre-wrap**: All contents are output as-is with line breaks.<br>- **pre-line**: All spaces and tabs are combined into one space, the carriage return remains unchanged, and the text is wrapped.|
......@@ -76,15 +76,20 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support
## Example
1.
```html
<!-- xxx.hml -->
<div class="container">
<div class="content">
<text class="title">
Hello {{ title }}
</text>
</div>
<text class="title">default text</text>
<text class="title textcolor">hello world with color</text>
<text class="title textsize">hello world with font-size</text>
<text class="title textletterspacing">hello world with letter-spacing</text>
<text class="title textwordspacing">hello world with word-spacing</text>
<text class="title textstyle">hello world with italic</text>
<text class="title textweight">hello world with font-weight</text>
<text class="title textdecoration1">hello world with underline</text>
<text class="title textdecoration2">hello world with line-through</text>
<text class="title textalign">hello world with text-align:right</text>
</div>
```
......@@ -94,66 +99,42 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are support
display: flex;
justify-content: center;
align-items: center;
}
.content{
width: 400px;
height: 400px;
border: 20px;
flex-direction: column;
}
.title {
font-size: 80px;
text-align: center;
width: 400px;
height: 400px;
width: 800px;
height: 60px;
}
```
```js
// xxx.js
export default {
data: {
title: 'World'
}
.textcolor {
color: indianred;
}
```
![3](figures/3.png)
```html
<!-- xxx.hml -->
<div class="container">
<text class="text1">
This is a passage
</text>
<text class="text2">
This is a passage
</text>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
align-items: center;
background-color: #F1F3F5;
justify-content: center;
.textsize {
font-size: 40px;
}
.text1{
word-spacing: 10px;
adapt-height: true;
.textletterspacing {
letter-spacing: -3px;
}
.text2{
width: 200px;
max-lines: 1;
text-overflow: ellipsis;
text-valign: middle;
line-height: 40px;
.textwordspacing {
word-spacing: 20px;
}
.textstyle {
font-style: italic;
}
.textweight {
font-weight: 700;
}
.textdecoration1 {
text-decoration: underline;
}
.textdecoration2 {
text-decoration: line-through;
text-decoration-color: red;
text-indent: 20px;
white-space: pre;
}
.textalign {
text-align: right;
}
```
![2](figures/2.png)
![en-us_image_0000001167823076](figures/text.png)
# xcomponent
> **NOTE**
>
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<xcomponent>** displays the components to which the EGL/OpenGLES or media data is written.
The **\<xcomponent>** displays the components to which the EGL/OpenGLES or media data is written.
## Required Permissions
None
None
## Child Components
Not supported
Not supported
## Attributes
......
......@@ -11,7 +11,7 @@ The **\<canvas>** component is used for customizing drawings.
None
## Child Component
## Child Components
Not supported
......@@ -38,7 +38,7 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
### getContext
getContext(type: '2d', options?: ContextAttrOptions): CanvasRendering2dContext
getContext(type: '2d', options?: ContextAttrOptions): CanvasRenderingContext2D
Obtains the canvas drawing context. This API cannot be called in **onInit** or **onReady**.
......@@ -49,7 +49,7 @@ Obtains the canvas drawing context. This API cannot be called in **onInit** or *
| type | string | Yes | Object type. The value is set to **'2d'**, indicating that a 2D drawing object is returned. This object can be used to draw rectangles, texts, and images on the canvas component.|
| options<sup>6+</sup> | ContextAttrOptions | No | Whether to enable anti-aliasing. By default, anti-aliasing is disabled. |
**Table 1** ContextAttrOptions
**Table 1** ContextAttrOptions
| Name | Type | Description |
| --------- | ------- | ------------------- |
......@@ -59,7 +59,7 @@ Obtains the canvas drawing context. This API cannot be called in **onInit** or *
| Type | Description |
| ---------------------------------------- | -------------------- |
| [CanvasRenderingContext2D](../arkui-js/js-components-canvas-canvasrenderingcontext2d.md) | 2D drawing object, which can be used to draw rectangles, images, and texts, on the canvas component. |
| [CanvasRenderingContext2D](../arkui-js/js-components-canvas-canvasrenderingcontext2d.md) | 2D drawing object, which can be used to draw rectangles, images, and texts on the canvas component.|
### toDataURL<sup>6+</sup>
......
......@@ -25,19 +25,21 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 500px; height: 500px; background-color: #ffff00;"></canvas>
<input type="button" style="width: 180px; height: 60px;" value="fillStyle"onclick="handleClick" />
</div>
```
```js
// xxx.js
export default {
handleClick() {
onShow() {
const el =this.$refs.canvas;
const ctx =el.getContext('2d');
const gradient = ctx.createLinearGradient(0,0,100,0);
gradient.addColorStop(0,'#00ffff');
gradient.addColorStop(1,'#ffff00');
const ctx = el.getContext('2d');
const gradient = ctx.createLinearGradient(50,0,300,100);
gradient.addColorStop(0.0, '#ff0000')
gradient.addColorStop(0.5, '#ffffff')
gradient.addColorStop(1.0, '#00ff00')
ctx.fillStyle = gradient
ctx.fillRect(0, 0, 300, 300)
}
}
```
......
......@@ -2,7 +2,7 @@
> **NOTE**
>
> Supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
**CanvasRenderingContext2D** allows you to draw rectangles, text, images, and other objects on a canvas.
......@@ -426,9 +426,9 @@ export default {
}
```
![en-us_image_0000001213192781](figures/en-us_image_0000001213192781.png)
![en-us_image_0000001213192781](figures/en-us_image_0000001213192781.png)
In the above example, the blue rectangle represents the new drawing, and the red rectangle represents the existing drawing.
In the above example, the blue rectangle represents the new drawing, and the red rectangle represents the existing drawing.
### shadowBlur
......@@ -585,7 +585,7 @@ Fills a rectangle on the canvas.
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px; "></canvas>
<canvas ref="canvas" style="width: 500px; height: 500px; "></canvas>
</div>
```
......@@ -621,7 +621,7 @@ Clears the content in a rectangle on the canvas.
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px;"></canvas>
<canvas ref="canvas" style="width: 500px; height: 500px;"></canvas>
</div>
```
......@@ -984,7 +984,7 @@ Creates a pattern for image filling based on a specified source image and repeti
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px;"></canvas>
<canvas ref="canvas" style="width: 1000px; height: 1000px;"></canvas>
</div>
```
......@@ -998,7 +998,7 @@ Creates a pattern for image filling based on a specified source image and repeti
img.src = 'common/images/example.jpg';
var pat = ctx.createPattern(img, 'repeat');
ctx.fillStyle = pat;
ctx.fillRect(0, 0, 20, 20);
ctx.fillRect(0, 0, 500, 500);
}
}
```
......@@ -1429,7 +1429,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para
setTransform(scaleX: number, skewX: number, skewY: number, scale: number, translateX: number, translateY: number): void
Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** function.
Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** API.
**Parameters**
......@@ -1574,7 +1574,7 @@ Draws an image on the canvas.
```html
<!-- xxx.hml -->
<div>
<canvas style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<canvas ref="canvas" style="width: 500px; height: 500px; background-color: #ffff00;"></canvas>
</div>
```
......@@ -1582,11 +1582,11 @@ Draws an image on the canvas.
//xxx.js
export default {
onShow() {
var test = this.$element('drawImage');
var test = this.$refs.canvas;
var ctx = test.getContext('2d');
var img = new Image();
img.src = 'common/image/test.jpg';
ctx.drawImage(img, 50, 80, 80, 80);
ctx.drawImage(img, 0, 0, 200, 200, 10, 10, 200, 200);
}
}
```
......@@ -1682,9 +1682,9 @@ Creates a linear gradient and returns a **CanvasGradient** object. For details,
// Linear gradient: start(50,0) end(300,100)
var gradient = ctx.createLinearGradient(50,0, 300,100);
// Add three color stops
gradient.addColorStop(0.0, 'red');
gradient.addColorStop(0.5, 'white');
gradient.addColorStop(1.0, 'green');
gradient.addColorStop(0.0, '#ff0000');
gradient.addColorStop(0.5, '#ffffff');
gradient.addColorStop(1.0, '#00ff00');
// Set the fill style and draw a rectangle
ctx.fillStyle = gradient;
ctx.fillRect(0, 0, 500, 500);
......
......@@ -65,7 +65,7 @@ Sets the path transformation matrix.
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<canvas ref="canvas" style="width: 300px; height: 250px; background-color: #ffff00;"></canvas>
</div>
```
......@@ -95,7 +95,7 @@ Moves the current point of the path back to the start point of the path, and dra
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<canvas ref="canvas" style="width: 500px; height: 500px; background-color: #ffff00;"></canvas>
</div>
```
......@@ -223,7 +223,7 @@ Draws a cubic bezier curve on the canvas.
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<canvas ref="canvas" style="width: 300px; height: 250px; background-color: #ffff00;"></canvas>
</div>
```
......@@ -264,7 +264,7 @@ Draws a quadratic curve on the canvas.
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<canvas ref="canvas" style="width: 300px; height: 250px; background-color: #ffff00;"></canvas>
</div>
```
......@@ -307,7 +307,7 @@ Draws an arc on the canvas.
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<canvas ref="canvas" style="width: 300px; height: 250px; background-color: #ffff00;"></canvas>
</div>
```
......@@ -348,7 +348,7 @@ Draws an arc based on the radius and points on the arc.
```html
<!-- xxx.hml -->
<div>
<canvas ref="canvas" style="width: 200px; height: 150px; background-color: #ffff00;"></canvas>
<canvas ref="canvas" style="width: 300px; height: 250px; background-color: #ffff00;"></canvas>
</div>
```
......
......@@ -31,5 +31,114 @@ Rendering attributes are used to set whether a component is rendered.
| if | boolean | - | Whether the element is added or removed.|
| show | boolean | - | Whether the element is displayed or hidden.|
> **NOTE**<br>
> **NOTE**
>
> Do not set styles in attribute fields.
## Example
### Example 1
```html
<!-- xxx.hml -->
<div id="container">
<button class="btn" type="capsule" value="toggleDisplay" onclick="toggleDisplay"></button>
<list class="list">
<list-item for="{{ array }}" class="listItem">
<text class="text" onclick="toggleShow" show="{{ visible }}"
if="{{ display }}">{{ $item.value }}</text>
</list-item>
</list>
</div>
```
```css
/* xxx.css */
#container {
flex-direction: column;
width: 100%;
margin-top: 10px;
}
.text {
font-size: 50px;
font-weight: 500;
margin-left: 12px;
}
.listItem {
width: 100%;
height: 100px;
line-height: 60px;
border-bottom: 1px solid #DEDEDE;
font-size: 20px;
}
.btn{
width: 280px;
font-size: 26px;
margin: 10px 0;
}
```
```js
// xxx.js
export default {
data: {
visible: true,
display: true,
title: "",
i: 4,
array: [
{"value": "Item 0"},
{"value": "Item 1"},
{"value": "Item 2"},
{"value": "Item 3"},
],
},
toggleShow: function() {
this.array.push ({"value": "Item" + this.i })
this.i++
},
toggleDisplay: function() {
this.display = !this.display
},
}
```
![en-us-attributes](figures/en-us-attributes.gif)
### Example 2
```html
<!-- xxx.hml -->
<div class="container">
<div>
<text class="text1" dir='rtl' >hello world</text>
</div>
<div>
<text class="text2" dir='ltr' >hello world</text>
</div>
</div>
```
```css
/* xxx.css */
.container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
.text1{
width: 90%;
height: 100px;
background-color: aqua;
}
.text2{
width: 90%;
height: 100px;
background-color: blue;
}
```
![en-us_image1](figures/en-us_image1.png)
......@@ -11,8 +11,8 @@ The custom font can be loaded from the font file in a project. The font file mus
```
@font-face {
font-family: HWfont;
src: url('/common/HWfont.ttf');
font-family: font;
src: url('/common/font.ttf');
}
```
......@@ -48,10 +48,10 @@ Page style:
```css
/*xxx.css*/
@font-face {
font-family: HWfont;
src: url("/common/HWfont.ttf");
font-family: font;
src: url("/common/font.ttf");
}
.demo-text {
font-family: HWfont;
font-family: font;
}
```
......@@ -32,7 +32,7 @@ animate( keyframes: Keyframes, options: Options): void
| height | number | - | Height set for the component during playback of the animation. |
| backgroundColor | &lt;color&gt; | none | Background color set for the component during playback of the animation. |
| opacity | number | 1 | Opacity set for the component. The value ranges from 0 to 1. |
| backgroundPosition | string | - | The value format is **x y**, in percentage or pixels.<br>The first value indicates the horizontal position, and the second value indicates the vertical position.<br>If only one value is specified, the other value is **50%**.|
| backgroundPosition | string | - | The value format is **"x y"**, in percentage or pixels.<br>The first value indicates the horizontal position, and the second value indicates the vertical position.<br>If only one value is specified, the other value is **50%**.|
| transformOrigin | string | 'center center' | Origin position of the transformed element.<br>The first value indicates the x-axis position. The value can be **left**, **center**, **right**, a length, or a percentage.<br>The second value indicates the y-axis position. The value can be **top**, **center**, **bottom**, a length, or a percentage.|
| transform | [Transform](../arkui-js/js-components-common-animation.md) | - | Transformation type set for a transformed element. |
| offset | number | - | - The value of **offset** must be within (0.0, 1.0] and sorted in ascending order if it is provided.<br>- If there are only two frames, **offset** can be left empty.<br>- If there are more than two frames, **offset** is mandatory.|
......@@ -53,10 +53,10 @@ animate( keyframes: Keyframes, options: Options): void
| Value | Description |
| ---------------------------------------- | ---------------------------------------- |
| linear | The animation speed keeps unchanged. |
| ease-in | The animation starts at a low speed. **cubic-bezier(0.42, 0.0, 1.0, 1.0)**.|
| ease-out | The animation ends at a low speed. **cubic-bezier(0.0, 0.0, 0.58, 1.0)**.|
| ease-in-out | The animation starts and ends at a low speed. **cubic-bezier(0.42, 0.0, 0.58, 1.0)**.|
| friction | The animation uses the damping curve, **cubic-bezier(0.2, 0.0, 0.2, 1.0)**.|
| ease-in | The animation starts at a low speed and then picks up speed until the end. The cubic-bezier curve (0.42, 0.0, 1.0, 1.0) is used.|
| ease-out | The animation ends at a low speed. The cubic-bezier curve (0.0, 0.0, 0.58, 1.0) is used.|
| ease-in-out | The animation starts and ends at a low speed. The cubic-bezier curve (0.42, 0.0, 0.58, 1.0) is used.|
| friction | The animation uses the friction cubic-bezier curve (0.2, 0.0, 0.2, 1.0).|
| extreme-deceleration | The animation uses the extreme deceleration cubic-bezier curve (0.0, 0.0, 0.0, 1.0).|
| sharp | The animation uses the sharp cubic-bezier curve (0.33, 0.0, 0.67, 1.0).|
| rhythm | The animation uses the rhythm cubic-bezier curve (0.7, 0.0, 0.2, 1.0).|
......@@ -71,7 +71,7 @@ animate( keyframes: Keyframes, options: Options): void
| --------- | ------- | ---------------------------------------- |
| finished | boolean | Read-only attribute, which indicates whether the animation playback is complete. |
| pending | boolean | Read-only attribute, which indicates whether the animation is waiting for the completion of other asynchronous operations (for example, start an animation with a delay).|
| playState | string | Read-write attribute, which indicates the playback status of the animation:<br>- **idle**: The animation is not running (playback ended or not started).<br>- **running**: The animation is running.<br>- **paused**: The animation is paused.<br>- **finished**: Animation playback ends.|
| playState | string | Read-write attribute, which indicates the playback status of the animation:<br>- **idle**: The animation is not running (playback ended or not started).<br>- **running**: The animation is running.<br>- **paused**: The animation is paused.<br>- **finished**: The animation finishes playing.|
| startTime | number | Read-write attribute, which indicates the animation start time. This attribute is similar to **delay** in the **options** attribute. |
The **animation** methods are as follows.
......@@ -103,7 +103,7 @@ animate( keyframes: Keyframes, options: Options): void
start
</button>
<button @click="cancel">
cancels
cancel
</button>
</div>
</div>
......@@ -139,7 +139,7 @@ button{
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default{
data:{
animation:'',
......@@ -162,19 +162,19 @@ export default{
this.animation = this.$element('idName').animate(frames, options);
// handle finish event
this.animation.onfinish = function(){
prompt.showToast({
promptAction.showToast({
message: "The animation is finished."
});
};
// handle cancel event
this.animation.oncancel = function(){
prompt.showToast({
promptAction.showToast({
message: "The animation is canceled."
});
};
// handle repeat event
this.animation.onrepeat = function(){
prompt.showToast({
promptAction.showToast({
message: "The animation is repeated."
});
};
......
......@@ -9,61 +9,61 @@ You can set universal styles for components in the **style** attribute or **.css
| Name | Type | Default Value | Description |
| ---------------------------------------- | ---------------------------------------- | ------------ | ---------------------------------------- |
| width | &lt;length&gt; \| &lt;percentage&gt; | - | Component width.<br>If this attribute is not set, the width required for the element content is used.<br> |
| height | &lt;length&gt; \| &lt;percentage&gt; | - | Component height.<br>If this attribute is not set, the height required for the element content is used.<br> |
| width | &lt;length&gt; \| &lt;percentage&gt; | - | Component width.<br>If this attribute is not set, the width required for the element content is used. |
| height | &lt;length&gt; \| &lt;percentage&gt; | - | Component height.<br>If this attribute is not set, the height required for the element content is used. |
| min-width<sup>5+</sup> | &lt;length&gt; \| &lt;percentage&gt;<sup>6+</sup> | 0 | Minimum component width. |
| min-height<sup>5+</sup> | &lt;length&gt; \| &lt;percentage&gt;<sup>6+</sup> | 0 | Minimum component height. |
| max-width<sup>5+</sup> | &lt;length&gt; \| &lt;percentage&gt;<sup>6+</sup> | - | Maximum component width, which has no restriction by default. |
| max-height<sup>5+</sup> | &lt;length&gt; \| &lt;percentage&gt;<sup>6+</sup> | - | Maximum component height, which has no restriction by default. |
| padding | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | Shorthand attribute to set the padding for all sides in a declaration.<br>The attribute can have one to four values:<br>- If you set only one value, it specifies the padding for all the four sides.<br>- If you set two values, the first value specifies the top and bottom padding, and the second value specifies the left and right padding.<br>- If you set three values, the first value specifies the top padding, the second value specifies the left and right padding, and the third value specifies the bottom padding.<br>- If you set four values, they respectively specify the padding for top, right, bottom, and left sides (in clockwise order).|
| padding-[left \| top \| right \| bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | Left, top, right, and bottom padding. |
| padding-[start \| end] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | Start and end padding. |
| padding-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | Left, top, right, and bottom padding. |
| padding-[start\|end] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | Start and end padding. |
| margin | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | Shorthand attribute to set the margin for all sides in a declaration. The attribute can have one to four values:<br>- If you set only one value, it specifies the margin for all the four sides.<br>- If you set two values, the first value specifies the top and bottom margins, and the second value specifies the left and right margins.<br>- If you set three values, the first value specifies the top margin, the second value specifies the left and right margins, and the third value specifies the bottom margin.<br>- If you set four values, they respectively specify the margin for top, right, bottom, and left sides (in clockwise order).|
| margin-[left \| top \| right \| bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | Left, top, right, and bottom margins. |
| margin-[start \| end] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | Start and end margins. |
| margin-[left\|top\|right\|bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | Left, top, right, and bottom margins. |
| margin-[start\|end] | &lt;length&gt; \| &lt;percentage&gt;<sup>5+</sup> | 0 | Start and end margins. |
| border | - | 0 | Shorthand attribute to set all borders. Set **border-width**, **border-style**, and **border-color** in sequence. Default values are used for attributes that are not set.|
| border-style | string | solid | Shorthand attribute to set the style for all borders. Available values are as follows:<br>- **dotted**: dotted border. The radius of a dot is half of **border-width**.<br>- **dashed**: dashed border.<br>- **solid**: solid border.|
| border-[left\|top\|right\|bottom]-style | string | solid | Styles of the left, top, right, and bottom borders. The available values are **dotted**, **dashed**, and **solid**.|
| border-[left \| top \| right \| bottom] | - | - | Shorthand attribute to set the borders for every side respectively. Set **border-width**, **border-style**, and **border-color** in sequence. Default values are used for attributes that are not set.|
| border-[left\|top\|right\|bottom] | - | - | Shorthand attribute to set the borders for every side respectively. Set **border-width**, **border-style**, and **border-color** in sequence. Default values are used for attributes that are not set.|
| border-width | &lt;length&gt; | 0 | Shorthand attribute to set the width for all borders, or separately set the width for each border. |
| border-[left \| top \| right \| bottom]-width | &lt;length&gt; | 0 | Attribute to set widths of left, top, right, and bottom borders. |
| border-[left\|top\|right\|bottom]-width | &lt;length&gt; | 0 | Attribute to set widths of left, top, right, and bottom borders. |
| border-color | &lt;color&gt; | black | Shorthand attribute to set the color for all borders, or separately set the color for each border. |
| border-[left \| top \| right \| bottom]-color | &lt;color&gt; | black | Attribute to set colors for left, top, right, and bottom borders. |
| border-radius | &lt;length&gt; | - | Attribute to set the radius for round borders of an element. This attribute cannot be used to set the width, color, or style of a specific border. To set the width or color, you need to set **border-width**, **border-color**, or **border-style** for all the borders at the same time.|
| border-[top \| bottom]-[left \| right]-radius | &lt;length&gt; | - | Attribute to respectively set the radii of upper-left, upper-right, lower-right, and lower-left rounded corners |
| border-[left\|top\|right\|bottom]-color | &lt;color&gt; | black | Attribute to set colors for left, top, right, and bottom borders. |
| border-radius | &lt;length&gt; | - | Attribute to set the radius for round borders of an element. This attribute cannot be used to set the width, color, or style of a specific border. To set the width or color, you need to set **border-width**, **border-color**, or **border-style** for all the borders at the same time.<br>In the four-value syntax, the values apply to lower-left corner, lower-right corner, upper-left corner, and upper-right corner, respectively.|
| border-[top\|bottom]-[left\|right]-radius | &lt;length&gt; | - | Attribute to respectively set the radii of upper-left, upper-right, lower-right, and lower-left rounded corners |
| background | &lt;linear-gradient&gt; | - | Background. This attribute supports [gradient styles](../arkui-js/js-components-common-gradient.md) only and is not compatible with **background-color** or **background-image**.|
| background-color | &lt;color&gt; | - | Background color. |
| background-image | string | - | Background image. Both online and local image resources are supported. Currently, this attribute is not compatible with **background-color** or **background**.<br>Example:<br>- background-image: url("/common/background.png")<br>The SVG format is not supported.|
| background-size | - string<br>- &lt;length&gt; &lt;length&gt;<br>- &lt;percentage&gt; &lt;percentage&gt; | auto | Background image size.<br>- The **string** values are as follows:<br> - **contain**: Expands the image to the maximum size so that its height and width are fully applicable to the content area.<br> - **cover**: Extends the background image to a large enough size so that it completely covers the background area. Some parts of the image may not be displayed in the background area.<br> - **auto**: Retains the original aspect ratio of the image.<br>- The two **\<length>** values are as follows:<br> Width and height of the background image. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.<br>- The two **\<percentage>** values are as follows:<br> Width and height of the background image in percentage of the parent element. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.|
| background-repeat | string | repeat | How a background image is repeatedly drawn. By default, a background image is repeated both horizontally and vertically.<br>- **repeat**: The image is repeated along the x-axis and y-axis at the same time.<br>- **repeat-x**: The image is repeated along the x-axis.<br>- **repeat-y**: The image is repeated along the y-axis.<br>- **no-repeat**: The image is not repeated.|
| background-position | - string string<br>- &lt;length&gt; &lt;length&gt;<br>- &lt;percentage&gt; &lt;percentage&gt; | 0px 0px | - Using keywords: If only one keyword is specified, the other value is **center** by default. The two values define the horizontal position and vertical position, respectively.<br> - **left**: leftmost in the horizontal direction.<br> - **right**: rightmost in the horizontal direction.<br> - **top**: top in the vertical direction.<br> - **bottom**: bottom in the vertical direction.<br> - **center**: center position.<br>- Using **\<length>**: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is **0 0**. The unit is pixel. If only one value is specified, the other one is **50%**.<br>- Using **\<percentage>**: The first value indicates the horizontal position, and the second value indicates the vertical position. **0% 0%** indicates the upper left corner. **100% 100%** indicates the lower right corner. If only one value is specified, the other one is **50%**.<br>- Using both **\<percentage>** and **\<length>**. |
| box-shadow<sup>5+</sup> | string | 0 | Syntax: **box-shadow: h-shadow v-shadow blur spread color**<br>Shadow style of the current component. The value includes the horizontal position (mandatory), vertical position (mandatory), fuzzy radius (optional, default value: **0**), extension distance (optional, default value: **0**), and color (optional, default value: **black**) of the shadow.<br>Example:<br>- box-shadow :10px 20px 5px 10px \#888888<br>- box-shadow :100px 100px 30px red<br>- box-shadow :-100px -100px 0px 40px |
| filter<sup>5+</sup> | string | - | Syntax: **filter: blur(px)**<br>Radius of the blur area within the component layout. If this style is not set, the default value **0** (no blur) is used. Percentage values are not supported.<br>Example:<br>- filter: blur(10px) |
| backdrop-filter<sup>5+</sup> | string | - | Syntax: **backdrop-filter: blur(px)**<br>Radius of the background blur area within the component layout. If this style is not set, the default value **0** (no blur) is used. Percentage values are not supported.<br>Example:<br>- backdrop-filter: blur(10px) |
| window-filter<sup>5+</sup> | string | - | Syntax: window-filter: blur(percent), style<sup>5+</sup><br>Blur degree and style for windows within the component layout. If this style is not set, the default value **0%** (no blur area) is used. Different blur degrees and styles for multiple blur areas are not supported. Available blur styles are as follows: **small_light** (default value), **medium_light**, **large_light**, **xlarge_light**, **small_dark**, **medium_dark**, **large_dark**, and **xlarge_dark**.<br>Example:<br>- window-filter: blur(50%)<br>- window-filter: blur(10%), large_light |
| background-size | - string<br>- &lt;length&gt; &lt;length&gt;<br>- &lt;percentage&gt; &lt;percentage&gt; | auto | Background image size.<br>- The available values of the **string** type are as follows:<br> - **contain**: extends the image to the maximum size so that its height and width are fully applicable to the content area.<br> - **cover**: extends the background image to a large enough size so that it completely covers the background area. Some parts of the image may not be displayed in the background area.<br> - **auto**: retains the original aspect ratio of the image.<br>- Values of the **\<length>** type:<br>The two values are width and height of the background image. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.<br>- Values of the **\<percentage>** type:<br>The two values are width and height of the background image in percentage of the parent element. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.|
| background-repeat | string | repeat | How a background image is repeatedly drawn. By default, a background image is repeated both horizontally and vertically.<br>- **repeat**: The image is repeated along both the x-axis and y-axis.<br>- **repeat-x**: The image is repeated along the x-axis.<br>- **repeat-y**: The image is repeated along the y-axis.<br>- **no-repeat**: The image is not repeated.|
| background-position | - string string<br>- &lt;length&gt; &lt;length&gt;<br>- &lt;percentage&gt; &lt;percentage&gt; | 0px 0px | - Values of the **string** type: If only one value is specified, the other value is **center** by default. The two values define the horizontal position and vertical position, respectively.<br> - **left**: leftmost in the horizontal direction.<br> - **right**: rightmost in the horizontal direction.<br> - **top**: top in the vertical direction.<br> - **bottom**: bottom in the vertical direction.<br> - **center**: center in the horizontal or vertical direction.<br>- Values of the **\<length>** type: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is 0 0 in px (**0px 0px**). If only one value is specified, the other one is **50%**.<br>- Values of the **\<percentage>** type: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is 0% 0%. For the lower right corner, the value is **100% 100%**. If only one value is specified, the other one is **50%**.<br>- Values of the **\<percentage>** type and **\<length>** type can be used together.|
| box-shadow<sup>5+</sup> | string | 0 | Syntax: box-shadow: h-shadow v-shadow blur spread color<br>Shadow style of the current component. The value includes the horizontal position (mandatory), vertical position (mandatory), fuzzy radius (optional, default value: **0**), extension distance (optional, default value: **0**), and color (optional, default value: **black**) of the shadow.<br>Example:<br>- box-shadow :10px 20px 5px 10px \#888888<br>- box-shadow :100px 100px 30px red<br>- box-shadow :-100px -100px 0px 40px |
| filter<sup>5+</sup> | string | - | Syntax: filter: blur(px)<br>Radius of the blur area within the component layout. If this style is not set, the default value **0** (no blur) is used. Percentage values are not supported.<br>Example:<br>- filter: blur(10px) |
| backdrop-filter<sup>5+</sup> | string | - | Syntax: backdrop-filter: blur(px)<br>Radius of the background blur area within the component layout. If this style is not set, the default value **0** (no blur) is used. Percentage values are not supported.<br>Example:<br>- backdrop-filter: blur(10px) |
| window-filter<sup>5+</sup> | string | - | Syntax: window-filter: blur(percent), style<sup>5+</sup><br>Blur degree and style for windows within the component layout. If this style is not set, the default value **0%** (no blur area) is used. Different blur degrees and styles for multiple blur areas are not supported. Available values of **style** are as follows: small_light (default value), medium_light, large_light, xlarge_light, small_dark, medium_dark, large_dark, xlarge_dark<br>Example:<br>- window-filter: blur(50%)<br>- window-filter: blur(10%), large_light |
| opacity | number | 1 | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. |
| display | string | flex | Type of the box containing an element. Available values are as follows:<br>- **flex**: Flexible layout.<br>- **none**: The box is disabled.<br>- **inline**<sup>9+</sup>: Inline box, where the element is displayed as an inline element and does not start on a new line.<br>- **block**<sup>9+</sup>: Block box, where the element is displayed as a block-level element and always starts on a new line. This is the default value for container components.<br>- **inline-block**<sup>9+</sup>: Inline-block box, where the element is displayed on one line and you can set a width and height on the element. This is the default value for basic components.|
| display | string | flex | Type of the box containing an element. Available values are as follows:<br>- **flex**: flexible layout<br>- **none**: not rendered<br>- **grid**: grid layout (available only for the **\<div>** component) |
| visibility | string | visible | Whether to display the box containing an element. The invisible box occupies layout space. (To remove the box, set the **display** attribute to **none**.) Available values are as follows:<br>- **visible**: The element is visible.<br>- **hidden**: The box is hidden but still takes up space.<br>If both **visibility** and **display** are set, only **display** takes effect.|
| flex | number \| string | - | How to divide available space of the parent component for each child component.<br>You can set one, two<sup>5+</sup>, or three<sup>5+</sup> values for this style.<br>Set one value in either of the following ways:<br>- A unitless number to set **flex-grow**.<br>- A valid width value<sup>5+</sup> to set **flex-basis**.<br>Set two values<sup>5+</sup> in the following ways:<br>The first value must be a unitless number used to set **flex-grow**. The second value must be either of the following:<br>- A unitless number to set **flex-shrink**.<br>- A valid width value to set **flex-basis**.<br>Set three values<sup>5+</sup> in the following ways:<br>The first value must be a unitless number used to set **flex-grow**. The second value must be a unitless number used to set **flex-shrink**. The third value must be a valid width value used to set **flex-basis**.<br>This style takes effect only when the container is any of the following components: **\<div>**, **\<list-item>**, **\<tabs>**, **\<refresh>**, and **\<stepper-item><sup>5+</sup>**.|
| flex-grow | number | 0 | How much a child component will grow. The value specifies allocation of the remaining space on the main axis of the parent component. Size of available space = Container size - Total size of all child components. Value **0** indicates that the child component does not grow.<br>This style takes effect only when the container is any of the following components: **\<div>**, **\<list-item>**, **\<tabs>**, **\<refresh>**, and **\<stepper-item><sup>5+</sup>**.|
| flex-shrink | number | 1 | How much a child component will shrink. The shrink occurs only when the sum of default child component widths is greater than that of the parent component. Value **0** indicates that the child component does not shrink.<br>This style takes effect only when the container is any of the following components: **\<div>**, **\<list-item>**, **\<tabs>**, **\<refresh>**, and **\<stepper-item><sup>5+</sup>**.|
| flex-basis | &lt;length&gt; | - | Initial length of the flex item on the main axis.<br>This style takes effect only when the container is any of the following components: **\<div>**, **\<list-item>**, **\<tabs>**, **\<refresh>**, and **\<stepper-item><sup>5+</sup>**.|
| align-self<sup>6+</sup> | string | - | Alignment mode on the cross axis of the parent element. This style overwrites the align-items style of the parent element. The align-items style is used only in the div and list styles of the parent container. Available values are as follows:<br>- **stretch**: Items are stretched to the same height or width as the container in the cross axis direction.<br>- **flex-start**: Items are aligned to the start of the cross axis.<br>- **flex-end**: Items are aligned to the end of the cross axis.<br>- **center**: Items are aligned in the center of the cross axis.<br>- **baseline**: Items are aligned on the peracross axis.|
| position | string | relative | Positioning type of an element. Dynamic changes are not supported.<br>- **fixed**: The element is positioned related to the browser window.<br>- **absolute**: The element is positioned absolutely to its parent element. The setting takes effect only when the parent component is **\<div>** or **\<stack>**.<br>- **relative**: The element is positioned relative to its normal position.|
| [left \| top \| right \| bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>6+</sup> | - | **left &#x7C; top &#x7C; right &#x7C; bottom** must be used together with **position** to determine the offset of an element.<br/>- The **left** attribute specifies the left edge position of the element. This attribute defines the offset between the left edge of the margin area of a positioned element and left edge of its containing block.<br/>- The **top** attribute specifies the top edge position of the element. This attribute defines the offset between the top edge of a positioned element and that of a block included in the element.<br/>- The **right** attribute specifies the right edge position of the element. This attribute defines the offset between the right edge of a positioned element and that of a block included in the element.<br/>- The **bottom** attribute specifies the bottom edge position of the element. This attribute defines the offset between the bottom edge of a positioned element and that of a block included in the element. |
| [start \| end]<sup>6+</sup> | &lt;length&gt; \| &lt;percentage&gt; | - | **start &#x7C; end** must be used together with **position** to determine the offset of an element.<br/>- The **start** attribute specifies the start edge position of the element. This attribute defines the offset between the start edge of a positioned element and that of a block included in the element.<br/>- The **end** attribute specifies the end edge position of the element. This attribute defines the offset between the end edge of a positioned element and that of a block included in the element. |
| align-self<sup>6+</sup> | string | - | How items are aligned along the main axis of the container. The setting overwrites the **align-items** setting of the container and is valid only when the container is **\<div>** or **\<list>**. 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**: Items are packed toward the baseline of the cross axis.|
| position | string | relative | Positioning type of an element. Dynamic changes are not supported.<br>- **fixed**: The element is positioned relative to the entire UI.<br>- **absolute**: The element is positioned relative to the container. The setting is valid only when the container is **\<div>** or **\<stack>**.<br>- **relative**: The element is positioned relative to its normal position.|
| [left \| top \| right \| bottom] | &lt;length&gt; \| &lt;percentage&gt;<sup>6+</sup> | - | Edge of the element. This style must be used together with **position** to determine the offset of an element.<br>- **left**: left edge position of the element. This attribute defines the offset between the left edge of the margin area of a positioned element and left edge of its containing block.<br>- **top**: top edge position of the element. This attribute defines the offset between the top edge of a positioned element and that of a block included in the element.<br>- **right**: right edge position of the element. This attribute defines the offset between the right edge of a positioned element and that of a block included in the element.<br>- **bottom**: bottom edge position of the element. This attribute defines the offset between the bottom edge of a positioned element and that of a block included in the element. |
| [start \| end]<sup>6+</sup> | &lt;length&gt; \| &lt;percentage&gt; | - | start \| end must be used together with **position** to determine the offset of an element.<br>- **start**: start edge position of the element. This attribute defines the offset between the start edge of a positioned element and that of a block included in the element.<br>- **end**: end edge position of the element. This attribute defines the offset between the end edge of a positioned element and that of a block included in the element.|
| z-index<sup>6+</sup> | number | - | Rendering sequence of child nodes under the same parent node. A child node with a larger value will be rendered later.<br>z-index does not support auto, and other styles such as opacity do not affect the rendering sequence of z-index.|
| image-fill<sup>6+</sup> | &lt;color&gt; | - | Fill color for SVG images. The following components are supported: **button** (icon attribute), **piece** (icon attribute), **search** (icon attribute), **input** (headericon attribute), **textarea** (headericon attribute), **image** (src attribute), and **toolbar-item** (icon attribute)<br>The **fill** color value in the SVG image file is replaced with the value of **image-fill** during rendering, and is valid only for the fill attribute that is declared in the SVG image.|
| clip-path<sup>6+</sup> | [ &lt;geometry-box&gt; \| &lt;basic-shape&gt; ] \| none | - | Clip area of a component. Only the content within this area is displayed.<br>**\<geometry-box>**: applicable scope of the clip area's width and height. The default value is **border-box**. Available values are as follows:<br>- **margin-box**: The width and height includes the margin.<br>- **border-box**: The width and height includes the border.<br>- **padding-box**: The width and height includes the padding.<br>- **content-box**: The width and height does not include any margin, border, or padding.<br>**\<basic-shape>**: shape of the clip area. Available values include:<br>- **inset**, in the format of inset( \<percentage>{1,4} [ round \<'border-radius'> ]? ).<br>- **circle**, in the format of circle( [ \<percentage> ]? [ at &lt;percentage&gt; &lt;percentage&gt; ]? ).<br>- **ellipse**, in the format of ellipse( [ \<percentage>{2} ]? [ at &lt;percentage&gt; &lt;percentage&gt; ]? ).<br>- **polygon**, in the format of polygon( [ \<percentage> \<percentage> ]\# ).<br>- **path**, in the format of path( \<string> ).|
| image-fill<sup>6+</sup> | &lt;color&gt; | - | Fill color for SVG images. The following components are supported: **\<button>** (**icon** attribute), **\<piece>** (**icon** attribute), **\<search>** (**icon** attribute), **\<input>** (**headericon** attribute), **\<textarea>** (**headericon** attribute), **\<image** (**src** attribute), and **\<toolbar-item>** (**icon** attribute)<br>The **fill** color value in the SVG image file is replaced with the value of **image-fill** during rendering, and is valid only for the fill attribute that is declared in the SVG image.|
| clip-path<sup>6+</sup> | [ &lt;geometry-box&gt; \| &lt;basic-shape&gt; ] \| none | - | Clip area of a component. Only the content within this area is displayed.<br>**\<geometry-box>**: applicable scope of the clip area's width and height. The default value is **border-box**. Available values are as follows:<br>- **margin-box**: The width and height includes the margin.<br>- **border-box**: The width and height includes the border.<br>- **padding-box**: The width and height includes the padding.<br>- **content-box**: The width and height does not include any margin, border, or padding.<br>**\<basic-shape>**: shape of the clip area. Available values include:<br>- **inset**, in the format of inset( &lt;percentage&gt;{1,4} [ round &lt;'border-radius'&gt; ]? ).<br>- **circle**, in the format of circle( [ &lt;percentage&gt; ]? [ at &lt;percentage&gt; &lt;percentage&gt; ]? ).<br>- **ellipse**, in the format of ellipse( [ &lt;percentage&gt;{2} ]? [ at &lt;percentage&gt; &lt;percentage&gt; ]? ).<br>- **polygon**, in the format of polygon( [ &lt;percentage&gt; &lt;percentage&gt; ]\# ).<br>- **path**, in the format of path( &lt;string&gt; ). |
| mask-image<sup>6+</sup> | - &lt;linear-gradient&gt;<br>- string | - | Image used for the mask of a component:<br>Gradient color mask, for example:<br>linear-gradient(to left, black, white)<br>Solid color mask, for example:<br>linear-gradient(to right, grey , grey)<br>Mask filled by a local SVG image, for example, **url(common/mask.svg)**|
| mask-size<sup>6+</sup> | - string<br>- &lt;length&gt;&lt;length&gt;<br>- &lt;percentage&gt; &lt;percentage&gt; | auto | Display size of the mask image. The setting is valid only when **mask-image** is set to an image source.<br>The **string** values are as follows:<br>- **contain**: Expands the image to the maximum size so that its height and width are fully applicable to the content area.<br>- **cover**: Extends the image to a large enough size so that it completely covers the background area. Some parts of the image may not be displayed in the background area.<br>- **auto**: Retains the original aspect ratio of the image.<br>The two **\<length>** values are as follows: The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.<br>The two **\<percentage>** values indicate the image size in relative to the original image size. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default. |
| mask-position<sup>6+</sup> | - string string<br>- &lt;length&gt; &lt;length&gt;<br>- &lt;percentage&gt; &lt;percentage&gt; | 0px 0px | Display position of the mask image. The setting is valid only when **mask-image** is set to an image source. Using keywords: If only one keyword is specified, the other value is **center** by default. The two values define the horizontal position and vertical position, respectively.<br>The **string** values are as follows:<br>- **left**: leftmost in the horizontal direction.<br>- **right**: rightmost in the horizontal direction.<br>- **top**: top in the vertical direction.<br>- **bottom**: bottom in the vertical direction.<br>- **center**: center position.<br>Using **\<length>**: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is **0 0**. The unit is pixel. If only one value is specified, the other one is **50%**.<br>Using **\<percentage>**: The first value indicates the horizontal position, and the second value indicates the vertical position. **0% 0%** indicates the upper left corner. **100% 100%** indicates the lower right corner. If only one value is specified, the other one is **50%**.<br>Using both **\<percentage>** and **\<length>**. |
| mask-size<sup>6+</sup> | - string<br>- &lt;length&gt;&lt;length&gt;<br>- &lt;percentage&gt; &lt;percentage&gt; | auto | Display size of the mask image. The setting is valid only when **mask-image** is set to an image source.<br>Values of the **string** type:<br>- **contain**: extends the image to the maximum size so that its height and width are fully applicable to the content area.<br>**cover**: extends the background image to a large enough size so that it completely covers the background area. Some parts of the image may not be displayed in the background area.<br>- **auto**: retains the original aspect ratio of the image.<br>Values of the **\<length>** type: The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.<br>Values of the **\<percentage>** type indicate the image size relative to the original image size. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.|
| mask-position<sup>6+</sup> | - string string<br>- &lt;length&gt; &lt;length&gt;<br>- &lt;percentage&gt; &lt;percentage&gt; | 0px 0px | Display position of the mask image. The setting is valid only when **mask-image** is set to an image source. Values of the **string** type: If only one value is specified, the other value is **center** by default. The two values define the horizontal position and vertical position, respectively.<br>Values of the **string** type:<br>- **left**: leftmost in the horizontal direction.<br>- **right**: rightmost in the horizontal direction.<br>- **top**: top in the vertical direction.<br>- **bottom**: bottom in the vertical direction.<br>- **center**: center position.<br>Values of the **\<length>** type: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is 0 0 in px (**0px 0px**). If only one value is specified, the other one is **50%**.<br>Values of the **\<percentage>** type: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is 0% 0%. For the lower right corner, the value is **100% 100%**. If only one value is specified, the other one is **50%**.<br>Values of the **\<percentage>** type and **\<length>** type can be used together. |
| border-image-source<sup>7+</sup> | string | - | Border image of the specified element.<br>Example:<br>border-image-source: url("/common/images/border.png") |
| border-image-slice<sup>7+</sup> | &lt;length&gt; \| &lt;percentage&gt; | 0 | Padding of the image.<br>The attribute can have one to four values:<br>If you set only one value, it specifies the padding for four sides.<br>If you set two values, the first value specifies the top and bottom padding, and the second value specifies the left and right padding.<br>If you set three values, the first value specifies the top padding, the second value specifies the left and right padding, and the third value specifies the bottom padding.<br>If you set four values, they respectively specify the padding for top, right, bottom, and left sides (in clockwise order).|
| border-image-width<sup>7+</sup> | &lt;length&gt; \| &lt;percentage&gt; | 0 | Width of the border image.<br>If you set only one value, it specifies the width for four sides.<br>If you set two values, the first value specifies the top and bottom width, and the second value specifies the left and right width.<br>If you set three values, the first value specifies the top width, the second value specifies the left and right width, and the third value specifies the bottom width.<br>If you set four values, they respectively specify the width for top, right, bottom, and left sides (in clockwise order).|
| border-image-outset<sup>7+</sup> | &lt;length&gt; \| &lt;percentage&gt; | 0 | How far the border image can extend beyond the border box.<br>If you set only one value, it specifies the distance of the boarder image beyond the border on four sides.<br>If you set two values, the first value specifies the distance of the boarder image's top and bottom sides beyond the boarder, and the second value specifies the distance of the boarder image's left and right sides beyond the boarder.<br>If you set three values, the first value specifies the distance of the boarder image's top side beyond the boarder, the second value specifies the distance of the boarder image's left and right sides beyond the boarder, and the third value specifies the distance of the boarder image's bottom side beyond the boarder.<br>If you set four values, they respectively specify the distance of the boarder image's top, right, bottom, and left sides beyond the boarder (in clockwise order).|
| border-image-repeat<sup>7+</sup> | string | stretch | How the border image fills the border box.<br>**stretch**: stretches the image to fill the border box.<br>**repeat**: tiles the image to fill the border box.<br>**round**: tiles the image to fill the border box. When the image cannot be tiled for an integer number of times, it can be scaled based on the site requirements. |
| border-image<sup>7+</sup> | string | - | Shorthand attribute. The options are as follows:<br>- Attributes of the image border. The parameters include **border-image-source**, **border-image-slice**, **border-image-width**, **border-image-outset**, and **border-image-repeat**, respectively meaning the padding, width of the border image, how far the border image can extend beyond the border box, and how the border image fills the border box. The default values are used if the parameters are not set.<br>- Gradient color border.<br> Example:<br> border-image: linear-gradient(red, yellow) 10px |
| border-image-outset<sup>7+</sup> | &lt;length&gt; \| &lt;percentage&gt; | 0 | How far the border image can extend beyond the border box.<br>If you set only one value, it specifies the distance of the boarder image beyond the border on four sides.<br>If you set two values, the first value specifies the distance of the boarder image's top and bottom sides beyond the boarder, and the second value specifies the distance of the boarder image's left and right sides beyond the boarder.<br>When three values are specified, the first value specifies the distance between the upper border image and the border, the second value specifies the distance between the left and right border images and the border, and the third value specifies the distance between the lower border image and the border.<br>If you set four values, they respectively specify the distance of the boarder image's top, right, bottom, and left sides beyond the boarder (in clockwise order).|
| border-image-repeat<sup>7+</sup> | string | stretch | How the border image fills the border box.<br>**stretch**: Stretches the image to fill the border box<br>**repeat**: Tiles the image to fill the border box.<br>**round**: Tiles the image to fill the border box. When the image cannot be tiled for an integer number of times, it can be scaled based on the site requirements.<br>|
| border-image<sup>7+</sup> | string | - | Shorthand attribute. The options are as follows:<br>- Attributes of the image border. The parameters include **border-image-source**, **border-image-slice**, **border-image-width**, **border-image-outset**, and **border-image-repeat**, which respectively indicate the padding, width of the border image, how far the border image can extend beyond the border box, and how the border image fills the border box. The default values are used if the parameters are not set.<br>- Gradient color border.<br> Example:<br> border-image: linear-gradient(red, yellow) 10px |
| box-sizing<sup>9+</sup> | string | border-box | Border type of the component.<br>**content-box**: standard box. Its width and height contain only the width and height of the content, and does not include the border and padding.<br>**border-box**: The width and height include the content, border, and padding, that is, the actual width of the component content area = width - (border + padding).|
......@@ -77,10 +77,10 @@ You can set universal styles for components in the **style** attribute or **.css
```html
<div class="container" onswipe="touchMove">
<text style="margin: 10px; box-sizing: content-box; width: 300px;height: 300px; border: blue; border-width: 20px;">
<text style="margin: 10px; box-sizing: content-box; width: 300px;height: 300px; border-color: blue; border-width: 20px;">
contentBox
</text>
<text style="margin: 10px; box-sizing: border-box; width: 300px;height: 300px;border: blue; border-width: 20px;">
<text style="margin: 10px; box-sizing: border-box; width: 300px;height: 300px;border-color: blue; border-width: 20px;">
borderBox
</text>
</div>
......
......@@ -11,14 +11,14 @@
| Name | Type | Default Value | Description |
| ------- | ------ | ---- | ---------------------------------------- |
| shareid | string | - | Used for the transition of shared elements, which takes effect only when this attribute is set. **\<list-item>**, **\<image>**, **\<text>**, **\<button>**, and **\<label>** components are supported for the transition of shared elements. |
| shareid | string | - | Used for the transition of shared elements, which takes effect only when this attribute is set. **\<list-item>**, **\<image>**, **\<text>**, **\<button>**, and **\<label>** components are supported for the transition of shared elements.|
### Styles
| Name | Type | Default Value | Description |
| --------------------------------- | ------ | -------- | ---------------------------------------- |
| shared-transition-effect | string | exchange | Entry style of a shared element during transition.<br>-&nbsp;**exchange** (default): The source page element is moved to the position of the target page element and is zoomed in or out properly.<br>-&nbsp;**static**: The position of the target page element remains unchanged. You can configure the opacity animation. Currently, only the static effect configured on the target page takes effect.|
| shared-transition-effect | string | exchange | Entry style of a shared element during transition.<br>- **exchange** (default): The source page element is moved to the position of the target page element and is zoomed in or out properly.<br>- **static**: The position of the target page element remains unchanged. You can configure the opacity animation. Currently, only the static effect configured on the target page takes effect.|
| shared-transition-name | string | - | During the transition, the style configured on the target page takes effect preferentially. This style is used to configure the animation effect of shared elements. The animation effect is an animation sequence defined by **@keyframes** supporting transform and opacity animations. If the effect of shared elements conflicts with the custom animation, the latter is used.|
| shared-transition-timing-function | string | friction | During the transition, the style configured on the target page takes effect preferentially. This style defines the difference curve during the transition of shared elements. If it is not configured, the friction curve is used.|
......@@ -52,7 +52,7 @@ In the example below, where **PageA** jumps to **PageB**, the shared element is
<image src="item.jpg" shareid="shareImage" onclick="jump" class="shared-transition-style"></image>
</list-item>
<list-item>
<text onclick="jump">Click on picture to Jump to the details</text>
<text onclick="jump">Click on picture to jump to the details</text>
</list-item>
</list>
</div>
......@@ -60,12 +60,12 @@ In the example below, where **PageA** jumps to **PageB**, the shared element is
```js
// xxx.js
import router from '@system.router';
import router from '@ohos.router';
export default {
jump() {
router.push({
// The path must be the same as that in the config.json file.
uri: 'pages/detailpage',
url: 'pages/detailpage',
});
},
}
......@@ -93,7 +93,7 @@ export default {
```js
// xxx.js
import router from '@system.router';
import router from '@ohos.router';
export default {
jumpBack() {
router.back();
......@@ -117,7 +117,6 @@ export default {
## Widget Transition
> **NOTE**
>
> Widget transitions are not available when other transitions (including shared element transitions and custom transitions) are used.
......@@ -125,7 +124,7 @@ export default {
| Name | Type | Default Value | Description |
| ----------------- | ------ | ---- | ---------------------------------------- |
| transition-effect | string | - | Whether a component on the current page displays the transition effect during a widget transition. Available values are as follows:<br>-&nbsp;**unfold**: The component will move upwards by one widget height if the component is located above the widget tapped by the user, or move downwards by one widget height if the component is located below the widget.<br>-&nbsp;**none**: No transition effect is displayed. |
| transition-effect | string | - | Whether a component on the current page displays the transition effect during a widget transition. Available values are as follows:<br>- **unfold**: The component will move upwards by one widget height if the component is located above the widget tapped by the user, or move downwards by one widget height if the component is located below the widget.<br>- **none**: No transition effect is displayed.|
### Example
......@@ -140,7 +139,7 @@ The **source_page** has a title area on the top and a widget list. Users can tap
<text style="font-size: 23px; margin-bottom: 20px" >MAIN TITLE</text>
</div>
<list style="width:340px;height:600px;flex-direction:column;justify-content:center;align-items:center">
<list-item type="listItem" class="item" card="true" for="list" id="{{$item.id}}" onclick="jumpPage({{$item.id}}, {{$item.uri}})">
<list-item type="listItem" class="item" card="true" for="list" id="{{$item.id}}" onclick="jumpPage({{$item.id}}, {{$item.url}})">
<text style="margin-left: 10px; font-size: 23px;">{{$item.title}}</text>
</list-item>
</list>
......@@ -149,19 +148,19 @@ The **source_page** has a title area on the top and a widget list. Users can tap
```js
// xxx.js
import router from '@system.router'
import router from '@ohos.router'
export default {
data: { list: [] },
onInit() {
for(var i = 0; i < 10; i++) {
var item = { uri: "pages/card_transition/target_page/index",
var item = { url: "pages/card_transition/target_page/index",
title: "this is title" + i, id: "item_" + i }
this.list.push(item);
}
},
jumpPage(id, uri) {
jumpPage(id, url) {
var cardId = this.$element(id).ref;
router.push({ uri: uri, params : { ref : cardId } });
router.push({ url: url, params : { ref : cardId } });
}
}
```
......@@ -169,6 +168,8 @@ export default {
```css
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
background-color: #ABDAFF;
......@@ -199,6 +200,8 @@ export default {
```css
/* xxx.css */
.container {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
background-color: #EBFFD7;
......@@ -223,7 +226,7 @@ export default {
| -------------------------- | ------ | ------------- | ---------------------------------------- |
| transition-enter | string | - | Works with **@keyframes** and supports transform and opacity animations. For details, see [Attributes available for the @keyframes rule](../arkui-js/js-components-common-animation.md).|
| transition-exit | string | - | Works with **@keyframes** and supports transform and opacity animations. For details, see [Attributes available for the @keyframes rule](../arkui-js/js-components-common-animation.md).|
| transition-duration | string | Follows the default page transition time of the device | The unit can be s or ms. The default unit is ms. If no value is specified, the default value is used. |
| transition-duration | string | Follows the default page transition time of the device| The unit can be s|or ms. The default unit is ms. If no value is specified, the default value is used.|
| transition-timing-function | string | friction | Speed curve of the transition animation, which makes the animation more fluent. For details, see the description of **animation-timing-function **in [Animation Styles](../arkui-js/js-components-common-animation.md).|
......@@ -255,16 +258,16 @@ export default {
</div>
```
```css
```js
// xxx.js
import router from '@system.router';
import router from '@ohos.router';
export default {
data: {
},
jump() {
router.push({
uri:'pages/transition2/transition2'
url:'pages/transition2/transition2'
})
}
}
......@@ -321,12 +324,12 @@ export default {
<div class="container">
<text>transition</text>
<div class="move_page" onclick="jumpBack"></div>
</div
</div>
```
```js
// xxx.js
import router from '@system.router';
import router from '@ohos.router';
export default {
data: {
......
......@@ -25,11 +25,11 @@ This component supports only one child component.
In addition to the [universal attributes](js-components-common-attributes.md), the following attributes are supported.
| Name | Type | Default Value | Mandatory | Description |
| ------------------ | ----------- | -------- | ---- | ---------------------------------------- |
| Name | Type | Default Value | Mandatory| Description |
| ------------------ | ----------- | -------- | ---- | ------------------------------------------------------------ |
| placement | string | rightTop | No | Position of a number or dot badge. Available values are as follows:<br>- **right**: on the right border of the component.<br>- **rightTop**: in the upper right corner of the component border.<br>- **left**: on the left border of the component.|
| count | number | 0 | No | Number of notifications displayed via the badge. The default value is **0**. If the number of notifications is greater than 0, the badge changes from a dot to the number. If this attribute is not set or the value is less than or equal to 0, the badge is a dot.<br>When the **count** value is greater than the **maxcount** value, *maxcount***+** is displayed. The largest integer value supported for **count** is **2147483647**.|
| visible | boolean | false | No | Whether to display the badge. The value **true** means that the badge shows up when a new notification is received. To use a number badge, set the **count** attribute.|
| count | number | 0 | No | Number of notifications displayed via the badge. If the value is 0 (default value), the badge is not displayed. If the value is greater than 0, the badge is a number badge.<br>When the **count** value is greater than the **maxcount** value, *maxcount***+** is displayed. The largest integer value supported for **count** is **2147483647**.|
| visible | boolean | false | No | Whether to display the badge. The value **true** means that the badge shows up when a new notification is received. To use a number badge, also set the **count** attribute.|
| maxcount | number | 99 | No | Maximum number of notifications. When the number of new notifications exceeds the value of this attribute, *maxcount***+** is displayed, for example, **99+**.<br>The largest integer value supported for **maxcount** is **2147483647**.|
| config | BadgeConfig | - | No | Configuration of the badge. |
| label<sup>6+</sup> | string | - | No | Text of the new notification displayed via the badge.<br>When this attribute is set, attributes **count** and **maxcount** do not take effect.|
......@@ -110,4 +110,4 @@ export default {
}
```
![figures1](figures/figures1.png)
![en-us_image_000000117726526811](figures/en-us_image_000000117726526811.png)
......@@ -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,7 +247,7 @@ 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>
```
......@@ -255,8 +256,10 @@ In addition to the [universal methods](js-components-common-methods.md), the fol
/* xxx.css */
.container {
flex-direction: column;
width: 100%;
height: 100%;
}
.content{
.content {
width: 200px;
height: 200px;
background-color: red;
......@@ -265,7 +268,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,
......@@ -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;
}
```
......
......@@ -72,7 +72,7 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md
| scrollend | - | Triggered when the list stops scrolling. |
| scrolltouchup | - | Triggered when the list continues scrolling after the user lifts their fingers. |
| requestitem | - | Triggered for a request to create a list-item.<br>This event is triggered when the number of cached list-items outside the visible area is less than the value of **cachedcount** during long list loading with delay.|
| rotate<sup>7+</sup> | { rotateValue: number } | Triggered to indicate the incremental value of the rotation angle of the watch crown. This parameter is only supported by wearables. |
| rotation<sup>7+</sup> | { rotateValue: number } | Triggered to indicate the incremental value of the rotation angle of the watch crown. This parameter is only supported by wearables. |
## Methods
......@@ -112,22 +112,6 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
</list>
</div>
```
```js
// index.js
export default {
data: {
todolist: [{
title: 'Prepare for the interview',
date: '2021-12-31 10:00:00',
}, {
title: 'Watch the movie',
date: '2021-12-31 20:00:00',
}],
},
}
```
```css
/* index.css */
.container {
......@@ -153,4 +137,21 @@ export default {
}
```
```js
// index.js
export default {
data: {
todolist: [{
title: 'Prepare for the interview',
date: '2021-12-31 10:00:00'
}, {
title: 'Watch the movie',
date: '2021-12-31 20:00:00'
}],
},
}
```
![en-us_image_0000001185033226](figures/en-us_image_0000001185033226.png)
......@@ -92,7 +92,7 @@ The following methods are supported.
<panel id="simplepanel" type="foldable" mode="half" onsizechange="changeMode" miniheight="200px">
<div class="panel-div">
<div class="inner-txt">
<text class="txt">Simple panel in {{modeFlag}} mode</text>
<text class="txt">Simple panel in {{ modeFlag }} mode</text>
</div>
<div class="inner-btn">
<button type="capsule" value="Close" onclick="closePanel"></button>
......@@ -109,6 +109,7 @@ The following methods are supported.
justify-content: center;
align-items: center;
}
.btn-div {
width: 100%;
height: 200px;
......@@ -116,16 +117,19 @@ The following methods are supported.
align-items: center;
justify-content: center;
}
.txt {
color: #000000;
font-weight: bold;
font-size: 39px;
}
.panel-div {
width: 100%;
flex-direction: column;
align-items: center;
}
.inner-txt {
width: 100%;
height: 160px;
......@@ -133,6 +137,7 @@ The following methods are supported.
align-items: center;
justify-content: center;
}
.inner-btn {
width: 100%;
height: 120px;
......
......@@ -4,7 +4,7 @@
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
Bubble indication. The **\<popup>** component is used to display a pop-up to offer instructions after a user clicks a bound control.
The **\<popup>** component is used to display a pop-up to offer instructions after a user clicks a bound component.
## Required Permissions
......@@ -116,7 +116,7 @@ export default {
visibilitychange(e) {
prompt.showToast({
message: 'visibility change visibility: ' + e.visibility,
duration: 3000,
duration: 3000
});
},
showpopup() {
......@@ -124,7 +124,7 @@ export default {
},
hidepopup() {
this.$element("popup").hide();
},
}
}
```
......
......@@ -4,7 +4,7 @@
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
The **<Refresh\>** component is used to refresh a page through a pull-down gesture.
The **<refresh\>** component is used to refresh a page through a pull-down gesture.
## Required Permissions
......@@ -22,7 +22,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| offset | &lt;length&gt; | - | No| Distance to the top of the parent component from the **<Refresh\>** component that comes to rest after a successful pull-down gesture.|
| offset | &lt;length&gt; | - | No| Distance to the top of the parent component from the **<refresh\>** component that comes to rest after a successful pull-down gesture.|
| refreshing | boolean | false | No| Whether the **\<refresh>** component is being used for refreshing.|
| type | string | auto | No| Dynamic effect when the component is refreshed. Two options are available and cannot be modified dynamically.<br>- **auto**: default effect. When the list is pulled to the top, the list does not move. When the list is pulled to the bottom, a circle is displayed.<br>- **pulldown**: When the list is pulled to the top, users can continue to pull down to trigger a refresh. The rebound effect will appear after the refresh. If the child component contains a list, set **scrolleffect** of the list to **no** to prevent drop-down effect conflicts.|
| lasttime | boolean | false | No| Whether to display the last update time. The character string format is **last update time: XXXX**, where **XXXX** is displayed based on the certain time and date formats and cannot be dynamically modified. (It is recommended that this attribute be used when **type** is set to **pulldown**. The fixed distance is at the bottom of the content drop-down area. Pay attention to the **offset** attribute setting to prevent overlapping.)|
......@@ -36,8 +36,8 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| background-color | &lt;color&gt; | white | No| Background color of the **\<refresh>** component.|
| progress-color | &lt;color&gt; | black | No| Loading color of the **\<refresh>** component.|
| background-color | &lt;color&gt; | white<br>| No| Background color of the **\<refresh>** component.|
| progress-color | &lt;color&gt; | black<br>| No| Color of the loading icon of the **\<refresh>** component.|
## Events
......@@ -107,7 +107,7 @@ The [universal methods](../arkui-js/js-components-common-methods.md) are not sup
```js
// xxx.js
import prompt from '@system.prompt';
import promptAction from '@ohos.promptAction';
export default {
data: {
list:[],
......@@ -121,7 +121,7 @@ export default {
}
},
refresh: function (e) {
prompt.showToast({
promptAction.showToast({
message: 'Refreshing...'
})
var that = this;
......@@ -130,7 +130,7 @@ export default {
that.fresh = false;
var addItem ='Refresh element';
that.list.unshift(addItem);
prompt.showToast({
promptAction.showToast({
message: 'Refreshed.'
})
}, 2000)
......
......@@ -27,7 +27,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| Name | Type | Default Value | Description |
| ----- | ------ | ---- | ------------------------------ |
| index | number | - | Index of the **\<stepper-item>** child component that is currently displayed.|
| index | number | 0 | Index of the **\<stepper-item>** child component to display. By default, the first one is displayed.|
## Styles
......@@ -46,10 +46,10 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md
| Name | Parameter | Description |
| ------ | ---------------------------------------- | ---------------------------------------- |
| finish | - | Triggered when the last step on the navigator is complete. |
| skip | - | Triggered when users click the skip button, which works only if you have called **setNextButtonStatus** method to allow users to skip all steps.|
| skip | - | Triggered when users click the skip button to skip steps.|
| change | { prevIndex: prevIndex, index: index} | Triggered when users click the left or right (text) button of the step navigator to switch between steps. **prevIndex** indicates the index of the previous step, and **index** indicates that of the current step.|
| next | { index: index, pendingIndex: pendingIndex } | Triggered when users click the next (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **\<stepper-item>** child component as the next step to go.|
| back | { index: index, pendingIndex: pendingIndex } | Triggered when users click the previous (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in Object:{ **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **\<stepper-item>** child component as the previous step.|
| next | { index: index, pendingIndex: pendingIndex } | Triggered when users click the next (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **<stepper-item>** child component as the next step to go.|
| back | { index: index, pendingIndex: pendingIndex } | Triggered when users click the previous (text) button. **index** indicates the index of the current step, and **pendingIndex** indicates that of the step to go. The return value is in Object:{ **{pendingIndex:*** pendingIndex***}** format. You can use **pendingIndex** to specify a **<stepper-item>** child component as the previous step.|
## Methods
......@@ -58,32 +58,33 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
| Name | Parameter | Description |
| ------------------- | ---------------------------------------- | ---------------------------------------- |
| setNextButtonStatus | { status: string, label: label } | Sets the status of the next (text) button in this step navigator. Available **status** values are as follows:<br>- **normal**: The next button is displayed normally and can navigate users to the next step when it is clicked.<br>- **disabled**: The next button is grayed out and unavailable.<br>- **waiting**: The next button is not displayed, and a process bar is displayed instead.<br>- **skip**: The skip button is displayed to allow users to skip all remaining steps.|
| setNextButtonStatus | { status: string, label: label } | Sets the text and status of the next button in the step navigator. **label** indicates the button text, and **status** indicates the button status. Available **status** values are as follows:<br>- **normal**: The next button is displayed normally and can navigate users to the next step when it is clicked.<br>- **disabled**: The next button is grayed out and unavailable.<br>- **waiting**: The next button is not displayed, and a process bar is displayed instead.<br>- **skip**: The skip button is displayed to allow users to skip all remaining steps.|
## Example
```html
<!-- xxx.hml -->
<div class = "container">
<stepper class="stepper" id="mystepper" index="0" onnext="nextclick" onback="backclick">
<stepper-item class ="stepperItem" label="{{label_1}}">
<div class = "stepperItemContent" >
<text class = "text">First screen</text>
<div class="container">
<stepper class="stepper" id="mystepper" onnext="nextclick" onback="backclick" onchange="statuschange"
onfinish="finish" onskip="skip" style="height : 100%;">
<stepper-item class="stepper-item" label="{{ label_1 }}">
<div class="item">
<text>Page One</text>
<button type="capsule" class="button" value="change status" onclick="setRightButton"></button>
</div>
<button type="capsule" class ="button" value="setRightButtonStatus" onclick="setRightButton"></button>
</stepper-item>
<stepper-item class ="stepperItem" label="{{label_2}}">
<div class = "stepperItemContent" >
<text class = "text">Second screen</text>
<stepper-item class="stepper-item" label="{{ label_2 }}">
<div class="item">
<text>Page Two</text>
<button type="capsule" class="button" value="change status" onclick="setRightButton"></button>
</div>
<button type="capsule" class ="button" value="setRightButtonStatus" onclick="setRightButton"></button>
</stepper-item>
<stepper-item class ="stepperItem" label="{{label_3}}">
<div class = "stepperItemContent" >
<text class = "text">Third screen</text>
<stepper-item class="stepper-item" label="{{ label_3 }}">
<div class="item">
<text>Page Three</text>
<button type="capsule" class="button" value="change status" onclick="setRightButton"></button>
</div>
<button type="capsule" class ="button" value="setRightButtonStatus" onclick="setRightButton"></button>
</stepper-item>
</stepper>
</div>
......@@ -92,30 +93,48 @@ In addition to the [universal methods](../arkui-js/js-components-common-methods.
```css
/* xxx.css */
.container {
margin-top: 20px;
flex-direction: column;
align-items: center;
height: 300px;
height: 100%;
width: 100%;
background-color: #f7f7f7;
}
.stepper{
width: 100%;
height: 100%;
}
.stepperItem {
.stepper-item {
width: 100%;
height: 100%;
flex-direction: column;
align-items: center;
}
.stepperItemContent {
color: #0000ff;
font-size: 50px;
justify-content: center;
.item{
width: 90%;
height: 86%;
margin-top: 80px;
background-color: white;
border-radius: 60px;
flex-direction: column;
align-items: center;
padding-top: 160px;
}
text {
font-size: 78px;
color: #182431;
opacity: 0.4;
}
.button {
width: 60%;
margin-top: 30px;
width: 40%;
margin-top: 100px;
justify-content: center;
}
```
```js
// xxx.js
import prompt from '@system.prompt';
export default {
data: {
label_1:
......@@ -135,10 +154,12 @@ export default {
prevLabel: 'BACK',
nextLabel: 'NEXT',
status: 'normal'
},
}
},
setRightButton(e) {
this.$element('mystepper').setNextButtonStatus({status: 'skip', label: 'SKIP'});
this.$element('mystepper').setNextButtonStatus({
status: 'waiting', label: 'SKIP'
});
},
nextclick(e) {
var index = {
......@@ -152,7 +173,22 @@ export default {
}
return index;
},
statuschange(e) {
prompt.showToast({
message: 'Previous step index' + e.prevIndex + 'Current step index' + e.index
})
},
finish() {
prompt.showToast({
message:'Finished.'
})
},
skip() {
prompt.showToast({
message: 'Skip triggered'
})
}
}
```
![en-us_image_0000001127125114](figures/en-us_image_0000001127125114.gif)
![](figures/stepper.gif)
......@@ -4,7 +4,7 @@
>
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Swiper>** component provides a container that allows users to switch among child components using swipe gestures.
The **\<swiper>** component provides a container that allows users to switch among child components using swipe gestures.
## Required Permissions
......
......@@ -13,8 +13,7 @@ None
## Child Components
A **\<tabs>** component can wrap at most one **[\<tab-bar>](../arkui-js/js-components-container-tab-bar.md)** and at most one **[\<tab-content>](../arkui-js/js-components-container-tab-content.md)**.
Only [\<tab-bar>](../arkui-js/js-components-container-tab-bar.md) and [\<tab-content>](../arkui-js/js-components-container-tab-content.md) are supported.
## Attributes
......@@ -23,7 +22,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
| Name | Type | Default Value | Mandatory | Description |
| -------- | ------- | ----- | ---- | ---------------------------------------- |
| index | number | 0 | No | Index of the active tab. |
| vertical | boolean | false | No | Whether the tab is vertical. Available values are as follows:<br>- **false**: The **\<tab-bar>** and **\<tab-content>** are arranged vertically.<br>- **true**: The **\<tab-bar>** and **\<tab-content>** are arranged horizontally.|
| vertical | boolean | false | No | Whether the tab is vertical. Available values are as follows:<br>- **false**: The **\<tab-bar>** and **\<tab-content>** are arranged vertically.<br>- **true**: The **\<tab-bar>** and **\<tab-content>** are arranged horizontally. |
## Styles
......
# Dynamic Component Creation
You can dynamically add components with specified attributes and styles to pages.
> **NOTE**
>
> This API is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## createElement
createElement(tag: string): Element
Creates a component object.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------------ | ---- | ------- |
| tag | string | Yes | Component name.|
**Return value**
| Type | Description |
| ----------- | ------------- |
| Element | Component object corresponding to the value of **tag**.|
```js
let newImage = dom.createElement('image')
```
## setAttribute
setAttribute(name: string, value: string): void
Dynamically sets the attributes of this component.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------------ | ---- | ------- |
| name | string | Yes | Attribute name.|
| value | string | Yes | Attribute value.|
```js
newImage.setAttribute('src', 'common/testImage.jpg')
```
## setStyle
setStyle(name: string, value: string): boolean
Dynamically sets the style of this component.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------------ | ---- | ------- |
| name | string | Yes | Style name.|
| value | string | Yes | Style value.|
**Return value**
| Type | Description |
| ----------- | ------------- |
| boolean | Returns **true** if the setting is successful; returns **false** otherwise.|
```js
newImage.setStyle('width', '120px')
```
## addChild
addChild(child: Element): void
Adds a dynamically created component to the parent component.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------------ | ---- | ------- |
| child | Element | Yes | Component object.|
```js
newDiv.addChild(newImage)
```
## Example
```html
<!-- xxx.hml -->
<div class="container">
<div id="parentDiv" class="parent"></div>
<button onclick="appendDiv" class="btn">Dynamically create a <div> component.</button>
<button onclick="appendImage" class="btn">Dynamically create an <image> component and add it to the newly created <div> component.</button>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
align-items: center;
width: 100%;
}
.parent {
flex-direction: column;
}
.btn {
width: 70%;
height: 60px;
margin: 15px;
}
```
```js
// xxx.js
let newDiv = null
let newImage = null
export default {
appendDiv() {
let parent = this.$element('parentDiv')
newDiv = dom.createElement('div')
newDiv.setStyle('width', '150px')
newDiv.setStyle('height', '150px')
newDiv.setStyle('backgroundColor', '#AEEEEE')
newDiv.setStyle('marginTop', '15px')
parent.addChild(newDiv)
},
appendImage() {
newImage = dom.createElement('image')
newImage.setAttribute('src', 'common/testImage.jpg')
newImage.setStyle('width', '120px')
newImage.setStyle('height', '120px')
newDiv.addChild(newImage)
}
}
```
# Basic Usage
# Basic Usage of Custom Components
Custom components are existing components encapsulated based on service requirements. A custom component can be invoked multiple times in a project to improve the code readability. You can import a custom component to the host page through **element** as shown in the following code snippet:
Custom components are existing components encapsulated based on service requirements. A custom component can be invoked multiple times in a project to improve the code readability. You can introduce a custom component to the host page through **element** as shown in the following code snippet:
```html
<element name='comp' src='../../common/component/comp.hml'></element>
<div>
......@@ -8,8 +9,8 @@ Custom components are existing components encapsulated based on service requirem
</div>
```
The following is an example of using a custom component with **if-else**, which displays **comp1** when **showComp1** is set to **true** and displays **comp2** otherwise.
The following is an example of using a custom component with **if-else**:
```html
<element name='comp1' src='../../common/component/comp1/comp1.hml'></element>
<element name='comp2' src='../../common/component/comp2/comp2.hml'></element>
......@@ -19,18 +20,142 @@ The following is an example of using a custom component with **if-else**:
</div>
```
The **name** attribute indicates the custom component name (optional), which is case-insensitive and is in lowercase by default. The **src** attribute indicates the **.hml** file path (mandatory) of the custom component. If **name** is not set, the **.hml** file name is used as the component name by default.
## Custom Events
To bind an event to a custom child component, use the **(on|@)event-name="bindParentVmMethod"** syntax. **this.$emit('eventName', { params: 'passedParameters' })** is used in the child component to trigger the event and pass parameters to the parent component. The parent component then calls the **bindParentVmMethod** API and receives parameters passed by the child component.
> **NOTE**
>
> For child component events that are named in camel case, convert the names to kebab case when binding the events to the parent component. For example, use **\@children-event** in the parent component instead of **childrenEvent** used in the child component.
**Example 1 with parameters passed**
The following example describes how to define a child component **comp**:
```html
<!-- comp.hml -->
<div class="item">
<text class="text-style" onclick="childClicked">Click here to view the hidden text.</text>
<text class="text-style" if="{{showObj}}">hello world</text>
</div>
```
```css
/* comp.css */
.item {
width: 700px;
flex-direction: column;
height: 300px;
align-items: center;
margin-top: 100px;
}
.text-style {
font-weight: 500;
font-family: Courier;
font-size: 40px;
}
```
```js
// comp.js
export default {
data: {
showObj: false,
},
childClicked () {
this.$emit('eventType1');
this.showObj = !this.showObj;
},
}
```
The following example describes how to import **comp** to the parent component:
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/component/comp.hml'></element>
<div class="container">
<comp @event-type1="textClicked"></comp>
</div>
```
```css
/* xxx.css */
.container {
background-color: #f8f8ff;
flex: 1;
flex-direction: column;
align-content: center;
}
```
```js
// xxx.js
export default {
textClicked () {}
}
```
**Example 2 with no parameters passed**
The following example describes how to define a child component **comp**:
```html
<!-- comp.hml -->
<div class="item">
<text class="text-style" onclick="childClicked">Click here to view the hidden text.</text>
<text class="text-style" if="{{ showObj }}">hello world</text>
</div>
```
```js
// comp.js
export default {
childClicked () {
this.$emit('eventType1', { text: 'Receive the parameters from the child component.' });
this.showObj = !this.showObj;
},
}
```
In the following example, the child component passes the **text** parameter to the parent component, and the parent component obtains the parameter through **e.detail**:
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/comp/comp.hml'></element>
<div class="container">
<text>Parent component: {{text}}</text>
<comp @event-type1="textClicked"></comp>
</div>
```
```js
// xxx.js
export default {
data: {
text: 'Start'
},
textClicked (e) {
this.text = e.detail.text;
},
}
```
![EventParameters](figures/EventParameters.gif)
## Custom Component Data
- The **name** attribute indicates the custom component name (optional), which is case-insensitive and is in lowercase by default. The **src** attribute indicates the **.hml** file path (mandatory) of the custom component. If **name** is not set, the **.hml** file name is used as the component name by default.
- Event binding: Use **(on|@)***child1* syntax to bind a child component event to a custom component. In the child component, use **this.$emit('***child1***', {params:'***parameter to pass***'})** for event triggering and value transferring. In the parent component, call **bindParentVmMethod** method and receive the parameters passed from the child component.
> **NOTE**
>
> For child component events that are named in camel case, convert the names to kebab case when binding the events to the parent component. For example, use **\@children-event** instead of **childrenEvent**: **\@children-event="bindParentVmMethod"**.
In the JS file of a custom component, you can define, pass, and process data by declaring fields such as **data**, **props**, and **computed**. For details about how to use **props** and **computed**, see [Data Transfer and Processing](js-components-custom-props.md).
**Table 1** Objects
**Table 1** Custom component data
| Name | Type | Description |
| -------- | --------------- | ---------------------------------------- |
| data | Object/Function | Data model of the page. If the attribute is of the function type, the return value must be of the object type. The attribute name cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**).<br>Do not use this attribute and **private** or **public** at the same time.(Rich) |
| props | Array/Object | Used for communication between components. This attribute can be transferred to components via **\<tag xxxx='value'>**. A **props** name must be in lowercase and cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words (**for**, **if**, **show**, and **tid**). Currently, **props** does not support functions.|
| computed | Object | Used for pre-processing an object for reading and setting. The result is cached. The name cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words.|
| data | Object \| Function | Data model of the page. If the attribute is of the function type, the return value must be of the object type. The name cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words (**for**, **if**, **show**, and **tid**).<br>Do not use this attribute and **private** or **public** at the same time.|
| props | Array \| Object | Used for communication between components. This attribute can be passed to components through **\<tag xxxx='value'>**. A **props** name must be in lowercase and cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**) in the name. Currently, **props** does not support functions.|
| computed | Object | Used for pre-processing for reading and setting parameters. The result is cached. The name cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words.|
# Event Parameter
A child component can also pass parameters to an upper-layer component through the bound event. The following example describes how to pass parameters through the custom event:
```html
<!-- comp.hml -->
<div class="item">
<text class="text-style" onclick="childClicked">Click to View Hidden Text</text>
<text class="text-style" if="{{ showObj }}">hello world</text>
</div>
```
```js
// comp.js
export default {
childClicked () {
this.$emit('eventType1', {text: 'Received parameters from the child component.'});
this.showObj = !this.showObj;
},
}
```
In the following example, the child component passes the **text** parameter to the parent component, and the parent component obtains the parameter through **e.detail**:
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/comp/comp.hml'></element>
<div class="container">
<text>Parent component: {{text}}</text>
<comp @event-type1="textClicked"></comp>
</div>
```
```js
// xxx.js
export default {
data: {
text: 'Start'
},
textClicked (e) {
this.text = e.detail.text;
},
}
```
![EventParameters](figures/EventParameters.gif)
# Custom Events
The following example describes how to define a child component **comp**:
```html
<!-- comp.hml -->
<div class="item">
<text class="text-style" onclick="childClicked">Click here to view the hidden text.</text>
<text class="text-style" if="{{showObj}}">hello world</text>
</div>
```
```css
/* comp.css */
.item {
width: 700px;
flex-direction: column;
height: 300px;
align-items: center;
margin-top: 100px;
}
.text-style {
font-weight: 500;
font-family: Courier;
font-size: 40px;
}
```
```js
// comp.js
export default {
data: {
showObj: false,
},
childClicked () {
this.$emit('eventType1');
this.showObj = !this.showObj;
},
}
```
The following example describes how to introduce the child component:
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/component/comp.hml'></element>
<div class="container">
<comp @event-type1="textClicked"></comp>
</div>
```
```css
/* xxx.css */
.container {
background-color: #f8f8ff;
flex: 1;
flex-direction: column;
align-content: center;
}
```
```js
// xxx.js
export default {
textClicked () {},
}
```
For more information, see [Basic Usage](./js-components-custom-basic-usage.md).
......@@ -5,7 +5,7 @@
> This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version.
We provide a range of lifecycle callbacks for custom components, including **onInit**, **onAttached**, **onDetached**, **onLayoutReady**, **onDestroy**, **onShow**, and **onHide**. You can use these callbacks to manage the internal logic of your custom components. The following describes the times when the lifecycle callbacks are invoked.
A range of lifecycle callbacks are provided for custom components, including **onInit**, **onAttached**, **onDetached**, **onLayoutReady**, **onDestroy**, **onShow**, and **onHide**. You can use these callbacks to manage the internal logic of your custom components. The following describes the times when the lifecycle callbacks are invoked.
| Attribute | Type | Description | Invoked When |
......@@ -13,7 +13,7 @@ We provide a range of lifecycle callbacks for custom components, including **onI
| onInit | Function | Custom component initialization | The custom component is created. This callback is invoked once.|
| onAttached | Function | Custom component loading | The custom component is added to the **\<Page>** component tree. When this callback is invoked, related data can be displayed during the lifecycle in scenarios such as image loading and animation playback.|
| onLayoutReady | Function | Component layout completion| Layout calculation, including content size and position adjustment, is complete for the custom component.|
| onDetached | Function | Custom component removal | The custom component is removed. It is usually used to stop animation or asynchronous logic execution.|
| onDetached | Function | Custom component detachment | The custom component is detached. It is usually used to stop animation or asynchronous logic execution. |
| onDestroy | Function | Custom component destruction | The custom component is destroyed. It is usually used to release resources. |
| onShow | Function | Page display of a custom component| The page where the custom component is located is displayed. |
| onHide | Function | Page hiding of a custom component| The page where the custom component is located is hidden. |
......@@ -24,7 +24,7 @@ We provide a range of lifecycle callbacks for custom components, including **onI
```html
<!-- comp.hml -->
<div class="item">
<text class="text-style">{{value}}</text>
<text class="text-style">{{ value }}</text>
</div>
```
......@@ -39,9 +39,7 @@ export default {
},
onAttached() {
this.value = "Load the component."
},
onDetached() {
this.value = ""
console.log ("Component loaded.")
},
onShow() {
console.log ("Page displayed.")
......
# props<a name="EN-US_TOPIC_0000001173164675"></a>
# Data Transfer and Processing
You can use **props** to declare attributes of a custom component and pass the attributes to the child component. The supported types of **props** include String, Number, Boolean, Array, Object, and Function. Note that a camel case attribute name \(**compProp**\) should be converted to the kebab case format \(**comp-prop**\) when you reference the attribute in an external parent component. You can add **props** to a custom component, and pass the attribute to the child component.
```
## props
You can use **props** to declare attributes of a custom component and pass the attributes to the child component. The supported types of **props** include String, Number, Boolean, Array, Object, and Function. Note that a camel case attribute name (**compProp**) should be converted to the kebab case format (**comp-prop**) when you reference the attribute in an external parent component. The following is sample for adding **props** to a custom component and passing the attribute to the child component.
```html
<!-- comp.hml -->
<div class="item">
<text class="title-style">{{compProp}}</text>
</div>
```
```
```js
// comp.js
export default {
props: ['compProp'],
}
```
```
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/component/comp/comp.hml'></element>
<div class="container">
......@@ -24,21 +27,22 @@ export default {
</div>
```
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>The name of a custom attribute cannot start with reserved keywords such as **on**, **@**, **on:**, and **grab:**.
> **NOTE**
>
> The name of a custom attribute cannot start with reserved keywords such as **on**, **@**, **on:**, and **grab:**.
## Default Value<a name="section448655843113"></a>
### Default Value
You can set the default value for a child component attribute via **default**. The default value is used if the parent component does not have **default** set. In this case, the **props** attribute must be in object format instead of an array.
```
```html
<!-- comp.hml -->
<div class="item">
<text class="title-style">{{title}}</text>
</div>
```
```
```js
// comp.js
export default {
props: {
......@@ -49,21 +53,21 @@ export default {
}
```
In this example, a **<text\>** component is added to display the title. The title content is a custom attribute, which displays the text specified by a user. If the user has not set a title, the default text will be displayed. Add the attribute when referencing the custom component.
In this example, a **\<text>** component is added to display the title. The title content is a custom attribute, which displays the text specified by a user. If the user has not set a title, the default text will be displayed. Add the attribute when referencing the custom component.
```
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/component/comp/comp.hml'></element>
<div class="container">
<comp title=" Custom component "></comp>
<comp title="Custom component"></comp>
</div>
```
## Unidirectional Value Transfer<a name="section9681151218247"></a>
### Unidirectional Value Transfer
Data can be transferred only from the parent component to child components. You are not allowed to change the value passed to the child component. However, you can receive the value passed by **props** as a default value in **data**, and then change the **data** value.
```
```js
// comp.js
export default {
props: ['defaultCount'],
......@@ -78,11 +82,11 @@ export default {
}
```
## Monitoring Data Changes by **$watch**<a name="section205821113182114"></a>
### Monitoring Data Changes by **$watch**
To listen for attribute changes in a component, you can use the **$watch** method to add a callback. The following code snippet shows how to use **$watch**:
```
```js
// comp.js
export default {
props: ['title'],
......@@ -95,11 +99,12 @@ export default {
}
```
## Computed Property<a name="section1088954011234"></a>
## computed
To improve the development efficiency, you can use a computed property to pre-process an attribute in a custom component before reading or setting the attribute. In the **computed** field, you can set a getter or setter to be triggered when the attribute is read or written, respectively. The following is an example:
```
```js
// comp.js
export default {
props: ['title'],
......@@ -129,5 +134,4 @@ export default {
}
```
The first computed property **message** has only a getter. The value of **message** changes depending on the **objTitle** value. The getter can only read but cannot set the value. You need a setter \(such as **notice** in the sample code\) to set the value of the computed property.
The first computed property **message** has only a getter. The value of **message** changes depending on the **objTitle** value. The getter can only read but cannot set the value (such as **time** defined during initialization in **data**). You need a setter (such as **notice** in the sample code) to set the value of the computed property.
# slot<a name="EN-US_TOPIC_0000001127284840"></a>
# slot
>![](../../public_sys-resources/icon-note.gif) **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.
> **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.
## Default Slot<a name="section68133181214"></a>
You can use the **<slot\>** tag to create a slot inside a custom component to fill the content defined in the parent component. The sample code is as follows:
## Default Slot
```
You can use the **\<slot>** tag to create a slot inside a custom component to fill the content defined in the parent component. The sample code is as follows:
```html
<!-- comp.hml -->
<div class="item">
<text class="text-style">The following uses the content defined in the parent component.</text>
......@@ -16,8 +18,7 @@ You can use the **<slot\>** tag to create a slot inside a custom component to
```
The following references the custom component:
```
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/component/comp.hml'></element>
<div class="container">
......@@ -27,11 +28,12 @@ The following references the custom component:
</div>
```
## Named Slot<a name="section18337143291211"></a>
When multiple slots are need inside a custom component, you can name them, so that you can specify the slot in which you want to fill content by setting the **<name\>** attribute.
## Named Slot
```
When multiple slots are need inside a custom component, you can name them, so that you can specify the slot in which you want to fill content by setting the **<name>** attribute.
```html
<!-- comp.hml -->
<div class="item">
<text class="text-style">The following uses the content defined in the parent component.</text>
......@@ -41,8 +43,7 @@ When multiple slots are need inside a custom component, you can name them, so th
```
The following references the custom component:
```
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/component/comp.hml'></element>
<div class="container">
......@@ -53,6 +54,6 @@ The following references the custom component:
</div>
```
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>**<name\>** and **<slot\>** do not support dynamic data binding.
> **NOTE**
>
> **\<name>** and **\<slot>** do not support dynamic data binding.
# Style Inheritance
> **NOTE**<br/>
> The APIs of this module are supported since API 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.
A custom component has the **inherit-class** attribute, which is defined in the following table.
| Name | Type | Default Value| Mandatory| Description |
| ------------ | ------ | ------ | ---- | ------------------------------------------------------ |
| inherit-class | string | - | No | Class styles inherited from the parent component, seperated by spaces.|
| Name | Type | Default Value | Mandatory | Description |
| ------------- | ------ | ---- | ---- | -------------------------------- |
| inherit-class | string | - | No | Class styles inherited from the parent component, separated by spaces.|
To enable a custom component to inherit the styles of its parent component, set the **inherit-calss** attribute for the custom component.
The example below is a code snippet in the HML file of the parent page that references a custom component named **comp**. This component uses the **inherit-class** attribute to inherit the styles of its parent component: **parent-class1** and **parent-class2**.
The example below is a code snippet in the HML file of the parent component that references a custom component named **comp**. This component uses the **inherit-class** attribute to inherit the styles of its parent component: **parent-class1** and **parent-class2**.
```html
<!-- xxx.hml -->
<element name='comp' src='../../common/component/comp.hml'></element>
......@@ -20,9 +23,10 @@ The example below is a code snippet in the HML file of the parent page that refe
</div>
```
Code snippet in the CSS file of the parent page:
```html
// xxx.css
Code snippet in the CSS file of the parent component:
```css
/* xxx.css */
.parent-class1 {
background-color:red;
border:2px;
......@@ -34,6 +38,7 @@ Code snippet in the CSS file of the parent page:
```
Code snippet in the HML file of the custom component, where **parent-class1** and **parent-class2** are styles inherited from the parent component:
```html
<!--comp.hml-->
<div class="item">
......
......@@ -3,17 +3,7 @@
> **NOTE**
>
> - This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
>
> - Set **configChanges** under **abilities** in the **config.json** file to **orientation**.
> ```
> "abilities": [
> {
> "configChanges": ["orientation"],
> ...
> }
> ]
> ```
> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
The **\<video>** component provides a video player.
......@@ -28,11 +18,11 @@ Not supported
In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported.
| Name | Type | Default Value | Mandatory | Description |
| -------- | ------- | ------------- | --------- | ---------------------------------------- |
| -------- | ------- | ----- | ---- | ---------------------------------------- |
| muted | boolean | false | No | Whether the video is muted. |
| src | string | - | No | Path of the video content to play. |
| autoplay | boolean | false | No | Whether the video is played automatically after being rendered. |
| controls | boolean | true | No | Whether the control bar is displayed during video playback. If the value is set to **false**, the control bar is not displayed. The default value is **true**, indicating that the platform can either show or hide the control bar. |
| controls | boolean | true | No | Whether the control bar is displayed during video playback. If the value is set to **false**, the control bar is not displayed. The default value is **true**, indicating that the platform can either show or hide the control bar.|
## Styles
......@@ -40,14 +30,14 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri
In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported.
| Name | Type | Default Value | Mandatory | Description |
| ---------- | ------ | ------------- | --------- | ---------------------------------------- |
| object-fit | string | contain | No | Video scale type. If **poster** has been assigned a value, the setting of this style will affect the scaling type of the video poster. For details, see object-fit enums. |
| ---------- | ------ | ------- | ---- | ---------------------------------------- |
| object-fit | string | contain | No | Video scale type. If **poster** has been assigned a value, the setting of this style will affect the scaling type of the video poster. For details, see object-fit enums.|
**Table 1** object-fit enums
| Type | Description |
| ---- | ---------------------------------------- |
| fill | The image is resized to fill the display area, and its aspect ratio is not retained. |
| ---- | ------------------------- |
| fill | The image is resized to fill the display area, and its aspect ratio is not retained.|
## Events
......@@ -55,15 +45,15 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md
In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported.
| Name | Parameter | Description |
| ---------- | ---------------------------------------- | ---------------------------------------- |
| prepared | {&nbsp;duration:&nbsp;value&nbsp;}<sup>5+</sup> | Triggered when the video preparation is complete. The video duration (in seconds) is obtained from **duration**. |
| ---------- | ---------------------------------------- | ------------------------------------- |
| prepared | { duration: value }<sup>5+</sup> | Triggered when the video preparation is complete. The video duration (in seconds) is obtained from **duration**.|
| start | - | Triggered when the video is played. |
| pause | - | Triggered when the video playback is paused. |
| finish | - | Triggered when the video playback is finished. |
| error | - | Triggered when the video playback fails. |
| seeking | {&nbsp;currenttime:&nbsp;value&nbsp;} | Triggered to report the time (in seconds) when the progress bar is being dragged. |
| seeked | {&nbsp;currenttime:&nbsp;value&nbsp;} | Triggered to report the playback time (in seconds) when the user finishes dragging the progress bar. |
| timeupdate | {&nbsp;currenttime:&nbsp;value&nbsp;} | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second. |
| seeking | { currenttime: value } | Triggered to report the time (in seconds) when the progress bar is being dragged. |
| seeked | { currenttime: value } | Triggered to report the playback time (in seconds) when the user finishes dragging the progress bar. |
| timeupdate | { currenttime: value } | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second. |
## Methods
......@@ -71,10 +61,10 @@ In addition to the [universal events](../arkui-js/js-components-common-events.md
In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported.
| Name | Parameter | Description |
| -------------- | ------------------------------------- | ---------------------------------------- |
| -------------- | ------------------------------------- | ----------------- |
| start | - | Starts playing a video. |
| pause | - | Pauses a video. |
| setCurrentTime | {&nbsp;currenttime:&nbsp;value&nbsp;} | Sets the video playback position, in seconds. |
| setCurrentTime | { currenttime: value } | Sets the video playback position, in seconds.|
> **NOTE**
>
......
......@@ -52,7 +52,7 @@ Not supported
```
![zh-cn_image_0000001173324703](figures/zh-cn_image_0000001173324703.gif)
![en-us_image_0000001173324703](figures/en-us_image_0000001173324703.gif)
```html
......@@ -68,7 +68,7 @@ Not supported
```
![zh-cn_image_0000001167662852](figures/zh-cn_image_0000001167662852.gif)
![en-us_image_0000001167662852](figures/en-us_image_0000001167662852.gif)
```html
......@@ -83,7 +83,7 @@ Not supported
```
![zh-cn_image_0000001127284938](figures/zh-cn_image_0000001127284938.gif)
![en-us_image_0000001127284938](figures/en-us_image_0000001127284938.gif)
```html
......@@ -117,4 +117,4 @@ Not supported
```
![animate-4](figures/animate-4.gif)
![en-us_image_0000001127125126](figures/en-us_image_0000001127125126.gif)
......@@ -24,7 +24,7 @@ The **animate** attributes (**values** does not take effect) and the attributes
| Name| Type| Default Value| Mandatory| Description|
| -------- | -------- | -------- | -------- | -------- |
| keyPoints | string | - | Yes| Point position of a group of key frames. The value of each frame is the distance proportion of the object along the path. The function is the same as that of **values** in the **animate** attribute.|
| path | string | - | Yes| Motion path. The syntax is the same as that of the **d** attribute of the **\<path>** component. |
| path | string | - | Yes| Motion path. The syntax is the same as that of the **d** attribute of the **\<path>** component.|
| rotate | [auto \| auto-reverse \| &lt;number&gt;] | auto | No| Rotation direction of an animation object.|
......@@ -38,7 +38,7 @@ The **animate** attributes (**values** does not take effect) and the attributes
<path fill="none" stroke="blue" stroke-width="3" d="m40,130 c0,-100 160,100 160,0 c0,-100 -160,100 -160,0 z"></path>
<path fill="none" stroke="blue" stroke-width="3" d="m40,200 c0,-100 160,100 160,0 c0,-100 -160,100 -160,0 z"></path>
<path fill="red" d="M-5,-5 L10,0 L-5,5 L0,0 Z">
<animateMotion dur="2000" repeatCount="indefinite" rotate="auto" keyPoints="0;0.2;0.4;0.6;0.8;1" path="m40,60 c0,-100 160,160,100 160,0 c0,-100,-160,100 -160,0 z">
<animateMotion dur="2000" repeatCount="indefinite" rotate="auto" keyPoints="0;0.2;0.4;0.6;0.8;1" path="m40,60 c0,-100 160,100 160,0 c0,-100 -160,100 -160,0 z">
</animateMotion>
</path>
<path fill="red" d="M-5,-5 L10,0 L-5,5 L0,0 Z">
......
......@@ -194,6 +194,7 @@ Example of involved components
dur="3s" repeatCount="indefinite"></animateTransform>
</rect>
<text x="20" y="700" fill="#D2691E" font-size="40">
animate-transform
<animateTransform attributeName="transform" attributeType="XML" type="translate" from="0" to="300"
dur="3s" repeatCount="indefinite"></animateTransform>
</text>
......
......@@ -6,9 +6,9 @@ The **\<textPath>** component is used to draw text along the path.
> **NOTE**
> - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>
> - The **\<tspan>** component can be nested in the **\<textPath>** component for segmenting.
> - This component can have **\<tspan>** components nested for segmenting.
>
> - The **\<textPath>** component can only be nested in the **\<text>** component.
> - This component can only be nested in the **\<text>** component.
## Required Permissions
......@@ -26,19 +26,19 @@ The **[\<tspan>](js-components-svg-tspan.md)** child component is supported.
The attributes in the following table are supported.
| Name | Type | Mandatory | Description |
| Name | Type | Default Value| Description |
| -------------- | ---------------------------------- | ------ | ------------------------------------------------------------ |
| id | string | - | Unique ID of the component. |
| path | string | No | Shape of the path.<br>The meanings of the letters are as follows:<br>-&nbsp;M&nbsp;=&nbsp;moveto<br>-&nbsp;L&nbsp;=&nbsp;lineto<br>-&nbsp;H&nbsp;=&nbsp;horizontal&nbsp;lineto<br>-&nbsp;V&nbsp;=&nbsp;vertical&nbsp;lineto<br>-&nbsp;C&nbsp;=&nbsp;curveto<br>-&nbsp;S&nbsp;=&nbsp;smooth&nbsp;curveto<br>-&nbsp;Q&nbsp;=&nbsp;quadratic&nbsp;Belzier&nbsp;curve<br>-&nbsp;T&nbsp;=&nbsp;smooth&nbsp;quadratic&nbsp;Belzier&nbsp;curveto<br>-&nbsp;A&nbsp;=&nbsp;elliptical&nbsp;Arc<br>-&nbsp;Z&nbsp;=&nbsp;closepath<br>Default value: **0**|
| startOffset | &lt;length&gt;\|&lt;percentage&gt; | Yes | Offset of the text start point relative to the path start point.<br>Default value: **0** |
| font-size | &lt;length&gt; | No | Font size.<br>Default value: **30px** |
| fill | &lt;color&gt; | No | Font fill color.<br>Default value: **black** |
| by | number | No | Attribute offset relative to the specified animation. By default, **from** is the original attribute value. |
| opacity | number | No | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported.<br>Default value: **0**|
| fill-opacity | number | No | Font fill opacity.<br>Default value: **1.0** |
| stroke | &lt;color&gt; | No | Stroke color.<br>Default value: **black** |
| stroke-width | number | No | Stroke width.<br>Default value: **1px** |
| stroke-opacity | number | No | Stroke opacity.<br>Default value: **1.0** |
| path | string | 0 | Shape of the path.<br>The meanings of the letters are as follows:<br>- M = moveto<br>- L = lineto<br>- H = horizontal lineto<br>- V = vertical lineto<br>- C = curveto<br>- S = smooth curveto<br>- Q = quadratic Belzier curve<br>- T = smooth quadratic Belzier curveto<br>- A = elliptical Arc<br>- Z = closepath<br>Default value: **0**|
| startOffset | &lt;length&gt;\|&lt;percentage&gt; | 0 | Offset of the text start point relative to the path start point.<br>Default value: **0** |
| font-size | &lt;length&gt; | 30px | Font size.<br>Default value: **30px** |
| fill | &lt;color&gt; | black | Font fill color.<br>Default value: **black** |
| by | number | - | Attribute offset relative to the specified animation. By default, **from** is the original attribute value. |
| opacity | number | 1 | Opacity of an element. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent. Attribute animations are supported.<br>Default value: **0**|
| fill-opacity | number | 1.0 | Font fill opacity.<br>Default value: **1.0** |
| stroke | &lt;color&gt; | black | Stroke color.<br>Default value: **black** |
| stroke-width | number | 1px | Stroke width.<br>Default value: **1px** |
| stroke-opacity | number | 1.0 | Stroke opacity.<br>Default value: **1.0** |
## Example
......@@ -97,9 +97,9 @@ Combination of **\<textpath>** and **\<tspan>**
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00" x="50">
<path d="M40,760 Q360,760 360,580 Q360,440 200,440 Q40,440 40,560 Q40,680 180,680 Q280,680 300,600" stroke="red" fill="none"></path>
<path d="M40,360 Q360,360 360,180 Q360,40 200,40 Q40,40 40,160 Q40,280 180,280 Q280,280 300,200" stroke="red" fill="none"></path>
<text>
<textpath fill="#D2691E" path="M40,760 Q360,760 360,580 Q360,440 200,440 Q40,440 40,560 Q40,680 180,680 Q280,680 300,600"font-size="30px" stroke="black" stroke-width="1" >
<textpath fill="#D2691E" path="M40,360 Q360,360 360,180 Q360,40 200,40 Q40,40 40,160 Q40,280 180,280 Q280,280 300,200" font-size="30px" stroke="black" stroke-width="1" >
This is TextPath.
<tspan font-size="20px" fill="red">This is tspan onTextPath.</tspan>
<tspan font-size="30px">Let's play.</tspan>
......@@ -117,11 +117,11 @@ Combination of **\<textpath>** and **\<tspan>**
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00" x="50">
<path d="M40,1160 Q360,1160 360,980 Q360,840 200,840 Q40,840 40,960 Q40,1080 180,1080 Q280,1080 300,1000" stroke="red" fill="none">
<path d="M40,360 Q360,360 360,180 Q360,40 200,40 Q40,40 40,160 Q40,280 180,280 Q280,280 300,200" stroke="red" fill="none">
</path>
<!-- Value percentage -->
<text>
<textpath fill="#D2691E" path="M40,1160 Q360,1160 360,980 Q360,840 200,840 Q40,840 40,960 Q40,1080 180,1080 Q280,1080 300,1000" font-size="30px">
<textpath fill="#D2691E" path="M40,360 Q360,360 360,180 Q360,40 200,40 Q40,40 40,160 Q40,280 180,280 Q280,280 300,200" font-size="30px">
This is TextPath.
<tspan x="50" fill="blue">This is first tspan.</tspan>
<tspan x="50%">This is second tspan.</tspan>
......@@ -172,10 +172,10 @@ Attribute animation of the **\<textPath>** and **\<tspan>** in combination
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00">
<path d="M40,1160 Q360,1160 360,980 Q360,840 200,840 Q40,840 40,960 Q40,1080 180,1080 Q280,1080 300,1000" stroke="red" fill="none">
<path d="M40,360 Q360,360 360,180 Q360,40 200,40 Q40,40 40,160 Q40,280 180,280 Q280,280 300,200" stroke="red" fill="none">
</path>
<text>
<textpath fill="#D2691E" path="M40,1160 Q360,1160 360,980 Q360,840 200,840 Q40,840 40,960 Q40,1080 180,1080 Q280,1080 300,1000" font-size="30px">
<textpath fill="#D2691E" path="M40,360 Q360,360 360,180 Q360,40 200,40 Q40,40 40,160 Q40,280 180,280 Q280,280 300,200" font-size="30px">
This is TextPath.
<tspan x="50" fill="blue">
tspan attribute x|rotate
......@@ -209,11 +209,11 @@ Attribute animation of the **\<textPath>** and **\<tspan>** in combination
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00">
<path d="M40,1560 Q360,1560 360,1380 Q360,1240 200,1240 Q40,1240 40,1360 Q40,1480 180,1480 Q280,1480 300,1400" stroke="red"
<path d="M40,360 Q360,360 360,180 Q360,40 200,40 Q40,40 40,160 Q40,280 180,280 Q280,280 300,200" stroke="red"
fill="none">
</path>
<text>
<textpath fill="#D2691E" path="M40,1560 Q360,1560 360,1380 Q360,1240 200,1240 Q40,1240 40,1360 Q40,1480 180,1480 Q280,1480 300,1400" font-size="30px">
<textpath fill="#D2691E" path="M40,360 Q360,360 360,180 Q360,40 200,40 Q40,40 40,160 Q40,280 180,280 Q280,280 300,200" font-size="30px">
This is TextPath.
<tspan dx="20" fill="blue">
tspan attribute fill|fill-opacity
......@@ -247,11 +247,11 @@ Attribute animation of the **\<textPath>** and **\<tspan>** in combination
<!-- xxx.hml -->
<div class="container">
<svg fill="#00FF00">
<path d="M40,1960 Q360,1960 360,1780 Q360,1640 200,1640 Q40,1640 40,1760 Q40,1880 180,1880 Q280,1880 300,1800" stroke="red"
<path d="M40,360 Q360,360 360,180 Q360,40 200,40 Q40,40 40,160 Q40,280 180,280 Q280,280 300,200" stroke="red"
fill="none">
</path>
<text>
<textpath fill="#D2691E" path="M40,1960 Q360,1960 360,1780 Q360,1640 200,1640 Q40,1640 40,1760 Q40,1880 180,1880 Q280,1880 300,1800" font-size="30px">
<textpath fill="#D2691E" path="M40,360 Q360,360 360,180 Q360,40 200,40 Q40,40 40,160 Q40,280 180,280 Q280,280 300,200" font-size="30px">
This is TextPath.
<tspan dx="20" fill="blue">
tspan attribute stroke
......
......@@ -14,12 +14,12 @@ In addition to the attributes that are supported by **CanvasRenderingContext2D**
| Name | Type | Description |
| ------ | ------ | ---------------------------------------- |
| filter | string | Image filter.<br>Available options are as follows:<br>- **blur**: applies the Gaussian blur for the image.<br>- **brightness**: applies a linear multiplication to the image to make it look brighter or darker.<br>- **contrast**: adjusts the image contrast.<br>- **drop-shadow**: sets a shadow effect for the image.<br>- **grayscale**: converts the image to a grayscale image.<br>- **hue-rotate**: applies hue rotation to the image.<br>- **invert**: inverts the input image.<br>- **opacity**: sets the opacity of the image.<br>- **saturate**: sets the saturation of the image.<br>- **sepia**: converts the image to dark brown. |
| filter | string | Image filter.<br>Available options are as follows:<br>- **blur**: applies the Gaussian blur for the image.<br>- **brightness**: applies a linear multiplication to the image to make it look brighter or darker.<br>- **contrast**: adjusts the image contrast.<br>- **drop-shadow**: sets a shadow effect for the image.<br>- **grayscale**: converts the image to a grayscale image.<br>- **hue-rotate**: applies hue rotation to the image.<br>- **invert**: inverts the image.<br>- **opacity**: sets the image opacity.<br>- **saturate**: sets the image saturation.<br>- **sepia**: converts the image to sepia.|
**Example**
```html
<!-- xxx.hml -->
<div style="width: 180px; height: 60px;">
<div style="width: 500px; height: 500px;">
<canvas ref="canvasId" style="width: 500px; height: 500px; background-color: #ffff00;"></canvas>
</div>
```
......@@ -95,7 +95,7 @@ Checks whether a specified point is in the path area.
**Example**
```html
<!-- xxx.hml -->
<div style="width: 180px; height: 60px;">
<div style="width: 500px; height: 500px;">
<text>In path:{{textValue}}</text>
<canvas ref="canvas" style="width: 500px; height: 500px; background-color: #ffff00;"></canvas>
</div>
......@@ -145,7 +145,7 @@ Checks whether a specified point is on the edge line of a path.
**Example**
```html
<!-- xxx.hml -->
<div style="width: 180px; height: 60px;">
<div style="width: 500px; height: 500px;">
<text>In path:{{textValue}}</text>
<canvas ref="canvas" style="width: 500px; height: 500px; background-color: #ffff00;"></canvas>
</div>
......@@ -181,7 +181,7 @@ resetTransform(): void
**Example**
```html
<!-- xxx.hml -->
<div style="width: 180px; height: 60px;">
<div style="width: 500px; height: 500px;">
<text>In path:{{textValue}}</text>
<canvas ref="canvas" style="width: 500px; height: 500px; background-color: #ffff00;"></canvas>
</div>
......@@ -199,13 +199,13 @@ export default {
var offscreenCanvasCtx = offscreen.getContext("2d");
offscreenCanvasCtx.transform(1, 0, 1.7, 1, 0, 0);
offscreenCanvasCtx.fillStyle = 'gray';
offscreenCanvasCtx.fillStyle = '#a9a9a9';
offscreenCanvasCtx.fillRect(40, 40, 50, 20);
offscreenCanvasCtx.fillRect(40, 90, 50, 20);
// Non-skewed rectangles
offscreenCanvasCtx.resetTransform();
offscreenCanvasCtx.fillStyle = 'red';
offscreenCanvasCtx.fillStyle = '#ff0000';
offscreenCanvasCtx.fillRect(40, 40, 50, 20);
offscreenCanvasCtx.fillRect(40, 90, 50, 20);
......
# ArkTS-based Declarative Development Paradigm
- [Component Overview](ts-components-summary.md)
- Universal Component Information
- Universal Events
- [Click Event](ts-universal-events-click.md)
......@@ -65,6 +66,8 @@
- [LoadingProgress](ts-basic-components-loadingprogress.md)
- [Marquee](ts-basic-components-marquee.md)
- [Navigation](ts-basic-components-navigation.md)
- [NavRouter](ts-basic-components-navrouter.md)
- [NavDestination](ts-basic-components-navdestination.md)
- [PatternLock](ts-basic-components-patternlock.md)
- [PluginComponent](ts-basic-components-plugincomponent.md)
- [Progress](ts-basic-components-progress.md)
......@@ -98,7 +101,7 @@
- [ColumnSplit](ts-container-columnsplit.md)
- [Counter](ts-container-counter.md)
- [Flex](ts-container-flex.md)
- [GridContainer](ts-container-gridcontainer.md)
- [FlowItem](ts-container-flowitem.md)
- [GridCol](ts-container-gridcol.md)
- [GridRow](ts-container-gridrow.md)
- [Grid](ts-container-grid.md)
......@@ -118,8 +121,8 @@
- [Swiper](ts-container-swiper.md)
- [Tabs](ts-container-tabs.md)
- [TabContent](ts-container-tabcontent.md)
- [WaterFlow](ts-container-waterflow.md)
- Media Components
- [Video](ts-media-components-video.md)
- Drawing Components
- [Circle](ts-drawing-components-circle.md)
......@@ -139,16 +142,14 @@
- [OffscreenCanvasRenderingContext2D](ts-offscreencanvasrenderingcontext2d.md)
- [Path2D](ts-components-canvas-path2d.md)
- [Lottie](ts-components-canvas-lottie.md)
- Animation
- [AnimatorProperty](ts-animatorproperty.md)
- [Explicit Animation](ts-explicit-animation.md)
- [Explicit Animatio](ts-explicit-animation.md)
- Transition Animation
- [Page Transition](ts-page-transition-animation.md)
- [Component Transition](ts-transition-animation-component.md)
- [Transition of Shared Elements](ts-transition-animation-shared-elements.md)
- [Motion Path Animation](ts-motion-path-animation.md)
- Global UI Methods
- Pop-up Window
- [Alert Dialog Box](ts-methods-alert-dialog-box.md)
......@@ -158,5 +159,9 @@
- [Time Picker Dialog Box](ts-methods-timepicker-dialog.md)
- [Text Picker Dialog Box](ts-methods-textpicker-dialog.md)
- [Menu](ts-methods-menu.md)
- [Built-in Enums](ts-appendix-enums.md)
- [State Management with Application-level Variables](ts-state-management.md)
- [Pixel Units](ts-pixel-units.md)
- [Enums](ts-appendix-enums.md)
- [Types](ts-types.md)
- Components No Longer Maintained
- [GridContainer](ts-container-gridcontainer.md)
# Property Animator
You can create a property animator to animate certain universal attributes of a component, including **width**, **height**, backgroundColor, **opacity**, **scale**, **rotate**, and **translate**.
You can create a property animator to animate certain universal attributes of a component, including **width**, **height**, **backgroundColor**, **opacity**, **scale**, **rotate**, and **translate**.
> **NOTE**
>
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
animation(value: {duration?: number, tempo?: number, curve?: string | Curve | ICurve, delay?:number, iterations: number, playMode?: PlayMode, onFinish?: () => void})
Applies a property animator to the component to animate its attributes over time.
animation(value: {duration?: number, tempo?: number, curve?: string | Curve | ICurve, delay?:number, iterations: number, playMode?: PlayMode, onFinish?: () => void})
**Parameters**
| Name | Type | Mandatory | Description |
| ---------- | ------------------------------------------| ---- | ------------------------------------------------------------ |
| duration | number | No | Animation duration, in ms.<br>Default value: **1000**|
| tempo | number | No | Animation playback speed. A greater value indicates a higher animation playback speed.<br>The value **0** indicates that no animation is applied.<br>Default value: **1**|
| curve | string&nbsp;\|&nbsp;[Curve](ts-appendix-enums.md#curve)&nbsp;\|&nbsp;ICurve<sup>9+</sup> | No | Animation curve.<br>Default value: **Curve.Linear** |
| curve | string \| [Curve](ts-appendix-enums.md#curve) \| ICurve<sup>9+</sup> | No | Animation curve.<br>Default value: **Curve.Linear** |
| delay | number | No | Delay of animation playback, in ms. The value **0** indicates that the playback is not delayed.<br>Default value: **0** |
| iterations | number | No | Number of times that the animation is played. The value **-1** indicates that the animation is played for an unlimited number of times.<br>Default value: **1**|
| playMode | [PlayMode](ts-appendix-enums.md#playmode) | No | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.<br>Default value: **PlayMode.Normal**|
......@@ -31,34 +29,49 @@ Applies a property animator to the component to animate its attributes over time
@Entry
@Component
struct AttrAnimationExample {
@State widthSize: number = 200;
@State heightSize: number = 100;
@State flag: boolean = true;
@State widthSize: number = 250
@State heightSize: number = 100
@State rotateAngle: number = 0
@State flag: boolean = true
build() {
Column() {
Button('click me')
.onClick((event: ClickEvent) => {
Button('change width and height')
.onClick(() => {
if (this.flag) {
this.widthSize = 100
this.heightSize = 50
} else {
this.widthSize = 200
this.widthSize = 250
this.heightSize = 100
}
this.flag = !this.flag
})
.width(this.widthSize).height(this.heightSize).backgroundColor(0x317aff)
.margin(30)
.width(this.widthSize)
.height(this.heightSize)
.animation({
duration: 2000, // Animation duration
curve: Curve.EaseOut, // Animation curve
delay: 500, // Animation delay
iterations: 1, // Number of playback times
playMode: PlayMode.Normal // Animation playback mode
}) // Animation configuration for the width and height attributes of the <Button> component
}.width('100%').margin({ top: 5 })
duration: 2000,
curve: Curve.EaseOut,
iterations: 3,
playMode: PlayMode.Normal
})
Button('change rotate angle')
.onClick(() => {
this.rotateAngle = 90
})
.margin(50)
.rotate({ angle: this.rotateAngle })
.animation({
duration: 1200,
curve: Curve.Friction,
delay: 500,
iterations: -1, // The value -1 indicates that the animation is played for an unlimited number of times.
playMode: PlayMode.AlternateReverse
})
}.width('100%').margin({ top: 20 })
}
}
```
![en-us_image_0000001212378444](figures/en-us_image_0000001212378444.gif)
![animation](figures/animation.gif)
# 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)
......@@ -14,26 +14,26 @@ This component can contain only one child component.
## APIs
**Method 1:** Button(options?: {type?: ButtonType, stateEffect?: boolean})
**API 1:** Button(options?: {type?: ButtonType, stateEffect?: boolean})
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ---------- | ------| --------------------------------- |
| type | ButtonType | No | Button type.<br>Default value: **ButtonType.Capsule** |
| stateEffect | boolean | No | Whether to enable the state switchover effect for when the button is touched or clicked. The value **false** indicates that the state switchover effect is disabled.<br>Default value: **true**|
| stateEffect | boolean | No | Whether to enable the pressed effect on the click of the button. The value **false** means to disable the pressed effect.<br>Default value: **true**|
**Method 2:** Button(label?: ResourceStr, options?: { type?: ButtonType, stateEffect?: boolean })
**API 2:** Button(label?: ResourceStr, options?: { type?: ButtonType, stateEffect?: boolean })
Creates a button component based on text content. In this case, the component cannot contain child components.
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ----------------------------------- | ---- | ------------- |
| label | [ResourceStr](ts-types.md#resourcestr) | No | Button text. |
| options | Object | No | For details, see **options**.|
| Name | Type | Mandatory | Description |
| ------- | ----------------------------------- | ---- | ------------- |
| label | [ResourceStr](ts-types.md#resourcestr) | No | Button text. |
| options | { type?: ButtonType, stateEffect?: boolean } | No | See parameters of API 1.|
## Attributes
......@@ -41,7 +41,7 @@ This component can contain only one child component.
| Name | Type | Description |
| ----------- | ----------- | --------------------------------- |
| type | ButtonType | Button type.<br>Default value: **ButtonType.Capsule** |
| stateEffect | boolean | Whether to enable the state switchover effect. The value **false** indicates that the state switchover effect is disabled.<br>Default value: **true**|
| stateEffect | boolean | Whether to enable the pressed effect on the click of the button. The value **false** means to disable the pressed effect.<br>Default value: **true**|
## ButtonType enums
| Name | Description |
......@@ -66,43 +66,42 @@ This component can contain only one child component.
struct ButtonExample {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
Text('Common button').fontSize(9).fontColor(0xCCCCCC)
Text('Normal button').fontSize(9).fontColor(0xCCCCCC)
Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Button('Ok', { type: ButtonType.Normal, stateEffect: true }).borderRadius(8).backgroundColor(0x317aff).width(90)
Button('OK', { type: ButtonType.Normal, stateEffect: true }).borderRadius(8).backgroundColor(0x317aff).width(90)
Button({ type: ButtonType.Normal, stateEffect: true }) {
Row() {
// To import an image, you are advised to create a Resource object through $r.
Image($r('app.media.loading')).width(20).height(20).margin({ left: 12 })
LoadingProgress().width(20).height(20).margin({ left: 12 }).color(0xFFFFFF)
Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 })
}.alignItems(VerticalAlign.Center)
}.borderRadius(8).backgroundColor(0x317aff).width(90)
Button('Disable', { type: ButtonType.Normal, stateEffect: false }).opacity(0.5)
}.borderRadius(8).backgroundColor(0x317aff).width(90).height(40)
Button('Disable', { type: ButtonType.Normal, stateEffect: false }).opacity(0.4)
.borderRadius(8).backgroundColor(0x317aff).width(90)
}
Text('Capsule button').fontSize(9).fontColor(0xCCCCCC)
Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Button('Ok', { type: ButtonType.Capsule, stateEffect: true }).backgroundColor(0x317aff).width(90)
Button('OK', { type: ButtonType.Capsule, stateEffect: true }).backgroundColor(0x317aff).width(90)
Button({ type: ButtonType.Capsule, stateEffect: true }) {
Row() {
Image($r('app.media.loading')).width(20).height(20).margin({ left: 12 })
LoadingProgress().width(20).height(20).margin({ left: 12 }).color(0xFFFFFF)
Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 })
}.alignItems(VerticalAlign.Center).width(90)
}.alignItems(VerticalAlign.Center).width(90).height(40)
}.backgroundColor(0x317aff)
.onClick((event: ClickEvent) => {
AlertDialog.show({ message: 'The login is successful' })
})
Button('Disable', { type: ButtonType.Capsule, stateEffect: false }).opacity(0.5)
Button('Disable', { type: ButtonType.Capsule, stateEffect: false }).opacity(0.4)
.backgroundColor(0x317aff).width(90)
}
Text('Circle button').fontSize(9).fontColor(0xCCCCCC)
Flex({ alignItems: ItemAlign.Center, wrap: FlexWrap.Wrap }) {
Button({ type: ButtonType.Circle, stateEffect: true }) {
Image($r('app.media.ic_public_app_filled')).width(20).height(20)
LoadingProgress().width(20).height(20).color(0xFFFFFF)
}.width(55).height(55).backgroundColor(0x317aff)
Button({ type: ButtonType.Circle, stateEffect: true }) {
Image($r('app.media.ic_public_delete_filled')).width(30).height(30)
LoadingProgress().width(20).height(20).color(0xFFFFFF)
}.width(55).height(55).margin({ left: 20 }).backgroundColor(0xF55A42)
}
}.height(400).padding({ left: 35, right: 35, top: 35 })
......@@ -110,4 +109,4 @@ struct ButtonExample {
}
```
![en-us_image_0000001257138341](figures/en-us_image_0000001257138341.gif)
![button](figures/button.gif)
......@@ -37,7 +37,7 @@ In addition to the [universal events](ts-universal-events-click.md), the followi
| Name | Description|
| ----------| -------- |
|onChange(callback: (value: boolean) => void) | Triggered when the selection status of the check box changes.<br>- The value **true** means that the check box is selected.<br>- The value **false** means that the check box is not selected.|
|onChange(callback: (value: boolean) => void) | Triggered when the selected status of the check box changes due to a manual operation.<br>- The value **true** means that the check box is selected.<br>- The value **false** means that the check box is not selected. |
## Example
......
......@@ -18,6 +18,8 @@ Creates a check box group so that you can select or deselect all check boxes in
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| group | string | No| Group name.|
......@@ -28,7 +30,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Description|
| -------- | -------- | -------- |
| selectAll | boolean | Whether to select all.<br>Default value: **false**|
| selectAll | boolean | Whether to select all.<br>Default value: **false**<br>If **select** is explicitly set for check boxes in the group, the check box settings are prioritized.|
| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected check box.|
## Events
......@@ -37,13 +39,13 @@ In addition to the [universal events](ts-universal-events-click.md), the followi
| Name| Description|
| -------- | -------- |
| onChange (callback: (event: CheckboxGroupResult) => void ) |Triggered when the selection status of the check box group or any check box wherein changes.|
| onChange (callback: (event: [CheckboxGroupResult](#checkboxgroupresult)) => void ) |Triggered when the selected status of the check box group or any check box wherein changes due to a manual operation.|
## CheckboxGroupResult
| Name | Type | Description |
| ------ | ------ | ------- |
| name | Array&lt;string&gt; | Names of all the selected check boxes in the group.|
| status | SelectStatus | Selected status.|
| status | [SelectStatus](#selectstatus) | Selected status.|
## SelectStatus
......@@ -64,47 +66,48 @@ struct CheckboxExample {
build() {
Scroll() {
Column() {
// Select All button
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
CheckboxGroup({ group: 'checkboxGroup' })
.selectedColor(0xed6f21)
.selectedColor('#007DFF')
.onChange((itemName: CheckboxGroupResult) => {
console.info("TextPicker::dialogResult is" + JSON.stringify(itemName))
console.info("checkbox group content" + JSON.stringify(itemName))
})
Text('select all').fontSize(20)
Text('Select All').fontSize(14).lineHeight(20).fontColor('#182431').fontWeight(500)
}
// Option 1
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Checkbox({ name: 'checkbox1', group: 'checkboxGroup' })
.select(true)
.selectedColor(0x39a2db)
.selectedColor('#007DFF')
.onChange((value: boolean) => {
console.info('Checkbox1 change is' + value)
})
Text('Checkbox1').fontSize(20)
}
Text('Checkbox1').fontSize(14).lineHeight(20).fontColor('#182431').fontWeight(500)
}.margin({ left: 36 })
// Option 2
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Checkbox({ name: 'checkbox2', group: 'checkboxGroup' })
.select(false)
.selectedColor(0x39a2db)
.selectedColor('#007DFF')
.onChange((value: boolean) => {
console.info('Checkbox2 change is' + value)
})
Text('Checkbox2').fontSize(20)
}
Text('Checkbox2').fontSize(14).lineHeight(20).fontColor('#182431').fontWeight(500)
}.margin({ left: 36 })
// Option 3
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Checkbox({ name: 'checkbox3', group: 'checkboxGroup' })
.select(true)
.selectedColor(0x39a2db)
.selectedColor('#007DFF')
.onChange((value: boolean) => {
console.info('Checkbox3 change is' + value)
})
Text('Checkbox3').fontSize(20)
}
Text('Checkbox3').fontSize(14).lineHeight(20).fontColor('#182431').fontWeight(500)
}.margin({ left: 36 })
}
}
}
}
```
![](figures/checkboxgroup.gif)
![checkboxgroup](figures/checkboxgroup.gif)
......@@ -22,12 +22,12 @@ DataPanel(options:{values: number[], max?: number, type?: DataPanelType})
| Name | Type | Mandatory | Description|
| ----------------- | -------- | ----- | -------- |
| values | number[] | Yes | Value list. A maximum of nine values are supported.|
| values | number[] | Yes | Data value list. A maximum of nine values are supported. If more than nine values are set, only the first nine ones are used. If the value is less than 0, the value 0 is used.|
| max | number | No | - When set to a value greater than 0, this parameter indicates the maximum value in the **values** list.<br>- When set to a value equal to or smaller than 0, this parameter indicates the sum of values in the **values** list. The values are displayed in proportion.<br>Default value: **100**|
| type<sup>8+</sup> | DataPanelType | No| Type of the data panel.<br>Default value: **DataPanelType.Circle**|
| type<sup>8+</sup> | [DataPanelType](#datapaneltype) | No| Type of the data panel.<br>Default value: **DataPanelType.Circle**|
## DataPanelType enums
## DataPanelType
| Name| Description|
| -------| ------------ |
| Line | Line data panel.|
......@@ -41,18 +41,46 @@ DataPanel(options:{values: number[], max?: number, type?: DataPanelType})
@Entry
@Component
struct DataPanelExample {
public values1: number[] = [10, 10, 10, 10, 10, 10, 10, 10, 10]
public valueArr: number[] = [10, 10, 10, 10, 10, 10, 10, 10, 10]
build() {
Column({ space: 5 }) {
Text('Circle').fontSize(9).fontColor(0xCCCCCC).margin({ top: 20, right: '80%' })
DataPanel({ values: this.values1, max: 100, type: DataPanelType.Circle }).width(200).height(200)
Row() {
Stack() {
DataPanel({ values: [25], max: 100, type: DataPanelType.Circle }).width(168).height(168)
Column() {
Text('30').fontSize(35).fontColor('#182431')
Text('1.0.0').fontSize(9.33).lineHeight(12.83).fontWeight(500).opacity(0.6)
}
Text('%')
.fontSize(9.33)
.lineHeight(12.83)
.fontWeight(500)
.opacity(0.6)
.position({ x: 104.42, y: 78.17 })
}.margin({ right: 44 })
Stack() {
DataPanel({ values: [50, 12, 8, 5], max: 100, type: DataPanelType.Circle }).width(168).height(168)
Column() {
Text('75').fontSize(35).fontColor('#182431')
Text('Used: 98 GB/128 GB') .fontSize(8.17).lineHeight(11.08).fontWeight(500).opacity(0.6)
}
Text('%')
.fontSize(9.33)
.lineHeight(12.83)
.fontWeight(500)
.opacity(0.6)
.position({ x: 104.42, y: 78.17 })
}
}.margin({ bottom: 59 })
Text('Line').fontSize(9).fontColor(0xCCCCCC).margin({ bottom: 20, right: '80%' })
DataPanel({ values: this.values1, max: 100, type: DataPanelType.Line }).width(300).height(10)
DataPanel({ values: this.valueArr, max: 100, type: DataPanelType.Line }).width(300).height(10)
}.width('100%').margin({ top: 5 })
}
}
```
![en-us_image_0000001211898476](figures/en-us_image_0000001211898476.jpg)
![dataPanel](figures/dataPanel.PNG)
......@@ -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)
......@@ -27,7 +27,7 @@ Obtains an image from the specified source for subsequent rendering and display.
| Name| Type | Mandatory| Description |
| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| src | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.<br>When using an image referenced using a relative path, for example, `Image("common/test.jpg")`, the **\<Image>** component cannot be called across bundles or modules. Therefore, you are advised to use `$r` to reference image resources that need to be used globally.<br>- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.<br>\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.<br/>\- Strings with the **datashare://path** prefix are supported, which are used to access the image path provided by a data ability.<br>\- Strings with the `file:///data/storage` prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the application. Ensure that the files in the directory package path have the read permission.|
| src | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.<br>When using an image referenced using a relative path, for example, `Image("common/test.jpg")`, the **\<Image>** component cannot be called across bundles or modules. Therefore, you are advised to use `$r` to reference image resources that need to be used globally.<br>- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.<br>\- Base64 strings are supported. The value format is data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data], where [base64 data] is a Base64 string.<br/>\- Strings with the **datashare://path** prefix are supported, which are used to access the image path provided by a data ability. Before loading images, the application must [request the required permissions](../../file-management/medialibrary-overview.md#requesting-permissions).<br>\- Strings with the **file:///data/storage** prefix are supported, which are used to read image resources in the **files** folder in the installation directory of the application. Ensure that the files in the directory package path have the read permission.|
## Attributes
......@@ -37,8 +37,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| --------------------- | ------------------------------------------------------- | ------------------------------------------------------------ |
| alt | string \| [Resource](ts-types.md#resource)| Placeholder image displayed during loading. Local images are supported. |
| objectFit | [ImageFit](ts-appendix-enums.md#imagefit) | Image scale mode.<br>Default value: **ImageFit.Cover** |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Whether the image is repeated.<br>Default value: **NoRepeat**<br>**NOTE**<br>This attribute is not applicable to SVG images.|
| interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.<br>Default value: **ImageInterpolation.None**<br>**NOTE**<br>This attribute is not applicable to SVG images and **PixelMap** objects. |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Whether the image is repeated.<br>Default value: **ImageRepeat.NoRepeat**<br>**NOTE**<br>This attribute is not applicable to SVG images.|
| interpolation | [ImageInterpolation](#imageinterpolation) | Interpolation effect of the image. This attribute is intended to alleviate aliasing that occurs when a low-definition image is zoomed in.<br>Default value: **ImageInterpolation.None**<br>**NOTE**<br>This attribute is not applicable to SVG images.<br>This attribute is not applicable to **PixelMap** objects.|
| renderMode | [ImageRenderMode](#imagerendermode) | Rendering mode of the image.<br>Default value: **ImageRenderMode.Original**<br>**NOTE**<br>This attribute is not applicable to SVG images.|
| sourceSize | {<br>width: number,<br>height: number<br>} | Size of the decoded image. The original image is decoded into a **pixelMap** of the specified size, in px.<br>**NOTE**<br>This attribute is not applicable to **PixelMap** objects.|
| matchTextDirection | boolean | Whether to display the image in the system language direction. When this parameter is set to true, the image is horizontally flipped in the right-to-left (RTL) language context.<br>Default value: **false** |
......@@ -76,9 +76,9 @@ In addition to the [universal events](ts-universal-events-click.md), the followi
| Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,<br> componentHeight: number, loadingStatus: number }) =&gt; void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.<br>- **width**: width of the image, in pixels.<br>- **height**: height of the image, in pixels.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>- **loadingStatus**: image loading status. |
| onError(callback: (event?: { componentWidth: number, componentHeight: number , message<sup>9+</sup>: string }) =&gt; void) | Triggered when an exception occurs during image loading.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels. |
| onFinish(event: () =&gt; void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered. |
| onComplete(callback: (event?: { width: number, height: number, componentWidth: number,<br> componentHeight: number, loadingStatus: number }) =&gt; void) | Triggered when an image is successfully loaded. The size of the loaded image is returned.<br>- **width**: width of the image, in pixels.<br>- **height**: height of the image, in pixels.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.<br>- **loadingStatus**: image loading status.<br>|
| onError(callback: (event?: { componentWidth: number, componentHeight: number , message<sup>9+</sup>: string }) =&gt; void) | Triggered when an exception occurs during image loading.<br>- **componentWidth**: width of the container component, in pixels.<br>- **componentHeight**: height of the container component, in pixels.|
| onFinish(event: () =&gt; void) | Triggered when the animation playback in the loaded SVG image is complete. If the animation is an infinite loop, this callback is not triggered.|
## Example
......@@ -161,7 +161,7 @@ The default network timeout period is 5 minutes for loading online images. When
```tsx
// @ts-nocheck
import http from '@ohos.net.http';
import ResponseCode from '@ohos.net.http';
import ResponseCode from '@ohos.net.http'
import image from '@ohos.multimedia.image'
......@@ -176,7 +176,7 @@ struct Index {
Column({space: 10}) {
Button ("Get Online Image")
.onClick(() => {
this.httpRequest();
this.httpRequest()
})
Image(this.image).height(100).width(100)
}
......@@ -187,7 +187,7 @@ struct Index {
// Request an online image.
private httpRequest() {
let httpRequest = http.createHttp();
let httpRequest = http.createHttp()
httpRequest.request(
"https://www.example.com/xxx.png", // Enter a specific URL of the online image.
......@@ -207,7 +207,7 @@ struct Index {
this.image = pixelMap
})
} else {
console.log("response code: " + code);
console.log("response code: " + code)
}
}
}
......@@ -218,7 +218,7 @@ struct Index {
> **NOTE**
>
> For details about the request mode, timeout, and additional request parameters for loading online images, see [`request()`](../../reference/apis/js-apis-http.md) in the HTTP module.
> For details about the request mode, timeout, and additional request parameters for loading online images, see [request()](../../reference/apis/js-apis-http.md) in the HTTP module.
### Setting Attributes
......@@ -351,3 +351,58 @@ struct ImageExample3 {
```
![en-us_image_0000001256858397](figures/en-us_image_0000001256858397.gif)
### Rendering Sandbox Images
```ts
import fileio from '@ohos.fileio'
import fs from '@ohos.file.fs'
import context from '@ohos.application.context'
@Entry
@Component
struct LoadImageExample {
@State resourcesPath: string = ''
@State sandboxPath: string = ''
context: context.AbilityContext
aboutToAppear() {
this.context = getContext(this) as context.AbilityContext
}
build() {
Column() {
Button ('Read Sandbox Image')
.margin({ bottom: 10, top: 10 })
.onClick(() => {
this.sandboxPath = this.context.getApplicationContext().filesDir + '/icon.png'
console.log(`Read the sandbox image=========>${this.sandboxPath}`)
let fd = fs.openSync(this.sandboxPath, 0o100)
console.log(`create file========>${fd}`)
let srcPath = this.context.bundleCodeDir + '/entry/resources/base/media/icon.png'
console.log('mySrcpath' + srcPath)
fileio.copyFileSync(srcPath, this.sandboxPath) // Copy the image to the sandbox path.
this.sandboxPath = 'file://' + this.context.getApplicationContext().filesDir + '/icon.png'
})
Button ('Read Image')
.margin({ bottom: 10 })
.onClick(() => {
this.resourcesPath = 'file://' + this.context.bundleCodeDir + '/entry/resources/base/media/icon.png'
})
Text(`Image path: ${this.resourcesPath}`)
.fontSize(20)
.margin({ bottom: 10 })
Image(this.resourcesPath)
.width(100)
.height(100)
Text(`Sandbox image path: ${this.sandboxPath}`)
.fontSize(20)
.margin({ bottom: 10 })
Image(this.sandboxPath)
.width(100)
.height(100)
}
.width('100%').height('100%')
}
}
```
# ImageAnimator
The **\<ImageAnimator>** component enables images to be played frame by frame. The list of images to be played can be configured, and the duration of each image can be configured.
The **\<ImageAnimator>** component enables images to be played frame by frame. The list of images to be played as well as the duration of each image can be configured.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Not supported
......@@ -25,7 +27,7 @@ ImageAnimator()
| duration | number | Playback duration, in ms. The default duration is 1000 ms. When the duration is **0**, no image is played. The value change takes effect only at the beginning of the next cycle. When a separate duration is set in **images**, the setting of this attribute is invalid.<br>Default value: **1000**|
| reverse | boolean | Playback sequence. The value **false** indicates that images are played from the first one to the last one, and **true** indicates that images are played from the last one to the first one.<br>Default value: **false**|
| fixedSize | boolean | Whether the image size is the same as the component size.<br> **true**: The image size is the same as the component size. In this case, the width, height, top, and left attributes of the image are invalid.<br> **false**: The width, height, top, and left attributes of each image must be set separately.<br>Default value: **true**|
| preDecode | number | Whether to enable pre-decoding. The default value **0** indicates that pre-decoding is disabled. The value **2** indicates that two images following the currently playing frame will be cached in advance to improve performance.<br>Default value: **0**|
| preDecode<sup>(deprecated)</sup> | number | Number of pre-decoded images. The value **2** indicates that two images following the currently playing page will be pre-decoded to improve performance.<br>This API is deprecated since API version 9.<br>Default value: **0**|
| fillMode | [FillMode](ts-appendix-enums.md#fillmode) | Status before and after the animation starts. For details about the options, see **FillMode**.<br>Default value: **FillMode.Forwards**|
| iterations | number | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.<br>Default value: **1**|
......@@ -100,7 +102,7 @@ struct ImageAnimatorExample {
left: 0
}
])
.state(this.state).reverse(this.reverse).fixedSize(false).preDecode(2)
.state(this.state).reverse(this.reverse).fixedSize(false)
.fillMode(FillMode.None).iterations(this.iterations).width(340).height(240)
.margin({ top: 100 })
.onStart(() => {
......@@ -117,6 +119,7 @@ struct ImageAnimatorExample {
})
.onFinish(() => {
console.info('Finish')
this.state = AnimationStatus.Stopped
})
Row() {
Button('start').width(100).padding(5).onClick(() => {
......
......@@ -3,6 +3,7 @@
The **\<LoadingProgress>** component is used to create a loading animation.
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
......
......@@ -51,10 +51,10 @@ Marquee(value: { start: boolean, step?: number, loop?: number, fromStart?: boole
@Component
struct MarqueeExample {
@State start: boolean = false
@State fromStart: boolean = true
@State step: number = 50
@State loop: number = 3
@State src: string = "Running Marquee starts rolling"
private fromStart: boolean = true
private step: number = 50
private loop: number = Infinity
private src: string = "Running Marquee starts rolling"
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
......@@ -65,29 +65,31 @@ struct MarqueeExample {
fromStart: this.fromStart,
src: this.src
})
.width(400)
.fontColor(Color.White)
.fontSize(50)
.allowScale(false)
.fontWeight(FontWeight.Bold)
.backgroundColor(Color.Black)
.margin({bottom:40})
.width(360)
.height(80)
.fontColor('#FFFFFF')
.fontSize(48)
.fontWeight(700)
.backgroundColor('#182431')
.margin({ bottom: 40 })
.onStart(() => {
console.log('Marquee animation complete onStart')
console.info('Marquee animation complete onStart')
})
.onBounce(() => {
console.log('Marquee animation complete onBounce')
console.info('Marquee animation complete onBounce')
})
.onFinish(() => {
console.log('Marquee animation complete onFinish')
console.info('Marquee animation complete onFinish')
})
Button('start')
Button('Start')
.onClick(() => {
this.start = true
})
.width(200)
.height(60)
.margin({bottom:20})
.width(120)
.height(40)
.fontSize(16)
.fontWeight(500)
.backgroundColor('#007DFF')
}
.width('100%')
.height('100%')
......@@ -95,4 +97,4 @@ struct MarqueeExample {
}
```
![en-us_image_0000001193499234](figures/en-us_image_0000001193499234.gif)
![marquee](figures/marquee.gif)
# NavDestination
**\<NavDestination>** is a child component of the **\<NavRouter>** component and represents a destination in the navigation area.
> **NOTE**
>
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Supported
## APIs
NavDestination()
## Attributes
In addition to the [backgroundColor](ts-universal-attributes-background.md) attribute, the following attributes are supported.
| Name | Type | Description |
| -------------- | ---------------------------------------- | ---------------------------------------- |
| title | string \| [CustomBuilder](ts-types.md#custombuilder8) \| [NavigationCommonTitle](ts-basic-components-navigation.md#navigationcommontitle) \| [NavigationCustomTitle](ts-basic-components-navigation.md##navigationcustomtitle) | Page title. |
| hideTitleBar | boolean | Whether to hide the title bar.<br>Default value: **false**<br>**true**: Hide the title bar.<br>**false**: Display the title bar.|
# Navigation
The **\<Navigation>** component typically functions as the root container of a page and displays the page title, toolbar, and menu based on the attribute settings.
The **\<Navigation>** component typically functions as the root container of a page and displays the title bar, toolbar, and navigation bar based on the attribute settings.
> **NOTE**
>
......@@ -11,12 +11,13 @@ The **\<Navigation>** component typically functions as the root container of a p
Supported
Since API version 9, it is recommended that this component be used together with the **[\<NavRouter>](ts-basic-components-navrouter.md)** component.
## APIs
Navigation()
Creates a component that can automatically display the navigation bar, title, and toolbar based on the attribute settings.
## Attributes
......@@ -24,14 +25,20 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Description |
| -------------- | ---------------------------------------- | ---------------------------------------- |
| title | string \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Page title. |
| subTitle | string | Subtitle of the page. |
| menus | Array<NavigationMenuItem&gt; \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Menu in the upper right corner of the page. |
| titleMode | NavigationTitleMode | Display mode of the page title bar.<br>Default value: **NavigationTitleMode.Free**|
| toolBar | object \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Content of the toolbar.<br>**items**: all items on the toolbar. |
| hideToolBar | boolean | Whether to hide the toolbar.<br>Default value: **false**<br>**true**: Hide the toolbar.<br>**false**: Show the toolbar.|
| hideTitleBar | boolean | Whether to hide the title bar.<br>Default value: **false** |
| hideBackButton | boolean | Whether to hide the back button.<br>Default value: **false** |
| title | string \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> \| [NavigationCommonTitle](#navigationcommontitle)<sup>9+</sup> \| [NavigationCustomTitle](#navigationcustomtitle)<sup>9+</sup> | Page title. |
| subTitle<sup>deprecated</sup> | string | Subtitle of the page. This attribute is deprecated since API version 9. You are advised to use **title** instead. |
| menus | Array<[NavigationMenuItem](#navigationmenuitem)&gt; \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Menu items in the upper right corner of the page. When the value type is Array\<[NavigationMenuItem](#navigationmenuitem)>, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, plus excess icons (if any) under the automatically generated **More** icon. |
| titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.<br>Default value: **NavigationTitleMode.Free**|
| toolBar | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)<sup>8+</sup> | Content of the toolbar.<br>**items**: items on the toolbar. |
| hideToolBar | boolean | Whether to hide the toolbar.<br>Default value: **false**<br>**true**: Hide the toolbar.<br>**false**: Display the toolbar.|
| hideTitleBar | boolean | Whether to hide the title bar.<br>Default value: **false**<br>**true**: Hide the title bar.<br>**false**: Display the title bar.|
| hideBackButton | boolean | Whether to hide the Back key.<br>Default value: **false**<br>**true**: Hide the Back key.<br>**false**: Display the Back key.|
| navBarWidth<sup>9+</sup> | [Length](ts-types.md#length) | Width of the navigation bar.<br>Default value: **200vp**|
| navBarPosition<sup>9+</sup> | [NavBarPosition](#navbarposition) | Position of the navigation bar.<br>Default value: **NavBarPosition.Start**|
| mode<sup>9+</sup> | [NavigationMode](#navigationmode) | Display mode of the navigation bar.<br>Default value: **NavigationMode.Auto**|
| backButtonIcon<sup>9+</sup> | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back icon on the navigation bar.|
| hideNavBar<sup>9+</sup> | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.|
## NavigationMenuItem
......@@ -54,12 +61,49 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Description |
| ---- | ---------------------------------------- |
| Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores when the content scrolls up to the top.|
| Mini | The icon, main title, and subtitle are in mini mode. |
| Full | The main title and subtitle are in full mode. |
| Mini | The title is fixed at mini mode. |
| Full | The title is fixed at full mode. |
## NavigationCommonTitle
| Name | Type | Mandatory| Description |
| ------ | --------- | ---- | -------- |
| main | string | Yes| Main title.|
| sub | string | Yes| Subtitle.|
## NavigationCustomTitle
| Name | Type | Mandatory| Description |
| ------ | ----------------------- | ---- | ------------------------------ |
| builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes| Content of the title bar.|
| height | [TitleHeight](#titleheight) \| [Length](ts-types.md#length) | Yes| Height of the title bar.|
## NavBarPosition
| Name| Description |
| ---- | ---------------------------------------- |
| Start | When two columns are displayed, the main column is at the start of the main axis.|
| End | When two columns are displayed, the main column is at the end of the main axis. |
## NavigationMode
| Name| Description |
| ---- | ---------------------------------------- |
| Stack | The navigation bar and content area are displayed independently of each other, which are equivalent to two pages.|
| Split | The navigation bar and content area are displayed in different columns.|
| Auto | When the window width is greater than or equal to 520 vp, Split mode is used. Otherwise, Stack mode is used.|
## TitleHeight
| Name| Description |
| ---- | ---------------------------------------- |
| MainOnly | Recommended height (56 vp) of the title bar when only the main title is available.|
| MainWithSub | Recommended height (82 vp) of the title bar when both the main title and subtitle exist.|
> **NOTE**
>
> Currently, the scrollable component can only be **\<List>**.
> The scrollable component can only be **\<List>**.
## Events
......@@ -67,6 +111,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Description |
| ---------------------------------------- | ---------------------------------------- |
| onTitleModeChange(callback: (titleMode: NavigationTitleMode) =&gt; void) | Triggered when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.|
| onNavBarStateChange(callback: (isVisible: boolean) =&gt; void) | Triggered when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.|
## Example
......@@ -77,143 +122,114 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
@Component
struct NavigationExample {
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@State hideBar: boolean = true
@Builder NavigationTitle() {
Column() {
Text('title')
.width(80)
.height(60)
.fontColor(Color.Blue)
.fontSize(30)
}
.onClick(() => {
console.log("title")
})
}
@Builder NavigationMenus() {
Row() {
Image('images/add.png')
.width(25)
.height(25)
Image('comment/more.png')
.width(25)
.height(25)
.margin({ left: 30 })
}.width(100)
}
build() {
Column() {
Navigation() {
Search({ value: '', placeholder: "" }).width('85%').margin(26)
List({ space: 5, initialIndex: 0 }) {
ForEach(this.arr, (item) => {
ListItem() {
Text('' + item)
.width('90%')
.height(80)
.backgroundColor('#3366CC')
.borderRadius(15)
.fontSize(16)
.textAlign(TextAlign.Center)
}.editable(true)
}, item => item)
}
.listDirection(Axis.Vertical)
.height(300)
.margin({ top: 10, left: 18 })
.width('100%')
Button(this.hideBar ? "tool bar" : "hide bar")
.onClick(() => {
this.hideBar = !this.hideBar
})
.margin({ left: 135, top: 60 })
}
.title(this.NavigationTitle)
.subTitle('subtitle')
.menus(this.NavigationMenus)
.titleMode(NavigationTitleMode.Free)
.hideTitleBar(false)
.hideBackButton(false)
.onTitleModeChange((titleModel: NavigationTitleMode) => {
console.log('titleMode')
})
.toolBar({ items: [
{ value: 'app', icon: 'images/grid.svg', action: () => {
console.log("app")
} },
{ value: 'add', icon: 'images/add.svg', action: () => {
console.log("add")
} },
{ value: 'collect', icon: 'images/collect.svg', action: () => {
console.log("collect")
} }] })
.hideToolBar(this.hideBar)
}
}
}
```
![en-us_image_0000001256978359](figures/en-us_image_0000001256978359.gif)
```ts
// xxx.ets
@Entry
@Component
struct ToolbarBuilderExample {
@State currentIndex: number = 0
@State Build: Array<Object> = [
{
icon: $r('app.media.ic_public_add'),
icon_after: $r('app.media.ic_public_addcolor'),
text: 'add',
num: 0
},
{
icon: $r('app.media.ic_public_app'),
icon_after: $r('app.media.ic_public_appcolor'),
text: 'app',
num: 1
},
{
icon: $r('app.media.ic_public_collect'),
icon_after: $r('app.media.ic_public_collectcolor'),
text: 'collect',
num: 2
}
]
@Builder NavigationTitle() {
Column() {
Text('Title')
.fontColor('#182431')
.fontSize(30)
.lineHeight(41)
.fontWeight(700)
Text('subtitle')
.fontColor('#182431')
.fontSize(14)
.lineHeight(19)
.opacity(0.4)
.margin({ top: 2 })
}.alignItems(HorizontalAlign.Start)
}
@Builder NavigationMenus() {
Row() {
Image('common/navigation_icon1.svg')
.width(24)
.height(24)
Image('common/navigation_icon1.svg')
.width(24)
.height(24)
.margin({ left: 24 })
Image('common/navigation_icon2.svg')
.width(24)
.height(24)
.margin({ left: 24 })
}
}
@Builder NavigationToolbar() {
Row() {
ForEach(this.Build, item => {
Column() {
Image(this.currentIndex == item.num ? item.icon_after : item.icon)
.width(25)
.height(25)
Image(this.currentIndex == item.num ? 'common/public_icon_selected.svg' : 'common/public_icon.svg')
.width(24)
.height(24)
Text(item.text)
.fontColor(this.currentIndex == item.num ? "#ff7500" : "#000000")
}
.fontColor(this.currentIndex == item.num ? '#007DFF' : '#182431')
.fontSize(10)
.lineHeight(14)
.fontWeight(500)
.margin({ top: 3 })
}.width(104).height(56)
.onClick(() => {
this.currentIndex = item.num
})
.margin({ left: 70 })
})
}
}.margin({ left: 24 })
}
build() {
Column() {
Navigation() {
Flex() {
TextInput({ placeholder: 'search...' })
.width(336)
.height(40)
.backgroundColor('#FFFFFF')
.margin({ top: 8, left: 12 })
List({ space: 12, initialIndex: 0 }) {
ForEach(this.arr, (item) => {
ListItem() {
Text('' + item)
.width(336)
.height(72)
.backgroundColor('#FFFFFF')
.borderRadius(24)
.fontSize(16)
.fontWeight(500)
.textAlign(TextAlign.Center)
}.editable(true)
}, item => item)
}
.height(324)
.width('100%')
.margin({ top: 12, left: 12 })
}
.title(this.NavigationTitle)
.menus(this.NavigationMenus)
.titleMode(NavigationTitleMode.Full)
.toolBar(this.NavigationToolbar)
}
.hideTitleBar(false)
.hideToolBar(false)
.onTitleModeChange((titleModel: NavigationTitleMode) => {
console.info('titleMode' + titleModel)
})
}.width('100%').height('100%').backgroundColor('#F1F3F5')
}
}
```
![en-us_image_0000001212058484](figures/en-us_image_0000001212058484.gif)
![en-us_image_0000001192655288](figures/en-us_image_0000001192655288.gif)
# NavRouter
The **\<NavRouter>** component provides default logic for click response processing, eliminating the need for manual logic definition.
> **NOTE**
>
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
This component must contain two child components, the second of which must be **[\<NavDestination>](ts-basic-components-navdestination.md)**.
## APIs
NavRouter()
## Events
| Name | Description |
| ------------------------------------------------------- | ------------------------------------------------------------ |
| onStateChange(callback: (isActivated: boolean) => void) | Invoked when the component activation status changes. The value **true** means that component is activated, and **false** means the opposite.<br>**NOTE**<br>After the user clicks **NavRouter**, if the **\<NavRouter>** component is activated and the corresponding **\<NavDestination>** child component loaded, **onStateChange(true)** is called. If the corresponding **\<NavDestination>** child component is no longer displayed, **onStateChange(false)** is called. |
......@@ -77,6 +77,7 @@ Pushes the component and data to the component user.
| name | string | Yes | Component name. |
| data | KVObject | No | Component data value. |
| extraData | KVObject | No | Additional data value. |
| jsonPath | string | No | Path of the **external.json** file that stores template paths. |
**Example**
......@@ -103,6 +104,7 @@ Requests the component from the component provider.
| want | Want | Yes | Ability information of the component provider.|
| name | string | Yes | Name of the requested component. |
| data | KVObject | Yes | Additional data. |
| jsonPath | string | No | Path of the **external.json file** that stores template paths. If this parameter is not null or not set, request communication is not triggered. |
**RequestCallbackParameters**
......@@ -112,12 +114,6 @@ Requests the component from the component provider.
| data | KVObject | Component data.|
| extraData | KVObject | Additional data.|
**KVObject**
| Name | Type | Description |
| ---- | ---------------------------------------- | ---------------------------------------- |
| key | number \| string \| boolean \| Array \| KVObject | Key of the **KVObject**. **KVObject** uses **key** and **value** to store data. If **key** is of the string type, **value** can be of the number, string, boolean, array type or another **KVObject**.|
**Example**
For details, see [PluginComponent User](#plugincomponent-user).
......@@ -155,6 +151,20 @@ Listens for events of the request type and returns the requested data, or listen
For details, see [PluginComponent Tools](#plugincomponent-tools).
**KVObject**
| Name | Type | Description |
| ---- | ---------------------------------------- | ---------------------------------------- |
| key | number \| string \| boolean \| Array \| KVObject | Key of the **KVObject**. **KVObject** uses **key** and **value** to store data. If **key** is of the string type, **value** can be of the number, string, boolean, array type or another **KVObject**.|
**Description of the external.json file**
The **external.json** file is created by developers. This file stores component names and template paths in key-value pairs. The component name is the key, and the corresponding template path is the value.
**Example**
For details, see [external.json](#externaljson).
## Example
......@@ -347,3 +357,11 @@ export default {
}
}
```
### external.json
```json
{
"plugintemplate": "ets/pages/plugintemplate.js",
"plugintemplate2": "ets/pages/plugintemplate2.js"
}
......@@ -22,38 +22,39 @@ Creates a progress indicator.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | number | Yes| Current progress.|
| value | number | Yes| Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used.|
| total | number | No| Total progress.<br>Default value: **100**|
| type<sup>8+</sup> | ProgressType | No| Type of the progress indicator.<br>Default value: **ProgressType.Linear**|
| style<sup>deprecated</sup> | ProgressStyle | No| Style the progress indicator.<br>This parameter is deprecated since API version 8. You are advised to use **type** instead.<br>Default value: **ProgressStyle.Linear**|
| type<sup>8+</sup> | [ProgressType](#progresstype) | No| Style the progress indicator.<br>Default value: **ProgressType.Linear**|
| style<sup>deprecated</sup> | [ProgressStyle](#progressstyle) | No| Type of the progress indicator.<br>This parameter is deprecated since API version 8. You are advised to use **type** instead.<br>Default value: **ProgressStyle.Linear**|
## ProgressType
| Name| Description|
| -------- | -------- |
| Linear | Linear type.|
| Linear | Linear type. Since API version 9, the progress indicator adaptively switches to vertical layout if the height is greater than the width.|
| Ring<sup>8+</sup> | Indeterminate ring type. The ring fills up as the progress increases.|
| Eclipse<sup>8+</sup> | Eclipse type, which visualizes the progress in a way similar to the moon waxing from new to full.|
| ScaleRing<sup>8+</sup> | Determinate ring type, which is similar to the clock scale.|
| Capsule<sup>8+</sup> | Capsule type. At both ends, the progress indicator works in a same manner as the eclipse type. In the middle part of the capsule, the progress indicator works in a same manner as the linear type.|
| ScaleRing<sup>8+</sup> | Determinate ring type, which is similar to the clock scale. Since API version 9, when the outer circles of scales overlap, the progress indicator is automatically converted to the **Ring** type.|
| Capsule<sup>8+</sup> | Capsule type. At both ends, the progress indicator works in a same manner as the eclipse type. In the middle part of the capsule, the progress indicator works in a same manner as the linear type. If the height is greater than the width, the progress indicator adaptively switches to vertical layout.|
## ProgressStyle
| Name | Description |
| --------- | ------------------------------------------------------------ |
| Linear | Linear type. |
| Ring | Indeterminate ring type. The ring fills up as the progress increases. |
| Linear | Linear type.|
| Ring | Indeterminate ring type. The ring fills up as the progress increases.|
| Eclipse | Eclipse type, which visualizes the progress in a way similar to the moon waxing from new to full.|
| ScaleRing | Determinate ring type, which is similar to the clock scale. |
| Capsule | Capsule type. At both ends, the progress indicator works in a same manner as the eclipse type. In the middle part of the capsule, the progress indicator works in a same manner as the linear type.|
| ScaleRing | Determinate ring type, which is similar to the clock scale.|
| Capsule | Capsule type. At both ends, the progress indicator works in a same manner as the eclipse type. In the middle part of the capsule, the progress indicator works in a same manner as the linear type. If the height is greater than the width, the progress indicator adaptively switches to vertical layout.|
## Attributes
| Name| Type| Description|
| -------- | -------- | -------- |
| value | number | Current progress.|
| value | number | Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used. Invalid values do not take effect.|
| color | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.|
| style<sup>8+</sup> | {<br>strokeWidth?: [Length](ts-types.md#length),<br>scaleCount?: number,<br>scaleWidth?: [Length](ts-types.md#length)<br>} | Component style.<br>- **strokeWidth**: stroke width of the progress indicator.<br>- **scaleCount**: number of divisions on the determinate ring-type process indicator.<br>- **scaleWidth**: scale bar width of the determinate ring-type process indicator. If it is greater than the progress indicator width, the default value is used instead.|
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.|
| style<sup>8+</sup> | {<br>strokeWidth?: [Length](ts-types.md#length),<br>scaleCount?: number,<br>scaleWidth?: [Length](ts-types.md#length)<br>} | Component style.<br>- **strokeWidth**: stroke width of the progress indicator. It cannot be set in percentage. Since API version 9, if the stroke width of the ring progress bar is greater than or equal to the radius, the width is changed to half of the radius.<br>Default value: **4.0Vp**<br>- **scaleCount**: number of divisions on the determinate ring-type process indicator.<br>Default value: **120**<br>- **scaleWidth**: scale width of the ring progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.<br>Default value: **2.0Vp**|
## Example
......@@ -69,6 +70,7 @@ struct ProgressExample {
Progress({ value: 10, type: ProgressType.Linear }).width(200)
Progress({ value: 20, total: 150, type: ProgressType.Linear }).color(Color.Grey).value(50).width(200)
Text('Eclipse Progress').fontSize(9).fontColor(0xCCCCCC).width('90%')
Row({ space: 40 }) {
Progress({ value: 10, type: ProgressType.Eclipse }).width(100)
......@@ -83,6 +85,16 @@ struct ProgressExample {
.style({ strokeWidth: 15, scaleCount: 15, scaleWidth: 5 })
}
// scaleCount vs. scaleWidth
Row({ space: 40 }) {
Progress({ value: 20, total: 150, type: ProgressType.ScaleRing })
.color(Color.Grey).value(50).width(100)
.style({ strokeWidth: 20, scaleCount: 20, scaleWidth: 5 })
Progress({ value: 20, total: 150, type: ProgressType.ScaleRing })
.color(Color.Grey).value(50).width(100)
.style({ strokeWidth: 20, scaleCount: 30, scaleWidth: 3 })
}
Text('Ring Progress').fontSize(9).fontColor(0xCCCCCC).width('90%')
Row({ space: 40 }) {
Progress({ value: 10, type: ProgressType.Ring }).width(100)
......@@ -105,4 +117,4 @@ struct ProgressExample {
}
```
![en-us_image_0000001212378432](figures/en-us_image_0000001212378432.gif)
![progress](figures/progress.png)
......@@ -21,7 +21,7 @@ Rating(options?: { rating: number, indicator?: boolean })
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| rating | number | Yes| Value to rate.<br>Default value: **0**|
| indicator | boolean | No| Used only as an indicator and cannot be operated.<br>Default value: **false**|
| indicator | boolean | No| Whether the component is used only as an indicator and cannot be operated.<br>Default value: **false**|
## Attributes
......@@ -47,21 +47,51 @@ Rating(options?: { rating: number, indicator?: boolean })
@Entry
@Component
struct RatingExample {
@State rating: number = 1
@State indicator: boolean = false
@State rating: number = 3.5
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Text('current score is ' + this.rating).fontSize(20)
Rating({ rating: this.rating, indicator: this.indicator })
Column() {
Column() {
Rating({ rating: this.rating, indicator: false })
.stars(5)
.stepSize(0.5)
.margin({ top: 24 })
.onChange((value: number) => {
this.rating = value
})
}.width(350).height(200).padding(35)
Text('current score is ' + this.rating)
.fontSize(16)
.fontColor('rgba(24,36,49,0.60)')
.margin({ top: 16 })
}.width(360).height(113).backgroundColor('#FFFFFF').margin({ top: 68 })
Row() {
Image('common/testImage.jpg')
.width(40)
.height(40)
.borderRadius(20)
.margin({ left: 24 })
Column() {
Text('Yue')
.fontSize(16)
.fontColor('#182431')
.fontWeight(500)
Row() {
Rating({ rating: 3.5, indicator: true }).margin({ top: 1, right: 8 })
Text('2021/06/02')
.fontSize(10)
.fontColor('#182431')
}
}.margin({ left: 12 }).alignItems(HorizontalAlign.Start)
Text('1st Floor')
.fontSize(10)
.fontColor('#182431')
.position({ x: 295, y: 8 })
}.width(360).height(56).backgroundColor('#FFFFFF').margin({ top: 64 })
}.width('100%').height('100%').backgroundColor('#F1F3F5')
}
}
```
![en-us_image_0000001257058423](figures/en-us_image_0000001257058423.gif)
![rating](figures/rating.gif)
......@@ -39,12 +39,13 @@ RichText(content:string)
| \<p>\</p> | Defines a paragraph.| \<p>This is a paragraph\</p>|
| \<br/> | Inserts a newline character.| \<p>This is a paragraph\<br/>This is a new paragraph\</p>|
| \<hr/> | Defines a thematic break (such as a shift of topic) on an HTML page and creates a horizontal line.| \<p>This is a paragraph\</p>\<hr/>\<p>This is a paragraph\</p> |
| \<image>\</image> | Defines an image.| \<image src="file:///data/storage/el1/bundle/entry/resources/rawfile/icon.png">\</image> |
| \<div>\</div> | Defines a generic container that is generally used to group block-level elements. It allows you to apply CSS styles to multiple elements at the same time.| \<div style='color:#0000FF'>\<h3>This is the heading in a div element\</h3>\</div> |
| \<i>\</i> | Displays text in italic style.| \<i>This is in italic style\</i>|
| \<u>\</u> | Defines text that should be styled differently or have a non-textual annotation, such as misspelt words or a proper name in Chinese text. It is recommended that you avoid using the \<u> tag where it could be confused with a hyperlink.| \<p>\<u>This is an underlined paragraph\</u>\</p> |
| \<style>\</style> | Used to embed CSS within an HTML document.| \<style>h1{color:red;}p{color:blue;}\</style> |
| style | Defines the inline style of an element and is placed inside the tag. Use quotation marks (') to separate the styling text and use semicolons (;) to separate styles, for example, **style='width: 500px;height: 500px;border: 1px solid;margin: 0 auto;'**.| \<h1 style='color:blue;text-align:center'>This is a heading\</h1>\<p style='color:green'>This is a paragraph\</p> |
| \<script>\</script> | Used to embed or reference a client-side script, such as JavaScript.| \<script>document.write("Hello World!")\</script> |
| \<script>\</script> | Embeds or references a client-side script, such as JavaScript. | \<script>document.write("Hello World!")\</script> |
## Example
......
......@@ -12,9 +12,9 @@ Not supported
## APIs
Select(options: Array\<SelectOption\>)
Select(options: Array\<[SelectOption](#selectoption)\>)
**SelectOption**
## SelectOption
| Name| Type | Mandatory| Description |
| ------ | ----------------------------------- | ---- | -------------- |
......@@ -39,8 +39,8 @@ Select(options: Array\<SelectOption\>)
## 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. |
| ----------------------------------------------------------- | ------------------------------------------------------------ |
| 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%')
}
}
```
......
......@@ -23,7 +23,7 @@ Slider(options?: {value?: number, min?: number, max?: number, step?: number, sty
| value | number | No| Current progress.<br>Default value: **0**|
| min | number | No| Minimum value.<br>Default value: **0**|
| max | number | No| Maximum value.<br>Default value: **100**|
| step | number | No| Step of the slider.<br>Default value: **1**|
| step | number | No| Step of the slider.<br>Default value: **1**<br>Value range: [0.01, max]|
| style | SliderStyle | No| Style of the slider thumb and track.<br>Default value: **SliderStyle.OutSet**|
| direction<sup>8+</sup> | [Axis](ts-appendix-enums.md#axis) | No| Whether the slider moves horizontally or vertically.<br>Default value: **Axis.Horizontal**|
| reverse<sup>8+</sup> | boolean | No| Whether the slider values are reversed. By default, the values increase from left to right for a horizontal slider and from top to bottom for a vertical slider.<br>Default value: **false**|
......@@ -46,7 +46,7 @@ Except touch target attributes, the universal attributes are supported.
| trackColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the slider.|
| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the selected part of the slider track.|
| showSteps | boolean | Whether to display the current step.<br>Default value: **false**|
| showTips | boolean | Whether to display a bubble to indicate the percentage when the user drags the slider.<br>Default value: **false** |
| showTips | boolean | Whether to display a bubble to indicate the percentage when the user drags the slider.<br>Default value: **false**|
| trackThickness | [Length](ts-types.md#length) | Track thickness of the slider.|
......@@ -223,4 +223,4 @@ struct SliderExample {
}
```
![en-us_image_0000001211898492](figures/en-us_image_0000001211898492.gif)
![en-us_image_0000001179613854](figures/en-us_image_0000001179613854.gif)
......@@ -45,6 +45,22 @@ None
```ts
// xxx.ets
@Styles function itemStyle () {
.width(336)
.height(621)
.margin({ top: 48, left: 12 })
.borderRadius(24)
.backgroundColor('#FFFFFF')
}
@Extend(Text) function itemTextStyle () {
.fontColor('#182431')
.fontSize(36)
.fontWeight(500)
.opacity(0.4)
.margin({ top: 82, bottom: 40 })
}
@Entry
@Component
struct StepperExample {
......@@ -61,15 +77,13 @@ struct StepperExample {
StepperItem() {
Column() {
Text('Page One')
.fontSize(35)
.fontColor(Color.Blue)
.lineHeight(50)
.margin({ top: 250, bottom: 50 })
.itemTextStyle()
Button('change status:' + this.firstState)
.backgroundColor('#007dFF')
.onClick(() => {
this.firstState = this.firstState === ItemState.Skip ? ItemState.Normal : ItemState.Skip
})
}.width('100%')
}.itemStyle()
}
.nextLabel('Next')
.status(this.firstState)
......@@ -77,15 +91,13 @@ struct StepperExample {
StepperItem() {
Column() {
Text('Page Two')
.fontSize(35)
.fontColor(Color.Blue)
.lineHeight(50)
.margin({ top: 250, bottom: 50 })
.itemTextStyle()
Button('change status:' + this.secondState)
.backgroundColor('#007dFF')
.onClick(() => {
this.secondState = this.secondState === ItemState.Disabled ? ItemState.Normal : ItemState.Disabled
})
}.width('100%')
}.itemStyle()
}
.nextLabel('Next')
.prevLabel('Previous')
......@@ -94,29 +106,25 @@ struct StepperExample {
StepperItem() {
Column() {
Text('Page Three')
.fontSize(35)
.fontColor(Color.Blue)
.lineHeight(50)
.margin({ top: 250, bottom: 50 })
.itemTextStyle()
Button('change status:' + this.thirdState)
.backgroundColor('#007dFF')
.onClick(() => {
this.thirdState = this.thirdState === ItemState.Waiting ? ItemState.Normal : ItemState.Waiting
})
}.width('100%')
}.itemStyle()
}
.status(this.thirdState)
// Fourth step page
StepperItem() {
Text('Page four')
.fontSize(35)
.fontColor(Color.Blue)
.width('100%')
.textAlign(TextAlign.Center)
.lineHeight(50)
.margin({ top: 250 })
Column() {
Text('Page Four')
.itemTextStyle()
}.itemStyle()
}
.nextLabel('Finish')
}
.backgroundColor('#F1F3F5')
.onFinish(() => {
// Define the processing logic for when Finish on the last page is clicked, for example, redirection.
console.info('onFinish')
......@@ -133,4 +141,4 @@ struct StepperExample {
```
![en-us_image_0000001250678457](figures/en-us_image_0000001250678457.gif)
![stepper](figures/stepper.gif)
......@@ -85,23 +85,29 @@ struct TextAreaExample {
build() {
Column() {
TextArea({ placeholder: 'The text area can hold an unlimited amount of text. input your word', controller: this.controller })
.placeholderFont({ size: 14, weight: 400 })
.width(400)
.height(50)
TextArea({
placeholder: 'The text area can hold an unlimited amount of text. input your word...',
controller: this.controller
})
.placeholderFont({ size: 16, weight: 400 })
.width(336)
.height(56)
.margin(20)
.fontSize(14)
.fontSize(16)
.fontColor('#182431')
.backgroundColor('#FFFFFF')
.onChange((value: string) => {
this.text = value
})
Text(this.text)
Button('Set caretPosition 1')
.backgroundColor('#007DFF')
.margin(15)
.onClick(() => {
// Move the caret to after the first entered character.
this.controller.caretPosition(1)
})
}.width('100%')
}.width('100%').height('100%').backgroundColor('#F1F3F5')
}
}
```
......
# 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)
......@@ -6,41 +6,37 @@ The **\<TextTimer>** component displays timing information and is controlled in
>
> 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()
})
}
}
}
......
......@@ -6,12 +6,6 @@ The **\<Toggle>** component provides a clickable element in the check box, butto
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components
This component can contain child components only when **ToggleType** is set to **Button**.
......@@ -21,27 +15,28 @@ This component can contain child components only when **ToggleType** is set to *
Toggle(options: { type: ToggleType, isOn?: boolean })
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | ToggleType | Yes| Type of the toggle.|
| isOn | boolean | No| Whether the toggle is turned on. The value **true** means that the toggle is turned on, and **false** means the opposite.<br/>Default value: **false** |
**Parameters**
| Name| Type| Mandatory | Description |
| ---- | ---------- | -----| -------------- |
| type | [ToggleType](#toggletype) | Yes | Type of the toggle.|
| isOn | boolean | No | Whether the toggle is turned on. The value **true** means that the toggle is turned on, and **false** means the opposite.<br>Default value: **false**|
- ToggleType enums
| Name| Description|
| -------- | -------- |
| Checkbox | Check box type.<br>> **NOTE**<br>> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 14 vp,<br> right: 6 vp,<br> bottom: 14 vp,<br> left: 6 vp<br> } |
| Button | Button type. The set string, if any, will be displayed inside the button. |
| Switch | Switch type.<br>> **NOTE**<br>> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 12 vp,<br> right: 12 vp,<br> bottom: 12 vp,<br> left: 12 vp<br> } |
## ToggleType
| Name | Description |
| -------- | ---------------- |
| Checkbox | Check box type.<br>> **NOTE**<br>> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 14 vp,<br> right: 6 vp,<br> bottom: 14 vp,<br> left: 6 vp<br> } |
| Button | Button type. The set string, if any, will be displayed inside the button. |
| Switch | Switch type.<br>> **NOTE**<br>> The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows:<br>{<br> top: 12 vp,<br> right: 12 vp,<br> bottom: 12 vp,<br> left: 12 vp<br> } |
## Attributes
| Name| Parameter| Default Value| Description|
| -------- | -------- | -------- | -------- |
| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | - | Background color of the component when it is turned on.|
| switchPointColor | [ResourceColor](ts-types.md#resourcecolor) | - | Color of the circular slider when the component is of the **Switch** type.<br>> **NOTE**<br>> This attribute is valid only when **type** is set to **ToggleType.Switch**.|
| Name | Parameter | Description |
| ---------------- | --------------------------- | ---------------------- |
| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component when it is turned on.|
| switchPointColor | [ResourceColor](ts-types.md#resourcecolor) | Color of the circular slider when the component is of the **Switch** type.<br>> **NOTE**<br>> This attribute is valid only when **type** is set to **ToggleType.Switch**.|
## Events
......@@ -58,21 +53,20 @@ Toggle(options: { type: ToggleType, isOn?: boolean })
@Entry
@Component
struct ToggleExample {
build() {
Column({ space: 10 }) {
Text('type: Switch').fontSize(12).fontColor(0xcccccc).width('90%')
Flex({ justifyContent: FlexAlign.SpaceEvenly, alignItems: ItemAlign.Center }) {
Toggle({ type: ToggleType.Switch, isOn: false })
.selectedColor(0xed6f21)
.switchPointColor(0xe5ffffff)
.selectedColor('#007DFF')
.switchPointColor('#FFFFFF')
.onChange((isOn: boolean) => {
console.info('Component status:' + isOn)
})
Toggle({ type: ToggleType.Switch, isOn: true })
.selectedColor(0x39a2db)
.switchPointColor(0xe5ffffff)
.selectedColor('#007DFF')
.switchPointColor('#FFFFFF')
.onChange((isOn: boolean) => {
console.info('Component status:' + isOn)
})
......@@ -81,15 +75,15 @@ struct ToggleExample {
Text('type: Checkbox').fontSize(12).fontColor(0xcccccc).width('90%')
Flex({ justifyContent: FlexAlign.SpaceEvenly, alignItems: ItemAlign.Center }) {
Toggle({ type: ToggleType.Checkbox, isOn: false })
.size({ width: 28, height: 28 })
.selectedColor(0xed6f21)
.size({ width: 20, height: 20 })
.selectedColor('#007DFF')
.onChange((isOn: boolean) => {
console.info('Component status:' + isOn)
})
Toggle({ type: ToggleType.Checkbox, isOn: true })
.size({ width: 28, height: 28 })
.selectedColor(0x39a2db)
.size({ width: 20, height: 20 })
.selectedColor('#007DFF')
.onChange((isOn: boolean) => {
console.info('Component status:' + isOn)
})
......@@ -98,17 +92,17 @@ struct ToggleExample {
Text('type: Button').fontSize(12).fontColor(0xcccccc).width('90%')
Flex({ justifyContent: FlexAlign.SpaceEvenly, alignItems: ItemAlign.Center }) {
Toggle({ type: ToggleType.Button, isOn: false }) {
Text('status button').padding({ left: 12, right: 12 })
}
.selectedColor(0xed6f21)
Text('status button').fontColor('#182431').fontSize(12)
}.width(106)
.selectedColor('rgba(0,125,255,0.20)')
.onChange((isOn: boolean) => {
console.info('Component status:' + isOn)
})
Toggle({ type: ToggleType.Button, isOn: true }) {
Text('status button').padding({ left: 12, right: 12 })
}
.selectedColor(0x39a2db)
Text('status button').fontColor('#182431').fontSize(12)
}.width(106)
.selectedColor('rgba(0,125,255,0.20)')
.onChange((isOn: boolean) => {
console.info('Component status:' + isOn)
})
......@@ -118,4 +112,4 @@ struct ToggleExample {
}
```
![en-us_image_0000001211898522](figures/en-us_image_0000001211898522.gif)
![toggle](figures/toggle.gif)
因为 它太大了无法显示 source diff 。你可以改为 查看blob
......@@ -8,8 +8,9 @@ The **\<XComponent>** can accept and display the EGL/OpenGL ES and media data in
## Child Components
Child components are not supported when **type** is set to **"surface"**.
Not supported
Since API version 9, child components are supported when **type** is set to **"component"**.
## APIs
......@@ -18,14 +19,34 @@ XComponent(value: {id: string, type: string, libraryname?: string, controller?:
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ----- |
| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters.|
| type | string | Yes | Type of the component. The options are as follows:<br>- **surface**: The content of this component is displayed individually, without being combined with that of other components.<br>- **component**: The content of this component is displayed after having been combined with that of other components. |
| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer.|
| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component.|
| ----------- | ---------------------------------------- | ---- | ---------------------------------------- |
| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters. |
| type | string | Yes | Type of the component. The options are as follows:<br>- **"surface"**: The content of the component is displayed individually, without being combined with that of other components. This option is used for displaying EGL/OpenGL ES and media data.<br>- **"component"**<sup>9+</sup>: The component becomes a container where non-UI logic can be executed to dynamically load the display content.|
| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer. This parameter is valid only when the component type is **"surface"**.|
| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component. This parameter is valid only when the component type is **"surface"**.|
> **NOTE**
>
> When **type** is set to **"component"**, the **\<XComponent>** functions as a container, where child components are laid out vertically.
>
> - Vertical alignment: [FlexAlign](ts-appendix-enums.md#flexalign).Start
> - Horizontal alignment: [FlexAlign](ts-appendix-enums.md#flexalign).Center
>
> The component does not respond to any events.
>
> Layout changes and event responses can be set by mounting child components.
>
> The non-UI logic written internally needs to be encapsulated in one or more functions.
## Attributes
- You can customize the content displayed in the **\<XComponent>**. Among the universal attributes, the [background](./ts-universal-attributes-background.md), [opacity](./ts-universal-attributes-opacity.md), and [image effects](./ts-universal-attributes-image-effect.md) attributes are not supported.
- When **type** is set to **"surface"**, you are advised to use the APIs provided by the EGL/OpenGL ES to set the display content.
- When **type** is set to **"component"**, you are advised to mount child components to set the display content.
## Events
The following events are supported only when **type** is set to **"surface"**. The [universal events](ts-universal-events-click.md) and [universal gestures](ts-gesture-settings.md) are not supported.
### onLoad
onLoad(callback: (event?: object) => void )
......@@ -35,7 +56,7 @@ Triggered when the plug-in is loaded.
**Parameters**
| Name | Type | Mandatory | Description |
| ------------- | ------ | ---- | ----------------------- |
| ----- | ------ | ---- | ---------------------------------------- |
| event | object | No | Context of the **\<XComponent>** object. The APIs contained in the context are defined at the C++ layer by developers.|
### onDestroy
......@@ -46,7 +67,7 @@ Triggered when the plug-in is destroyed.
## XComponentController
Defines the controller of the **\<XComponent>**. You can bind the controller to the **\<XComponent>** to invoke the component methods through the controller.
Defines the controller of the **\<XComponent>**. You can bind the controller to the **\<XComponent>** to invoke the methods of the component through the controller.
### Creating an Object
......@@ -56,11 +77,10 @@ xcomponentController: XComponentController = new XComponentController()
### getXComponentSurfaceId
getXComponentSurfaceId()
getXComponentSurfaceId(): string
Obtains the ID of the surface held by the **\<XComponent>**. The ID can be used for @ohos interfaces, such as camera-related interfaces.
Obtains the ID of the surface held by the **\<XComponent>**. The ID can be used for @ohos interfaces. For details, see [Camera Management](../apis/js-apis-camera.md). This API works only when **type** of the **\<XComponent>** is set to **"surface"**.
**System API**: This is a system API.
**Return value**
......@@ -71,11 +91,10 @@ Obtains the ID of the surface held by the **\<XComponent>**. The ID can be used
### setXComponentSurfaceSize
setXComponentSurfaceSize(value: {surfaceWidth: number, surfaceHeight: number})
setXComponentSurfaceSize(value: {surfaceWidth: number, surfaceHeight: number}): void
Sets the width and height of the surface held by the **\<XComponent>**.
Sets the width and height of the surface held by the **\<XComponent>**. This API works only when **type** of the **\<XComponent>** is set to **"surface"**.
**System API**: This is a system API.
**Parameters**
......@@ -87,9 +106,9 @@ Sets the width and height of the surface held by the **\<XComponent>**.
### getXComponentContext
getXComponentContext()
getXComponentContext(): Object
Obtains the context of an **\<XComponent>** object.
Obtains the context of an **\<XComponent>** object. This API works only when **type** of the **\<XComponent>** is set to **"surface"**.
**Return value**
......@@ -100,12 +119,10 @@ Obtains the context of an **\<XComponent>** object.
## Example
Provide a surface-type **\<XComponent>** to support capabilities such as camera preview.
You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer.
```ts
// xxx.ets
import camera from '@ohos.multimedia.camera'
@Entry
@Component
struct PreviewArea {
......@@ -121,9 +138,6 @@ struct PreviewArea {
.onLoad(() => {
this.xcomponentController.setXComponentSurfaceSize({surfaceWidth:1920,surfaceHeight:1080});
this.surfaceId = this.xcomponentController.getXComponentSurfaceId()
camera.createPreviewOutput(this.surfaceId).then((previewOutput) => {
console.log('Promise returned with the PreviewOutput instance')
})
})
.width('640px')
.height('480px')
......
......@@ -19,9 +19,9 @@ PanGesture(value?: { fingers?: number; direction?: PanDirection; distance?: numb
| -------- | -------- | -------- | -------- |
| fingers | number | No| Minimum number of fingers to trigger a pan gesture. The value ranges from 1 to 10.<br>Default value: **1**|
| direction | PanDirection | No| Pan direction. The enumerated value supports the AND (&amp;) and OR (\|) operations.<br>Default value: **PanDirection.All**|
| distance | number | No| Minimum pan distance to trigger the gesture, in vp.<br>Default value: **5**<br>**NOTE**<br>If a pan gesture and tab swipe occur at the same time, set **distance** to **1** so that the gesture can be more easily recognized.|
| distance | number | No| Minimum pan distance to trigger the gesture, in vp.<br>Default value: **5**<br>**NOTE**<br>If a pan gesture and [tab](ts-container-tabs.md) swipe occur at the same time, set **distance** to **1** so that the gesture can be more easily recognized.|
## PanDirection enums
## PanDirection
| Name| Description|
| -------- | -------- |
......@@ -47,7 +47,7 @@ PanGestureOptions(value?: { fingers?: number; direction?: PanDirection; distance
| --------- | ------------ | ---- | ------------------------------------------------------------ |
| fingers | number | No | Minimum number of fingers to trigger a pan gesture. The value ranges from 1 to 10.<br>Default value: **1**|
| direction | PanDirection | No | Pan direction. The enumerated value supports the AND (&amp;) and OR (\|) operations.<br>Default value: **All**|
| distance | number | No | Minimum pan distance to trigger the gesture, in vp.<br>Default value: **5.0**<br>**NOTE**<br>If a pan gesture and tab swipe occur at the same time, set **distance** to **1** so that the gesture can be more easily recognized.|
| distance | number | No | Minimum pan distance to trigger the gesture, in vp.<br>Default value: **5.0**<br>**NOTE**<br>If a pan gesture and [tab](ts-container-tabs.md) swipe occur at the same time, set **distance** to **1** so that the gesture can be more easily recognized.|
**APIs**
......@@ -126,6 +126,6 @@ Pannig to the left:
![en-us_image_0000001174264374](figures/en-us_image_0000001174264374.png)
Click Set PanGesture Trigger Condition to two fingers moving toward the lower left corner.
Click **Set PanGesture Trigger Condition** to two fingers moving toward the lower left corner.
![en-us_image1_0000001174264374](figures/en-us_image1_0000001174264374.png)
......@@ -7,11 +7,6 @@ Continuous recognition, parallel recognition, and exclusive recognition are supp
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## APIs
GestureGroup(mode: GestureMode, ...gesture: GestureType[])
......@@ -19,15 +14,15 @@ GestureGroup(mode: GestureMode, ...gesture: GestureType[])
- Parameters
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| mode | GestureMode | Yes| - | Recognition mode of combined gestures.|
| mode | [GestureMode](#gesturemode) | Yes| - | Recognition mode of combined gestures.|
| gesture | [TapGesture](ts-basic-gestures-tapgesture.md)<br>\| [LongPressGesture](ts-basic-gestures-longpressgesture.md)<br>\| [PanGesture](ts-basic-gestures-pangesture.md)<br>\| [PinchGesture](ts-basic-gestures-pinchgesture.md)<br>\| [RotationGesture](ts-basic-gestures-rotationgesture.md) | Yes| - | Variable-length parameter, indicating one or more basic gesture types. These gestures are recognized in combination.|
- GestureMode enums
| Name| Description|
| -------- | -------- |
| Sequence | Sequential recognition: Gestures are recognized in the registration sequence until all gestures are recognized successfully. When one gesture fails to be recognized, all gestures fail to be recognized.|
| Parallel | Parallel recognition. Registered gestures are recognized concurrently until all gestures are recognized. The recognition result of each gesture does not affect each other.|
| Exclusive | Exclusive recognition. Registered gestures are identified concurrently. If one gesture is successfully recognized, gesture recognition ends.|
## GestureMode
| Name| Description|
| -------- | -------- |
| Sequence | Sequential recognition: Gestures are recognized in the registration sequence until all gestures are recognized successfully. When one gesture fails to be recognized, all gestures fail to be recognized.|
| Parallel | Parallel recognition. Registered gestures are recognized concurrently until all gestures are recognized. The recognition result of each gesture does not affect each other.|
| Exclusive | Exclusive recognition. Registered gestures are identified concurrently. If one gesture is successfully recognized, gesture recognition ends.|
## Events
......@@ -47,40 +42,64 @@ struct GestureGroupExample {
@State count: number = 0
@State offsetX: number = 0
@State offsetY: number = 0
@State positionX: number = 0
@State positionY: number = 0
@State borderStyles: BorderStyle = BorderStyle.Solid
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Column() {
Text('sequence gesture\n' + 'LongPress onAction:' + this.count + '\nPanGesture offset:\nX: ' + this.offsetX + '\n' + 'Y: ' + this.offsetY)
}.translate({ x: this.offsetX, y: this.offsetY, z: 5 })
.height(100).width(200).padding(10).margin(80).border({ width: 1, style: this.borderStyles })
}
.translate({ x: this.offsetX, y: this.offsetY, z: 0 })
.height(150)
.width(200)
.padding(20)
.margin(20)
.border({ width: 3, style: this.borderStyles })
.gesture(
// The following combined gestures are recognized in sequential recognition mode. If the long press gesture event is not triggered correctly, the drag gesture event will not be triggered.
GestureGroup(GestureMode.Sequence,
LongPressGesture({ repeat: true })
.onAction((event: GestureEvent) => {
if (event.repeat) {this.count++}
console.log('LongPress onAction')
if (event.repeat) {
this.count++
}
console.info('LongPress onAction')
})
.onActionEnd(() => {
console.log('LongPress end')
console.info('LongPress end')
}),
PanGesture({})
PanGesture()
.onActionStart(() => {
this.borderStyles = BorderStyle.Dashed
console.log('pan start')
console.info('pan start')
})
.onActionUpdate((event: GestureEvent) => {
this.offsetX = event.offsetX
this.offsetY = event.offsetY
console.log('pan update')
this.offsetX = this.positionX + event.offsetX
this.offsetY = this.positionY + event.offsetY
console.info('pan update')
})
.onActionEnd(() => {
this.positionX = this.offsetX
this.positionY = this.offsetY
this.borderStyles = BorderStyle.Solid
console.info('pan end')
})
)
.onCancel(() => {
console.log('sequence gesture canceled')
console.info('sequence gesture canceled')
})
)
}
}
```
![en-us_image_0000001212058490](figures/en-us_image_0000001212058490.gif)
Diagram:
In sequence recognition mode the long press gesture event is triggered first.
![en-us_image_0000001174104384](figures/en-us_image_0000001174104384.png)
After the long press gesture is recognized, the drag gesture event is triggered.
![en-us_image1_0000001174104384](figures/en-us_image1_0000001174104384.png)
......@@ -6,12 +6,6 @@ The **\<Canvas>** component can be used to customize drawings.
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components
Not supported
......
......@@ -17,19 +17,19 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | --------- | ---------------------------- |
| offset | number | Yes | 0 | Relative position of the gradient stop along the gradient vector. The value ranges from 0 to 1.|
| color | string | Yes | '#ffffff' | Gradient color to set. |
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | --------- | ---------------------------- |
| offset | number | Yes | 0 | Relative position of the gradient stop along the gradient vector. The value ranges from 0 to 1.|
| color | string | Yes | '#ffffff' | Gradient color to set. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct Page45 {
// xxx.ets
@Entry
@Component
struct Page45 {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
......@@ -39,18 +39,19 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse
.width('100%')
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
var grad = this.context.createLinearGradient(50,0, 300,100)
grad.addColorStop(0.0, 'red')
grad.addColorStop(0.5, 'white')
grad.addColorStop(1.0, 'green')
.onReady(() => {
var grad = this.context.createLinearGradient(50, 0, 300, 100)
grad.addColorStop(0.0, '#ff0000')
grad.addColorStop(0.5, '#ffffff')
grad.addColorStop(1.0, '#00ff00')
this.context.fillStyle = grad
this.context.fillRect(0, 0, 500, 500)
})
}
.width('100%')
.height('100%')
}}
}
}
```
![en-us_image_0000001256858381](figures/en-us_image_0000001256858381.png)
......
......@@ -16,6 +16,10 @@ An **ImageData** object stores pixel data rendered on a canvas.
| height | number | Actual height of the rectangle on the canvas, in pixels.|
| data | Uint8ClampedArray | A one-dimensional array of color values. The values range from 0 to 255.|
> **NOTE**
>
> You can use [px2vp](ts-pixel-units.md) to convert units.
**Example**
```ts
......
......@@ -27,18 +27,18 @@ loadAnimation(
path: string, container: object, render: string, loop: boolean, autoplay: boolean, name: string ): AnimationItem
Loads an animation. Before calling this method, declare the **Animator('\__lottie\_ets')** object and check that the canvas layout is complete. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onAppear()** and **onPageShow()**.
Loads an animation. Before calling this API, declare the **Animator('__lottie_ets')** object and make sure the canvas layout is complete. This API can be used together with the lifecycle callback **onReady()** of the **Canvas** component.
**Parameters**
| Name | Type | Mandatory | Description |
| -------------- | --------------------------- | ---- | ---------------------------------------- |
| Name | Type | Mandatory| Description |
| -------------- | --------------------------- | ---- | ------------------------------------------------------------ |
| path | string | Yes | Path of the animation resource file in the HAP file. The resource file must be in JSON format. Example: **path: "common/lottie/data.json"**|
| container | object | Yes | Canvas drawing context. A **CanvasRenderingContext2D** object must be declared in advance.|
| render | string | Yes | Rendering type. The value can only be **"canvas"**. |
| loop | boolean \| number | No | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends; the default value is **true**. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays.|
| autoplay | boolean | No | Whether to automatically play the animation. The default value is **true**. |
| name | string | No | Custom animation name. In later versions, the name can be used to reference and control the animation. The default value is null. |
| autoplay | boolean | No | Whether to automatically play the animation.<br>Default value: **true** |
| name | string | No | Custom animation name. In later versions, the name can be used to reference and control the animation.<br/>Default value: null |
| initialSegment | [number, number] | No | Start frame and end frame of the animation, respectively. |
......@@ -46,15 +46,16 @@ Loads an animation. Before calling this method, declare the **Animator('\__lotti
destroy(name: string): void
Destroys the animation. This method must be called when a page exits. This method can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**.
Destroys the animation. This API must be called when a page exits. This API can be used together with a lifecycle callback of the **Canvas** component, for example, **onDisappear()** and **onPageHide()**.
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are destroyed.|
| name | string | Yes | Name of the animation to destroy, which is the same as the **name** in the **loadAnimation** API. By default, all animations are destroyed. |
**Example**
```ts
// xxx.ets
import lottie from '@ohos/lottieETS'
......@@ -78,7 +79,7 @@ Destroys the animation. This method must be called when a page exits. This metho
.width('30%')
.height('20%')
.backgroundColor('#0D9FFB')
.onAppear(() => {
.onReady(() => {
console.log('canvas onAppear');
this.animateItem = lottie.loadAnimation({
container: this.controller,
......@@ -133,7 +134,7 @@ Plays a specified animation.
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are played.|
| name | string | Yes | Name of the animation to play, which is the same as the **name** in the **loadAnimation** API. By default, all animations are played. |
**Example**
......@@ -152,7 +153,7 @@ Pauses a specified animation. The next time **lottie.play()** is called, the ani
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.|
| name | string | Yes | Name of the animation to pause, which is the same as the **name** in the **loadAnimation** API. By default, all animations are paused. |
**Example**
......@@ -165,13 +166,13 @@ Pauses a specified animation. The next time **lottie.play()** is called, the ani
togglePause(name: string): void
Pauses or plays a specified animation. This method is equivalent to the switching between **lottie.play()** and **lottie.pause()**.
Pauses or plays a specified animation. This API is equivalent to the switching between **lottie.play()** and **lottie.pause()**.
**Parameters**
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.|
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are paused or played. |
**Example**
......@@ -190,7 +191,7 @@ Stops the specified animation. The next time **lottie.play()** is called, the an
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ---------------------------------------- |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are paused.|
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are stopped. |
**Example**
......@@ -209,8 +210,8 @@ Sets the playback speed of the specified animation.
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is 0, the animation is paused. If the value is 1.0 or -1.0, the animation plays at the normal speed.|
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are stopped.|
| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays in forward direction. If the value is less than 0, the animation plays in reversed direction. If the value is **0**, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are set. |
**Example**
......@@ -230,7 +231,7 @@ Sets the direction in which the specified animation plays.
| Name | Type | Mandatory | Description |
| --------- | ------------------ | ---- | ---------------------------------------- |
| direction | AnimationDirection | Yes | Direction in which the animation plays. **1**: forwards; **-1**: backwards. When set to play backwards, the animation plays from the current playback progress to the first frame. When this setting is combined with **loop** being set to **true**, the animation plays backwards continuously. When the value of **speed** is less than 0, the animation also plays backwards.<br>AnimationDirection: 1 \| -1 |
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** interface. By default, all animations are set.|
| name | string | Yes | Name of the target animation, which is the same as the **name** in the **loadAnimation** API. By default, all animations are set. |
**Example**
......@@ -241,7 +242,7 @@ Sets the direction in which the specified animation plays.
## AnimationItem
Defines an **AnimationItem** object, which is returned by the **loadAnimation** interface and has attributes and interfaces. The attributes are described as follows:
Defines an **AnimationItem** object, which is returned by the **loadAnimation** API and has attributes and APIs. The attributes are described as follows:
| Name | Type | Description |
| ----------------- | ---------------------------------------- | ---------------------------------------- |
......@@ -253,11 +254,11 @@ Defines an **AnimationItem** object, which is returned by the **loadAnimation**
| totalFrames | number | Total number of frames in the animation segment that is being played. |
| frameRate | number | Frame rate (frame/s). |
| frameMult | number | Frame rate (frame/ms). |
| playSpeed | number | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.|If the value is **1.0** or **-1.0**, the animation plays at the normal speed.|
| playDirection | number | Playback direction. The options are **1** (forward) and **-1** (backward). |
| playSpeed | number | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is **0**, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. |
| playDirection | number | Playback direction.<br>**1**: forward.<br/>**-1**: backward. |
| playCount | number | Number of times the animation plays. |
| isPaused | boolean | Whether the current animation is paused. The value **true** means that the animation is paused. |
| autoplay | boolean | Whether to automatically play the animation upon completion of the loading. The value **false** means that the **play()** interface needs to be called to start playing.|
| autoplay | boolean | Whether to automatically play the animation upon completion of the loading. The value **false** means that the **play()** API needs to be called to start playing. |
| loop | boolean \| number | If the value is of the Boolean type, this parameter indicates whether to repeat the animation cyclically after the animation ends. If the value is of the number type and is greater than or equal to 1, this parameter indicates the number of times the animation plays. |
| renderer | any | Animation rendering object, which depends on the rendering type. |
| animationID | string | Animation ID. |
......@@ -309,7 +310,7 @@ Destroys an animation.
pause(name?: string): void
Pauses an animation. When the **play** interface is called next time, the animation is played from the current frame.
Pauses an animation. When the **play** API is called next time, the animation is played from the current frame.
**Parameters**
......@@ -328,7 +329,7 @@ Pauses an animation. When the **play** interface is called next time, the animat
togglePause(name?: string): void
Pauses or plays an animation. This method is equivalent to the switching between **play** and **pause**.
Pauses or plays an animation. This API is equivalent to the switching between **play** and **pause**.
**Parameters**
......@@ -347,7 +348,7 @@ Pauses or plays an animation. This method is equivalent to the switching between
stop(name?: string): void
Stops an animation. When the **play** interface is called next time, the animation is played from the first frame.
Stops an animation. When the **play** API is called next time, the animation is played from the first frame.
**Parameters**
......@@ -372,7 +373,7 @@ Sets the playback speed of an animation.
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ---------------------------------------- |
| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is 0, the animation is paused.|If the value is **1.0** or **-1.0**, the animation plays at the normal speed.|
| speed | number | Yes | Playback speed. The value is a floating-point number. If the value is greater than 0, the animation plays forward. If the value is less than 0, the animation plays backward. If the value is **0**, the animation is paused. If the value is **1.0** or **-1.0**, the animation plays at the normal speed. |
**Example**
......@@ -411,7 +412,7 @@ Sets the animation to stop at the specified frame or time.
| Name | Type | Mandatory | Description |
| ------- | ------- | ---- | ---------------------------------------- |
| value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will stop. |
| isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress. The default value is **false**.|
| isFrame | boolean | No | Whether to set the animation to stop at the specified frame. The value **true** means to set the animation to stop at the specified frame, and **false** means to set the animation to stop at the specified time progress.<br/>Default value: **false** |
| name | string | No | Name of the target animation. By default, the value is null. |
**Example**
......@@ -435,8 +436,8 @@ Sets the animation to start from the specified frame or time progress.
| Name | Type | Mandatory | Description |
| ------- | ------- | ---- | ---------------------------------------- |
| value | number | Yes | Frame ID (greater than or equal to 0) or time progress (ms) at which the animation will start. |
| isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress. The default value is **false**.|
| name | string | No | Name of the target animation. By default, the value is null. |
| isFrame | boolean | Yes | Whether to set the animation to start from the specified frame. The value **true** means to set the animation to start from the specified frame, and **false** means to set the animation to start from the specified time progress.<br/>Default value: **false** |
| name | string | No | Name of the target animation.<br/>Default value: null |
**Example**
......@@ -475,7 +476,7 @@ Sets the animation to play only the specified segment.
resetSegments(forceFlag: boolean): void
Resets the settings configured by the **playSegments** method to play all the frames.
Resets the settings configured by the **playSegments** API to play all the frames.
**Parameters**
......@@ -526,13 +527,13 @@ Sets the precision of the **currentFrame** attribute to display floating-point n
getDuration(inFrames?: boolean): void
Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** interface.
Obtains the duration (irrelevant to the playback speed) or number of frames for playing an animation sequence. The settings are related to the input parameter **initialSegment** of the **Lottie.loadAnimation** API.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ------- | ---- | ---------------------------------------- |
| inFrames | boolean | No | Whether to obtain the duration or number of frames.<br>**true**: number of frames.<br>**false**: duration, in ms.<br>Default value: **false**|
| inFrames | boolean | No | Whether to obtain the duration or number of frames.<br>**true**: number of frames.<br>**false**: duration, in ms.<br/>Default value: **false** |
**Example**
......@@ -545,7 +546,7 @@ Obtains the duration (irrelevant to the playback speed) or number of frames for
addEventListener&lt;T = any&gt;(name: AnimationEventName, callback: AnimationEventCallback&lt;T&gt;): () =&gt; void
Adds an event listener. After the event is complete, the specified callback function is triggered. This method returns the function object that can delete the event listener.
Adds an event listener. After the event is complete, the specified callback is triggered. This API returns the function object that can delete the event listener.
**Parameters**
......
# Component Overview
## Rows and Columns
- [Column](ts-container-column.md)
A container that lays out child components vertically.
- [ColumnSplit](ts-container-columnsplit.md)
A container that lays out child components vertically and inserts a horizontal divider between every two child components.
- [Row](ts-container-row.md)
A container that lays out child components horizontally.
- [RowSplit](ts-container-rowsplit.md)
A container that lays out child components horizontally and inserts a vertical divider between every two child components.
- [SideBarContainer](ts-container-sidebarcontainer.md)
A container that contains a sidebar and content area as its child components. The sidebar is the first child component and can be shown or hidden as needed. The content area is the second child component.
## Stack, Flex, and Grid
- [Stack](ts-container-stack.md)
A container where child components are successively stacked and the latter one overwrites the previous one.
- [Flex](ts-container-flex.md)
A container that allows for flexible layout of child components.
- [GridContainer](ts-container-gridcontainer.md)
A container that lays out components vertically and is used only in the grid layout.
- [GridRow](ts-container-gridrow.md)
A container that is used in a grid layout, together with its child component **\<GridCol>**.
- [GridCol](ts-container-gridcol.md)
A container that must be used as a child component of the **\<GridRow>** container.
- [RelativeContainer](ts-container-relativecontainer.md)
A container that is used for element alignment in complex scenarios.
## List and Grid
- [List](ts-container-list.md)
A container that presents a series of list items arranged in a column with the same width. It supports presentations of the same type of data in a multiple and coherent row style, for example, images or text.
- [ListItem](ts-container-listitem.md)
A component that displays a specific item in the list and that must be used together with **\<List>**.
- [ListItemGroup](ts-container-listitemgroup.md)
A component that displays list item groups and that must be used together with **\<List>**.
- [Grid](ts-container-grid.md)
A container that consists of cells formed by rows and columns. You can specify the cells where items are located to form various layouts.
- [GridItem](ts-container-griditem.md)
A container that provides a single item in a grid.
## Scroll and Swipe
- [Scroll](ts-container-scroll.md)
A container that scrolls the content when the layout size of a component exceeds the size of its parent component.
- [Swiper](ts-container-swiper.md)
A container that is able to display child components in looping mode.
- [WaterFlow](ts-container-waterflow.md)
A container that consists of cells formed by rows and columns and arranges items of different sizes from top to bottom according to the preset rules.
- [FlowItem](ts-container-flowitem.md)
A child component of the **\<WaterFlow>** container that is used to display specific items in the container layout.
## Navigation
- [Navigator](ts-container-navigator.md)
A container that provides redirection.
- [Navigation](ts-basic-components-navigation.md)
A container that typically functions as the root container of a page and displays the title bar, toolbar, and navigation bar based on the attribute settings.
- [NavRouter](ts-basic-components-navrouter.md)
A container that provides default logic for click response processing, eliminating the need for manual logic definition.
- [NavDestination](ts-basic-components-navdestination.md)
A child component of the **\<NavRouter>** component that represents a destination in the navigation area.
- [Stepper](ts-basic-components-stepper.md)
A component that provides a step navigator.
- [StepperItem](ts-basic-components-stepperitem.md)
A child component of the **\<Stepper>** component.
- [Tabs](ts-container-tabs.md)
A container that allows users to switch between content views through tabs.
- [TabContent](ts-container-tabcontent.md)
A component that corresponds to the content view on a tab page and is used only in the **\<Tabs>** component.
## Button and Selection
- [Button](ts-basic-components-button.md)
A component that can be used to create different types of buttons.
- [Toggle](ts-basic-components-toggle.md)
A component that provides a clickable element in the check box, button, or switch type.
- [Checkbox](ts-basic-components-checkbox.md)
A component that is used to enable or disable an option.
- [CheckboxGroup](ts-basic-components-checkboxgroup.md)
A component that is used to select or deselect all check boxes in a group.
- [DatePicker](ts-basic-components-datepicker.md)
A component that allows users to select a date from the given range.
- [TextPicker](ts-basic-components-textpicker.md)
A component that allows users to scroll to select text.
- [TimePicker](ts-basic-components-timepicker.md)
A component that allows users to select a time from the given range through scrolling.
- [Radio](ts-basic-components-radio.md)
A component that allows users to select from a set of mutually exclusive options.
- [Rating](ts-basic-components-rating.md)
A component that provides a rating bar.
- [Select](ts-basic-components-select.md)
A component that provides a drop-down list box to allow user to select among multiple options.
- [Slider](ts-basic-components-slider.md)
A component that is used to quickly adjust settings, such as the volume and brightness.
- [Counter](ts-container-counter.md)
A component that provides an operation to increase or decrease the number.
## Text and Input
- [Text](ts-basic-components-text.md)
A component that is used to display a piece of textual information.
- [Span](ts-basic-components-span.md)
A component that is used to display inline text in the **\<Text>** component.
- [Search](ts-basic-components-search.md)
A component that provides an area for users to enter search queries.
- [TextArea](ts-basic-components-textarea.md)
A component that provides multi-line text input and automatically wraps text so that each line does not have more than the width of the component.
- [TextInput](ts-basic-components-textinput.md)
A component that provides single-line text input.
- [PatternLock](ts-basic-components-patternlock.md)
A component that allows users to use a pattern password for authentication. It enters the input state once a finger is pressed against it, and exits the input state and completes the input once the finger leaves the screen.
- [RichText](ts-basic-components-richtext.md)
A component that parses and displays HTML text.
## Image, Video, and Media
- [Image](ts-basic-components-image.md)
A component that is used to render and display local and online images.
- [ImageAnimator](ts-basic-components-imageanimator.md)
A component that enables images to be played frame by frame. The list of images to be played as well as the duration of each image can be configured.
- [Video](ts-media-components-video.md)
A component that is used to play a video and control its playback.
- [PluginComponent](ts-basic-components-plugincomponent.md)
A component that allows the UI provided by an external application to be displayed in the application.
- [XComponent](ts-basic-components-xcomponent.md)
A component that can accept and display the EGL/OpenGL ES and media data input.
## Information Display
- [DataPanel](ts-basic-components-datapanel.md)
A component that displays proportions in a chart.
- [Gauge](ts-basic-components-gauge.md)
A component that is used to display data in a ring chart.
- [LoadingProgress](ts-basic-components-loadingprogress.md)
A component that is used to create a loading animation.
- [Marquee](ts-basic-components-marquee.md)
A component that is used to display a scrolling piece of text. The text is scrolled only when its width exceeds the width of the **\<Marquee>** component.
- [Progress](ts-basic-components-progress.md)
A component that is used to provide a progress indicator that displays the progress of content loading or an operation.
- [QRCode](ts-basic-components-qrcode.md)
A component that is used to display a QR code.
- [TextClock](ts-basic-components-textclock.md)
A component that displays the current system time in text format for different time zones. The time is accurate to seconds.
- [TextTimer](ts-basic-components-texttimer.md)
A component that displays timing information and is controlled in text format.
## Blank and Divider
- [Blank](ts-basic-components-blank.md)
A component that 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>**.
- [Divider](ts-basic-components-divider.md)
A component that is used to separate content blocks and elements.
## Canvas and Graphics Drawing
- [Canvas](ts-components-canvas-canvas.md)
A component that can be used to customize drawings.
- [Circle](ts-drawing-components-circle.md)
A component that is used to draw a circle.
- [Ellipse](ts-drawing-components-ellipse.md)
A component that is used to draw an ellipse.
- [Line](ts-drawing-components-line.md)
A component that is used to draw a straight line.
- [Polyline](ts-drawing-components-polyline.md)
A component that is used to draw a polyline.
- [Polygon](ts-drawing-components-polygon.md)
A component that is used to draw a polygon.
- [Path](ts-drawing-components-path.md)
A component that is used to define a closed shape.
- [Rect](ts-drawing-components-rect.md)
A component that is used to draw a rectangle.
- [Shape](ts-drawing-components-shape.md)
A parent component of the drawing components. The attributes provided by this component are universal attributes supported by all the drawing components.
## Web
- [Web](ts-basic-components-web.md)
A component that can be used to display web pages.
## Miscellaneous
- [ScrollBar](ts-basic-components-scrollbar.md)
A component that is used together with scrollable components, such as **\<List>**, **\<Grid>**, and **\<Scroll>**.
- [Badge](ts-container-badge.md)
A container that can be attached to another component for tagging.
- [AlphabetIndexer](ts-container-alphabet-indexer.md)
A component that can create a logically indexed array of items in a container for instant location.
- [Panel](ts-container-panel.md)
A container that presents lightweight content with flexible sizes.
- [Refresh](ts-container-refresh.md)
A container that provides the pull-to-refresh feature.
- [AbilityComponent](ts-container-ability-component.md)
A container that is used for independently displaying an ability.
- [RemoteWindow](ts-basic-components-remotewindow.md)
A component that is used to control the application window, providing the component animator and application window linkage animator during application startup and exit.
......@@ -6,7 +6,7 @@
>
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
>
> The APIs of this module are system APIs and cannot be called by third-party applications.
> The APIs provided by this component are system APIs.
## Constraints
......@@ -16,7 +16,7 @@
Only width and height can be set for **\<AbilityComponent>**. These attributes are mandatory and cannot be dynamically updated.
The ability to be started must inherit from [WindowExtension](../apis/js-apis-application-WindowExtensionAbility.md).
The ability to be started must inherit [WindowExtension](../apis/js-apis-application-windowExtensionAbility.md).
## Child Components
......@@ -31,7 +31,7 @@ AbilityComponent(want: Want)
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](../apis/js-apis-application-Want.md) | Yes| Description of the default ability to load.|
| want | [Want](../apis/js-apis-app-ability-want.md) | Yes| Description of the default ability to load.|
## Events
......@@ -74,3 +74,5 @@ struct MyComponent {
}
}
```
<!--no_check-->
\ No newline at end of file
......@@ -20,8 +20,8 @@ AlphabetIndexer(value: {arrayValue: Array&lt;string&gt;, selected: number})
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| arrayValue | Array&lt;string&gt; | Yes| Array of strings to be displayed in the alphabetic index bar.|
| selected | number | Yes | Index of the initially selected item. |
| arrayValue | Array&lt;string&gt; | Yes| Array of strings to be displayed in the alphabetic index bar. The value cannot be null.|
| selected | number | Yes | Index of the initially selected item. If the value exceeds the value range, the default value 0 is used. |
## Attributes
......@@ -29,21 +29,21 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Type | Description |
| ----------------------- | --------------- | ----------------------------------------------------------- |
| color | [ResourceColor](ts-types.md#resourcecolor) | Font color. |
| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Font color of the selected text. |
| popupColor | [ResourceColor](ts-types.md#resourcecolor) | Font color of the pop-up text. |
| selectedBackgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected item. |
| popupBackground | [ResourceColor](ts-types.md#resourcecolor) | Background color of the pop-up text. |
| usingPopup | boolean | Whether to use pop-up text. |
| selectedFont | [Font](ts-types.md#font) | Font style of the selected text. |
| popupFont | [Font](ts-types.md#font) | Font style of the pop-up text. |
| font | [Font](ts-types.md#font) | Default font style of the alphabetic index bar. |
| itemSize | string \| number | Size of an item in the alphabetic index bar. The item is a square, and the side length needs to be set. |
| color | [ResourceColor](ts-types.md#resourcecolor) | Font color.<br>Default value: **0x99000000** |
| selectedColor | [ResourceColor](ts-types.md#resourcecolor) | Font color of the selected text.<br>Default value: **0xFF254FF7** |
| popupColor | [ResourceColor](ts-types.md#resourcecolor) | Font color of the pop-up text.<br>Default value: **0xFF254FF7** |
| selectedBackgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected item.<br>Default value: **0x1F0A59F7** |
| popupBackground | [ResourceColor](ts-types.md#resourcecolor) | Background color of the pop-up text.<br>Default value: **0xFFF1F3F5** |
| usingPopup | boolean | Whether to use pop-up text.<br>Default value: **false** |
| selectedFont | [Font](ts-types.md#font) | Font style of the selected text.<br>Default value:<br>{<br>fontSize:10,<br> fontStyle:FontStyle.Normal,<br> fontWeight:FontWeight.Normal,<br> fontFamily:HarmonyOS Sans<br>} |
| popupFont | [Font](ts-types.md#font) | Font style of the pop-up text.<br>Default value:<br>{<br>fontSize:10,<br> fontStyle:FontStyle.Normal,<br> fontWeight:FontWeight.Normal,<br> fontFamily:HarmonyOS Sans<br>} |
| font | [Font](ts-types.md#font) | Default font style of the alphabetic index bar.<br>Default value:<br>{<br>fontSize:10,<br> fontStyle:FontStyle.Normal,<br> fontWeight:FontWeight.Normal,<br> fontFamily:HarmonyOS Sans<br>} |
| itemSize | string \| number | Size of an item in the alphabetic index bar. The item is a square, and the side length needs to be set. This attribute cannot be set to a percentage.<br>Default value: **24.0** |
| alignStyle | IndexerAlign | Alignment style of the alphabetic index bar. Left alignment and right alignment are supported.<br>Default value: **IndexerAlign.Right**|
| selected | number | Index of the selected item.|
| popupPosition | [Position](ts-types.md#position8) | Position of the pop-up window relative to the center of the indexer bar's top border.|
| selected | number | Index of the selected item.<br>Default value: **0**|
| popupPosition | [Position](ts-types.md#position8) | Position of the pop-up window relative to the center of the indexer bar's top border.<br>Default value: **{x:96.0, y:48.0}**|
## IndexerAlign enums
## IndexerAlign
| Name| Description|
| -------- | -------- |
......@@ -56,9 +56,9 @@ Only the following events are supported.
| Name| Description|
| -------- | -------- |
| onSelected(callback: (index: number) =&gt; void)<sup>(deprecated)</sup> | Invoked when an item in the alphabetic indexer bar is selected. The return value is the index of the selected item. |
| onSelected(callback: (index: number) =&gt; void)<sup>(deprecated)</sup> | Invoked when an item in the alphabetic indexer bar is selected. The return value is the index of the selected item. This API is deprecated since API version 8. You are advised to use **onSelect**. |
| onSelect(callback: (index: number) =&gt; void)<sup>8+</sup> | Invoked when an item in the alphabetic indexer bar is selected. The return value is the index of the selected item. |
| onRequestPopupData(callback: (index: number) =&gt; Array&lt;string&gt;)<sup>8+</sup> | Invoked when a request for displaying content in the index prompt window is sent after an item in the alphabetic indexer bar is selected.<br>The return value is a string array corresponding to the indexes. The string array is displayed vertically in the pop-up window. It can display up to five strings at a time and allows scrolling.|
| onRequestPopupData(callback: (index: number) =&gt; Array&lt;string&gt;)<sup>8+</sup> | Invoked when a request for displaying content in the index prompt window is sent after an item in the alphabetic indexer bar is selected.<br>The return value is a string array corresponding to the selected index. The string array is displayed vertically in the pop-up window. It can display up to five strings at a time and allows scrolling.|
| onPopupSelect(callback: (index: number) =&gt; void)<sup>8+</sup> | Invoked when an item in the index pop-up window is selected. |
......@@ -69,25 +69,97 @@ Only the following events are supported.
@Entry
@Component
struct AlphabetIndexerSample {
private value: string[] = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
private arrayA:string[] = ['Ann']
private arrayB: string[] = ['Ben', 'Bob']
private arrayC: string[] = ['Calvin', 'Cameron', 'Charlie', 'Charlotte']
private arrayL: string[] = ['Daisy', 'Daniel', 'Darla', 'David', 'Derek', 'Dorothy', 'Duke']
private value: string[] = ['#', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z']
build() {
Stack({ alignContent: Alignment.Start }) {
Row() {
List({ space: 20, initialIndex: 0 }) {
ForEach(this.arrayA, (item) => {
ListItem() {
Text(item)
.width('80%')
.height('5%')
.fontSize(30)
.textAlign(TextAlign.Center)
}.editable(true)
}, item => item)
ForEach(this.arrayB, (item) => {
ListItem() {
Text(item)
.width('80%')
.height('5%')
.fontSize(30)
.textAlign(TextAlign.Center)
}.editable(true)
}, item => item)
ForEach(this.arrayC, (item) => {
ListItem() {
Text(item)
.width('80%')
.height('5%')
.fontSize(30)
.textAlign(TextAlign.Center)
}.editable(true)
}, item => item)
ForEach(this.arrayL, (item) => {
ListItem() {
Text(item)
.width('80%')
.height('5%')
.fontSize(30)
.textAlign(TextAlign.Center)
}.editable(true)
}, item => item)
}
.width('50%')
.height('100%')
AlphabetIndexer({ arrayValue: this.value, selected: 0 })
.selectedColor(0xffffff) // Font color of the selected text
.popupColor(0xFFFAF0) // Font color of the pop-up text
.selectedBackgroundColor(0xCCCCCC) // Background color of the selected text
.popupBackground(0xD2B48C) // Background color of the pop-up text
.usingPopup(true) // Whether to use pop-up text
.selectedFont({ size: 16, weight: FontWeight.Bolder }) // Font style of the selected text
.popupFont({ size: 30, weight: FontWeight.Bolder }) // Font style of the pop-up text
.itemSize(28) // Size of each item (square)
.alignStyle(IndexerAlign.Left) // Left aligned
.selectedColor(0xFFFFFF) // Font color of the selected text.
.popupColor(0xFFFAF0) // Font color of the pop-up text.
.selectedBackgroundColor(0xCCCCCC) // Background color of the selected item.
.popupBackground(0xD2B48C) // Background color of the pop-up text.
.usingPopup(true) // Whether to use pop-up text.
.selectedFont({size: 16, weight: FontWeight.Bolder}) // Font style of the selected text.
.popupFont({ size: 30, weight: FontWeight.Bolder}) // Font style of the pop-up text.
.itemSize(28) // Size of an item in the alphabetic index bar.
.alignStyle(IndexerAlign.Left) // The pop-up window is displayed on the right of the alphabetic index bar.
.onSelect((index: number) => {
console.info(this.value[index] + 'Selected') // Event indicating that an item is selected
console.info(this.value[index] + ' Selected!')
})
.onRequestPopupData((index: number) => {
if (this.value[index] == 'A') {
return this.arrayA // When index A is selected, the pop-up window displays arrayA corresponding to index A. The same applies when other indexes are selected.
} else if (this.value[index] == 'B') {
return this.arrayB
} else if (this.value[index] == 'C') {
return this.arrayC
} else if (this.value[index] == 'L') {
return this.arrayL
} else {
return [] // When no array is available for the selected index, the pop-up window is empty.
}
})
.margin({ left: 50 })
.onPopupSelect((index: number) => {
console.info('onPopupSelected:' + index)
})
}
.width('100%')
.height('100%')
}
}
}
```
![en-us_image_0000001212378392](figures/en-us_image_0000001212378392.gif)
![alphabet](figures/alphabet.gif)
......@@ -14,9 +14,9 @@ This component supports only one child component.
## APIs
**Method 1**: Badge(value: {count: number, position?: BadgePosition, maxCount?: number, style: BadgeStyle})
**API 1**: Badge(value: {count: number, position?: BadgePosition, maxCount?: number, style: BadgeStyle})
Create a badge.
Creates a badge.
**Parameters**
| Name| Type| Mandatory| Default Value| Description|
......@@ -26,7 +26,7 @@ Create a badge.
| maxCount | number | No| 99 | Maximum number of notifications. When the maximum number is reached, only **maxCount+** is displayed.|
| style | [BadgeStyle](#badgestyle) | Yes| - | Style of the badge, including the font color, font size, badge color, and badge size.|
**Method 2**: Badge(value: {value: string, position?: BadgePosition, style: BadgeStyle})
**API 2**: Badge(value: {value: string, position?: BadgePosition, style: BadgeStyle})
Creates a badge based on the given string.
......@@ -62,90 +62,140 @@ Creates a badge based on the given string.
@Entry
@Component
struct BadgeExample {
@State counts: number = 1
@State message: string = 'new'
build() {
@Builder TabBuilder(index: number) {
Column() {
Text('numberBadge').width('80%')
Row({ space: 10 }) {
// Number badge. The default value of maxCount is 99. If the number of notifications exceeds 99, 99+ is displayed.
Badge({
count: this.counts,
maxCount: 99,
position: BadgePosition.RightTop,
style: { color: 0xFFFFFF, fontSize: 16, badgeSize: 20, badgeColor: Color.Red }
}) {
Button('message')
.onClick(() => {
this.counts++
})
.width(100).height(50).backgroundColor(0x317aff)
}.width(100).height(50)
// Number badge
if (index === 2) {
Badge({
count: this.counts,
maxCount: 99,
position: BadgePosition.Left,
style: { color: 0xFFFFFF, fontSize: 16, badgeSize: 20, badgeColor: Color.Red }
value: '',
style: { badgeSize: 6, badgeColor: '#FA2A2D' }
}) {
Button('message')
.onClick(() => {
this.counts++
})
.width(100).height(50).backgroundColor(0x317aff)
}.width(100).height(50)
Image('/common/public_icon_off.svg')
.width(24)
.height(24)
}
.width(24)
.height(24)
.margin({ bottom: 4 })
} else {
Image('/common/public_icon_off.svg')
.width(24)
.height(24)
.margin({ bottom: 4 })
}
Text('Tab')
.fontColor('#182431')
.fontSize(10)
.fontWeight(500)
.lineHeight(14)
}.width('100%').height('100%').justifyContent(FlexAlign.Center)
}
@Builder itemBuilder(value: string) {
Row() {
Image('common/public_icon.svg').width(32).height(32).opacity(0.6)
Text(value)
.width(177)
.height(21)
.margin({ left: 15, right: 76 })
.textAlign(TextAlign.Start)
.fontColor('#182431')
.fontWeight(500)
.fontSize(16)
.opacity(0.9)
Image('common/public_icon_arrow_right.svg').width(12).height(24).opacity(0.6)
}.width('100%').padding({ left: 12, right: 12 }).height(56)
}
// Number badge
build() {
Column() {
Text('dotsBadge').fontSize(18).fontColor('#182431').fontWeight(500).margin(24)
Tabs() {
TabContent()
.tabBar(this.TabBuilder(0))
TabContent()
.tabBar(this.TabBuilder(1))
TabContent()
.tabBar(this.TabBuilder(2))
TabContent()
.tabBar(this.TabBuilder(3))
}
.width(360)
.height(56)
.backgroundColor('#F1F3F5')
Column() {
Text('stringBadge').fontSize(18).fontColor('#182431').fontWeight(500).margin(24)
List({ space: 12 }) {
ListItem() {
Text('list1').fontSize(14).fontColor('#182431').margin({ left: 12 })
}
.width('100%')
.height(56)
.backgroundColor('#FFFFFF')
.borderRadius(24)
.align(Alignment.Start)
ListItem() {
Badge({
count: this.counts,
maxCount: 99,
value: 'New',
position: BadgePosition.Right,
style: { color: 0xFFFFFF, fontSize: 16, badgeSize: 20, badgeColor: Color.Red }
}) {
Button('message')
.onClick(() => {
this.counts++
})
.width(100).height(50).backgroundColor(0x317aff)
}.width(100).height(50)
}.margin(10)
Text('stringBadge').width('80%')
Row({ space: 30 }) {
Badge({
value: this.message,
style: { color: 0xFFFFFF, fontSize: 9, badgeSize: 20, badgeColor: Color.Blue }
style: { badgeSize: 16, badgeColor: '#FA2A2D' }
}) {
Text('message')
.width(80)
.height(50)
.fontSize(16)
.lineHeight(37)
.borderRadius(10)
.textAlign(TextAlign.Center)
.backgroundColor(0xF3F4ED)
}.width(80).height(50)
Text('list2').width(27).height(19).fontSize(14).fontColor('#182431')
}.width(49.5).height(19)
.margin({ left: 12 })
}
.width('100%')
.height(56)
.backgroundColor('#FFFFFF')
.borderRadius(24)
.align(Alignment.Start)
}.width(336)
Text('numberBadge').fontSize(18).fontColor('#182431').fontWeight(500).margin(24)
List() {
ListItem() {
this.itemBuilder('list1')
}
// When value is null, the dot-style badge is used.
ListItem() {
Row() {
Image('common/public_icon.svg').width(32).height(32).opacity(0.6)
Badge({
value: '',
count: 1,
position: BadgePosition.Right,
style: { badgeSize: 6, badgeColor: Color.Red }
style: { badgeSize: 16, badgeColor: '#FA2A2D' }
}) {
Text('message')
.width(90)
.height(50)
Text('list2')
.width(177)
.height(21)
.textAlign(TextAlign.Start)
.fontColor('#182431')
.fontWeight(500)
.fontSize(16)
.lineHeight(37)
.borderRadius(10)
.textAlign(TextAlign.Center)
.backgroundColor(0xF3F4ED)
}.width(90).height(50)
}.margin(10)
.opacity(0.9)
}.width(240).height(21).margin({ left: 15, right: 11 })
Image('common/public_icon_arrow_right.svg').width(12).height(24).opacity(0.6)
}.width('100%').padding({ left: 12, right: 12 }).height(56)
}
ListItem() {
this.itemBuilder('list3')
}
ListItem() {
this.itemBuilder('list4')
}
}
.width(336)
.height(232)
.backgroundColor('#FFFFFF')
.borderRadius(24)
.padding({ top: 4, bottom: 4 })
.divider({ strokeWidth: 0.5, color: 'rgba(0,0,0,0.1)', startMargin: 60, endMargin: 12 })
}.width('100%').backgroundColor('#F1F3F5').padding({ bottom: 12 })
}.width('100%')
}
}
```
......
# ColumnSplit
The **\<ColumnSplit>** lays out child components vertically and inserts a horizontal divider between every two child components.
The **\<ColumnSplit>** component lays out child components vertically and inserts a horizontal divider between every two child components.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Supported
......
......@@ -7,11 +7,6 @@ The **\<Counter>** component provides an operation to increase or decrease the n
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components
Supported
......
......@@ -4,7 +4,7 @@ The **\<Flex>** component allows for flexible layout of child components.
> **NOTE**
> - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> - The **\<Flex>** component adapts the layout of flex items during rendering. This may affect the performance. Therefore, you are advised to use **[Column](ts-container-column.md)** or **[Row](ts-container-row.md)** instead under scenarios where consistently high performance is required.
> - The **\<Flex>** component adapts the layout of flex items during rendering. This may affect the performance. Therefore, you are advised to use **[\<Column>](ts-container-column.md)** or **[\<Row>](ts-container-row.md)** instead under scenarios where consistently high performance is required.
## Required Permissions
......@@ -30,7 +30,7 @@ Creates a standard **\<Flex>** component.
| wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | FlexWrap.NoWrap | Whether the **\<Flex>** component has a single line or multiple lines. |
| justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in the **\<Flex>** component along the main axis. |
| alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Start | Alignment mode of the child components in the **\<Flex>** component along the cross axis. |
| alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **<Flex>** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**.|
| alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **\<Flex>** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**. |
## Example
......
# FlowItem
**\<FlowItem>** is a child component of the [\<WaterFlow>](ts-container-waterflow.md) container and is used to display specific items in the container layout.
> **NOTE**
>
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
This component supports only one child component.
## APIs
FlowItem()
Ceates a child component in the **\<WaterFlow>** layout.
## Attributes
None
## Example
See [WaterFlow](ts-container-waterflow.md#example).
......@@ -12,7 +12,7 @@ The **\<Grid>** component consists of cells formed by rows and columns. You can
This component contains the child component **[\<GridItem>](ts-container-griditem.md)**.
## Interface
## APIs
Grid(scroller?: Scroller)
......@@ -35,7 +35,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| scrollBarColor | string \| number \| Color | Color of the scrollbar.|
| scrollBarWidth | string \| number | Width of the scrollbar.|
| cachedCount | number | Number of grid items to be preloaded. For details, see [Minimizing White Blocks During Swiping](../../ui/ui-ts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).<br>Default value: **1**|
| editMode <sup>8+</sup> | boolean | Whether to enter editing mode. In editing mode, the user can drag the **\<[GridItem](ts-container-griditem.md)>** in the **\<Grid>** component.<br>Default value: **false**|
| editMode <sup>8+</sup> | boolean | Whether to enter editing mode. In editing mode, the user can drag the **[\<GridItem>](ts-container-griditem.md)** in the **\<Grid>** component.<br>Default value: **false** |
| layoutDirection<sup>8+</sup> | [GridDirection](#griddirection8) | Main axis direction of the grid.<br>Default value: **GridDirection.Row**|
| maxCount<sup>8+</sup> | number | When **layoutDirection** is **Row** or **RowReverse**: maximum number of columns that can be displayed.<br>When **layoutDirection** is **Column** or **ColumnReverse**: maximum number of rows that can be displayed.<br>Default value: **Infinity**|
| minCount<sup>8+</sup> | number | When **layoutDirection** is **Row** or **RowReverse**: minimum number of columns that can be displayed.<br>When **layoutDirection** is **Column** or **ColumnReverse**: maximum number of rows that can be displayed.<br>Default value: **1**|
......@@ -47,21 +47,21 @@ Depending on the settings of the **rowsTemplate** and **columnsTemplate** attrib
1. **rowsTemplate** and **columnsTemplate** are both set
The **\<Grid>** displays only elements in a fixed number of rows and columns and cannot be scrolled. For example, if both **rowsTemplate** and **columnsTemplate** are set to **"1fr 1fr"**, only four elements (two rows and two columns) are displayed.
The **\<Grid>** displays only elements in a fixed number of rows and columns and cannot be scrolled. For example, if both **rowsTemplate** and **columnsTemplate** are set to **"1fr 1fr"**, only four elements (two rows and two columns) are displayed.
In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, minCount, and **cellLength**.
In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, minCount, and **cellLength**.
2. Either **rowsTemplate** or **columnsTemplate** is set
The **\<Grid>** arranges elements in the specified direction and allows for scrolling to display excess elements. For example, if the **\<Grid>** has 10 elements and **columnsTemplate** is set to **"1fr 1fr 1fr"**, it contains three columns. The elements are arranged in the same direction as the main axis runs down the columns. Elements outside the **\<Grid>** area can be viewed through scrolling.
The **\<Grid>** arranges elements in the specified direction and allows for scrolling to display excess elements. For example, if the **\<Grid>** has 10 elements and **columnsTemplate** is set to **"1fr 1fr 1fr"**, it contains three columns. The elements are arranged in the same direction as the main axis runs down the columns. Elements outside the **\<Grid>** area can be viewed through scrolling.
In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, **minCount**, and **cellLength**.
In this mode, the following attributes do not take effect: **layoutDirection**, **maxCount**, **minCount**, and **cellLength**.
3. Neither **rowsTemplate** nor **columnsTemplate** is set
The **\<Grid>** arranges elements in the direction specified by **layoutDirection **. The number of columns is jointly determined by the grid width, width of the first element, **minCount**, **maxCount**, and **columnsGap**. The number of rows is jointly determined by the grid height, height of the first element, **cellLength**, and **rowsGap**. Elements outside the determined range of rows and columns are not displayed and cannot be viewed through scrolling.
The **\<Grid>** arranges elements in the direction specified by **layoutDirection **. The number of columns is jointly determined by the grid width, width of the first element, **minCount**, **maxCount**, and **columnsGap**. The number of rows is jointly determined by the grid height, height of the first element, **cellLength**, and **rowsGap**. Elements outside the determined range of rows and columns are not displayed and cannot be viewed through scrolling.
In this mode, only the following attributes take effect: **layoutDirection**, **maxCount**, **minCount**, **cellLength**, **editMode**, **columnsGap**, and **rowsGap**.
In this mode, only the following attributes take effect: **layoutDirection**, **maxCount**, **minCount**, **cellLength**, **editMode**, **columnsGap**, and **rowsGap**.
## GridDirection<sup>8+</sup>
......
# GridCol
The **\<GridCol>** component must be used as a child component of the [GridRow](ts-container-gridrow.md) container.
The **\<GridCol>** component must be used as a child component of the **[\<GridRow>](ts-container-gridrow.md)** container.
> **NOTE**
>
......@@ -16,10 +16,10 @@ GridCol(option?:{span?: number | GridColColumnOption, offset?: number | GridColC
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------------- | ---- | ------------------------------------------------------------ |
| span | number \| GridColColumnOption | No | Number of occupied columns. If it is set to **0**, the element is not involved in layout calculation, that is, the element is not rendered.<br>Default value: **1**|
| offset | number \| GridColColumnOption | No | Number of offset columns relative to the previous child component of the grid<br>Default value: **0** |
| order | number \| GridColColumnOption | No | Sequence number of the element. Child components of the grid are sorted in ascending order based on their sequence numbers.<br>Default value: **0**|
| ------ | ----------------------------------------------------- | ---- | ------------------------------------------------------------ |
| span | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Number of occupied columns. If it is set to **0**, the element is not involved in layout calculation, that is, the element is not rendered.<br>Default value: **1**|
| offset | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Number of offset columns relative to the previous child component of the grid<br>Default value: **0** |
| order | number \| [GridColColumnOption](#gridcolcolumnoption) | No | Sequence number of the element. Child components of the grid are sorted in ascending order based on their sequence numbers.<br>Default value: **0**|
## Attributes
......
......@@ -4,6 +4,8 @@ The **\<GridContainer>** component lays out components vertically. It is used on
> **NOTE**
>
> This component is deprecated since API version 9. You are advised to use **[\<GridCol>](ts-container-gridcol.md)** and **[\<GridRow>](ts-container-gridrow.md)** instead.
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
......@@ -22,8 +24,8 @@ GridContainer(value?: { columns?: number | 'auto', sizeType?: SizeType, gutter?:
| -------- | -------- | -------- | -------- |
| columns | number \| 'auto' | No| Total number of columns in the current layout.<br>Default value: **'auto'**|
| sizeType | SizeType | No| Device size type.<br>Default value: **SizeType.Auto**|
| gutter | number \| string | No| Gutter of the grid layout.|
| margin | number \| string | No| Margin of the grid layout.|
| gutter | number \| string | No| Gutter of the grid layout. This parameter cannot be set to a percentage. |
| margin | number \| string | No| Margin of the grid layout. This parameter cannot be set to a percentage. |
## SizeType
......
......@@ -133,17 +133,18 @@ onBreakpointChange(callback: (breakpoints: string) => void)
struct GridRowExample {
@State bgColors: Color[] = [Color.Red, Color.Orange, Color.Yellow, Color.Green, Color.Pink, Color.Grey, Color.Blue, Color.Brown]
@State currentBp: string = 'unknown'
build() {
Column() {
GridRow({
columns: 5,
gutter: {x:5, y:10},
breakpoints: {value:["400vp", "600vp", "800vp"],
reference: BreakpointsReference.WindowSize},
gutter: { x: 5, y: 10 },
breakpoints: { value: ["400vp", "600vp", "800vp"],
reference: BreakpointsReference.WindowSize },
direction: GridRowDirection.Row
}) {
ForEach(this.bgColors, (color)=>{
GridCol({ span: {xs:1, sm:2, md:3, lg:4}}) {
ForEach(this.bgColors, (color) => {
GridCol({ span: { xs: 1, sm: 2, md: 3, lg: 4 } }) {
Row().width("100%").height("20vp")
}.borderColor(color).borderWidth(2)
})
......@@ -151,8 +152,8 @@ struct GridRowExample {
.onBreakpointChange((breakpoint) => {
this.currentBp = breakpoint
})
}.width('80%').margin({ left: 10,top: 5, bottom:5 }).height(200)
.border({color:Color.Blue, width:2})
}.width('80%').margin({ left: 10, top: 5, bottom: 5 }).height(200)
.border({ color: '#880606', width: 2 })
}
}
```
......
......@@ -10,7 +10,7 @@ The **\<list>** component provides a list container that presents a series of li
## Child Components
This component supports the [\<ListItem>](ts-container-listitem.md) and [\<ListItemGroup>](ts-container-listitemgroup.md) child components.
This component supports the **[\<ListItem>](ts-container-listitem.md)** and **[\<ListItemGroup>](ts-container-listitemgroup.md)** child components.
## APIs
......@@ -34,14 +34,14 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| listDirection | [Axis](ts-appendix-enums.md#axis) | Direction in which the list items are arranged.<br>Default value: **Axis.Vertical**|
| divider | {<br>strokeWidth: [Length](ts-types.md#length),<br>color?:[ResourceColor](ts-types.md),<br>startMargin?: Length,<br>endMargin?: Length<br>} \| null | Style of the divider for the list items. By default, there is no divider.<br>- **strokeWidth**: stroke width of the divider.<br>- **color**: color of the divider.<br>- **startMargin**: distance between the divider and the start edge of the list.<br>- **endMargin**: distance between the divider and the end edge of the list.|
| scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.<br>Default value: **BarState.Off**|
| cachedCount | number | Number of list items to be preloaded. For details, see [Minimizing White Blocks During Swiping](../../ui/ui-ts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).<br>Default value: **1**|
| editMode | boolean | Whether to enter editing mode.<br>Default value: **false**|
| cachedCount | number | Number of list items or list item groups to be preloaded. A list item group is calculated as a whole, and all list items of the group are preloaded at the same time. For details, see [Minimizing White Blocks During Swiping](../../ui/ui-ts-performance-improvement-recommendation.md#minimizing-white-blocks-during-swiping).<br>Default value: **1**|
| editMode<sup>(deprecated)</sup> | boolean | Whether to enter editing mode.<br>This API is deprecated since API version 9.<br>Default value: **false**|
| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect.<br>Default value: **EdgeEffect.Spring**|
| chainAnimation | boolean | Whether to display chained animations on this list when it slides or its top or bottom is dragged. The list items are separated with even space, and one item animation starts after the previous animation during basic sliding interactions. The chained animation effect is similar with spring physics.<br>Default value: **false**<br>- **false**: No chained animations are displayed.<br>- **true**: Chained animations are displayed.|
| multiSelectable<sup>8+</sup> | boolean | Whether to enable mouse frame selection.<br>Default value: **false**<br>- **false**: The mouse frame selection is disabled.<br>- **true**: The mouse frame selection is enabled.|
| lanes<sup>9+</sup> | number \| [LengthConstrain](ts-types.md#lengthconstrain) | In the following description, **listDirection** is set to **Axis.Vertical**:<br>Number of columns in which the list items are arranged along the cross axis.<br>Default value: **1**<br>The rules are as follows:<br>- If the value is set to a number, the column width is determined based on the specified number and the cross-axis width of the **\<List>** component.<br>- If the value is set to {minLength, maxLength}, the number of columns is adjusted adaptively based on the width of the **\<List>** component, ensuring that the width respects the {minLength, maxLength} constraints during adaptation. The **minLength** constraint is prioritized. For example, if **lanes** is set to **{minLength: 40vp, maxLength: 60vp}** and the width of the **\<List>** component is 70 vp, the list items are arranged in one column with their alignment compliant with the **alignListItem** settings. If the width of the **\<List>** component is changed to 80 vp, which is twice the value of **minLength**, the list items are arranged in two columns.|
| alignListItem<sup>9+</sup> | ListItemAlign | Alignment mode of list items along the cross axis when: Cross-axis width of the **\<List>** component > Cross-axis width of list items x Value of **lanes**.<br>Default value: **ListItemAlign.Start**|
| sticky<sup>9+</sup> | StickyStyle | Whether to pin the header to the top or the footer to the bottom in the **\<ListItemGroup>** component. This attribute is used together with the **\<ListItemGroup>** component.<br>Default value: **StickyStyle.None**<br>**NOTE**<br>The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.|
| sticky<sup>9+</sup> | StickyStyle | Whether to pin the header to the top or the footer to the bottom in the **\<ListItemGroup>** component. This attribute is used together with the **[\<ListItemGroup>](ts-container-listitemgroup.md)** component.<br>Default value: **StickyStyle.None**<br>**NOTE**<br>The **sticky** attribute can be set to **StickyStyle.Header** or \| **StickyStyle.Footer** to support both the pin-to-top and pin-to-bottom features.|
## ListItemAlign<sup>9+</sup>
......@@ -65,13 +65,13 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Description|
| -------- | -------- |
| onItemDelete(event: (index: number) => boolean) | Triggered when a list item is deleted.<br>- **index**: index of the deleted list item.|
| onItemDelete<sup>(deprecated)</sup>(event: (index: number) => boolean) | Triggered when a list item is deleted.<br>This API is deprecated since API version 9.<br>- **index**: index of the deleted list item.|
| onScroll(event: (scrollOffset: number, scrollState: ScrollState) => void) | Triggered when the list scrolls.<br>- **scrollOffset**: scroll offset.<br>- **[scrollState](#scrollstate)**: current scroll state.|
| onScrollIndex(event: (start: number, end: number) => void) | Triggered when scrolling starts.<br>When calculating the index value, the **\<ListItemGroup>** accounts for one index value as a whole, and the index values of the list items within are not calculated.<br>- **start**: index of the scroll start position.<br>- **end**: index of the scroll end position.|
| onReachStart(event: () => void) | Triggered when the list reaches the start position.|
| onReachEnd(event: () => void) | Triggered when the list reaches the end position.|
| onScrollBegin<sup>9+</sup>(event: (dx: number, dy: number) => { dxRemain: number, dyRemain: number }) | Triggered when the list starts to scroll.<br>- **dx**: amount by which the list will scroll in the horizontal direction.<br>- **dy**: amount by which the list will scroll in the vertical direction.<br>- **dxRemain**: remaining amount by which the list can scroll in the horizontal direction.<br>- **dyRemain**: remaining amount by which the list can scroll in the vertical direction.|
| onScrollStop(event: () => void) | Triggered when the list stops scrolling.|
| onScrollBegin<sup>9+</sup>(event: (dx: number, dy: number) => { dxRemain: number, dyRemain: number }) | Triggered when the list starts to scroll. The input parameters indicate the amount by which the list will scroll. The event handler then works out the amount by which the list needs to scroll based on the real-world situation and returns the result.<br>- **dx**: amount by which the list will scroll in the horizontal direction.<br>- **dy**: amount by which the list will scroll in the horizontal direction.<br>- **dxRemain**: amount by which the list actually scrolls in the horizontal direction.<br>- **dyRemain**: amount by which the list actually scrolls in the vertical direction.|
| onScrollStop(event: () => void) | Triggered when the list stops scrolling after the user's finger leaves the screen. This event will not be triggered if the scrolling is initiated by using [Scroller](ts-container-scroll.md#scroller).|
| onItemMove(event: (from: number, to: number) => boolean) | Triggered when a list item moves.<br>- **from**: index of the item before moving.<br>- **to**: index of the item after moving.|
| onItemDragStart(event: (event: ItemDragInfo, itemIndex: number) => ((() => any) \| void) | Triggered when a list element starts to be dragged.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).<br>- **itemIndex**: index of the dragged list element.|
| onItemDragEnter(event: (event: ItemDragInfo) => void) | Triggered when the dragged item enters the drop target of the list.<br>- **event**: See [ItemDragInfo](ts-container-grid.md#itemdraginfo).|
......@@ -84,12 +84,12 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name | Description |
| ------ | ------------------------- |
| Idle | Not scrolling. |
| Scroll | Inertial scrolling. |
| Fling | Finger dragging. |
| Scroll | Finger dragging. |
| Fling | Inertial scrolling. |
> **NOTE**
>
> To enable the editable mode for a list, the following conditions must be met:
> To enable the editable mode for a list, the following conditions must be met: (This feature is deprecated since API version 9.)
>
> - **editMode** is set to **true**.
>
......@@ -99,7 +99,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
>
> To enable dragging for a list item, the following conditions must be met:
>
> - **editMode** is set to **true**.
> - **editMode** is set to **true**. (This is not required since API version 9.)
>
> - The list item is bound to the **onDragStart** event and the event returns a floating UI during event callback.
......@@ -112,10 +112,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
@Component
struct ListExample {
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@State editFlag: boolean = false
build() {
Stack({ alignContent: Alignment.TopStart }) {
Column() {
List({ space: 20, initialIndex: 0 }) {
ForEach(this.arr, (item) => {
......@@ -123,32 +121,22 @@ struct ListExample {
Text('' + item)
.width('100%').height(100).fontSize(16)
.textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF)
}.editable(true)
}
}, item => item)
}
.listDirection(Axis.Vertical) // Arrangement direction
.divider({ strokeWidth: 2, color: 0xFFFFFF, startMargin: 20, endMargin: 20 }) // Divider
.edgeEffect(EdgeEffect.None) // No effect when the list scrolls to the edge.
.chainAnimation(false) // Chained animations are disabled.
.edgeEffect(EdgeEffect.Spring) // No effect when the list scrolls to the edge.
.onScrollIndex((firstIndex: number, lastIndex: number) => {
console.info('first' + firstIndex)
console.info('last' + lastIndex)
})
.editMode(this.editFlag)
.onItemDelete((index: number) => {
console.info(this.arr[index] + 'Delete')
this.arr.splice(index, 1)
console.info(JSON.stringify(this.arr))
this.editFlag = false
return true
}).width('90%')
}.width('100%')
Button('edit list')
.onClick(() => {
this.editFlag = !this.editFlag
}).margin({ top: 5, left: 20 })
}.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 })
.width('90%')
}
.width('100%')
.height('100%')
.backgroundColor(0xDCDCDC)
.padding({ top: 5 })
}
}
```
......
......@@ -22,20 +22,21 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Description|
| -------- | -------- | -------- |
| sticky | [Sticky](#sticky)| Sticky effect of the list item.<br>Default value: **Sticky.None**|
| editable | boolean \| [EditMode](#editmode)| Whether to enter editing mode, where the list item can be deleted or moved.<br>Default value: **false**|
| sticky<sup>(deprecated)</sup> | [Sticky](#stickydeprecated) | Sticky effect of the list item.<br>Default value: **Sticky.None**<br>This API is deprecated since API version 9. You are advised to use **sticky** of the [\<List>](ts-container-list.md#attributes) component. |
| editable<sup>(deprecated)</sup> | boolean \| [EditMode](#editmodedeprecated) | Whether to enter editing mode, where the list item can be deleted or moved.<br>This API is deprecated since API version 9.<br>Default value: **false**|
| selectable<sup>8+</sup> | boolean | Whether the current list item is selectable by mouse drag.<br>**NOTE**<br>This attribute takes effect only when mouse frame selection is enabled for the parent **\<List>** container.<br>Default value: **true**|
| swipeAction<sup>9+</sup> | {<br>start?: CustomBuilder,<br>end?:CustomBuilder,<br>edgeEffect?: [SwipeEdgeEffect](#swipeedgeeffect9),<br>} | Component displayed when the list item is swiped out from the screen edge.<br>- **start**: component on the left of the list item when the item is swiped to the right (in vertical list layout) or component above the list item when the item is swiped down (in horizontal list layout).<br>- **end**: component on the right of the list item when the item is swiped to the left (in vertical list layout) or component below the list item when the item is swiped up (in horizontal list layout).<br>- **edgeEffect**: scroll effect.<br>|
## Sticky
## Sticky<sup>(deprecated)</sup>
This API is deprecated since API version 9. You are advised to use [stickyStyle](ts-container-list.md#stickystyle9) of the **\<List>** component.
| Name| Description|
| -------- | -------- |
| None | The list item is not sticky.|
| Normal | The list item is sticky with no special effects.|
| Opacity | The list item is sticky with opacity changes.|
## EditMode
## EditMode<sup>(deprecated)</sup>
This API is deprecated since API version 9.
| Name | Description |
| ------ | --------- |
| None | The editing operation is not restricted. |
......@@ -63,41 +64,24 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
@Component
struct ListItemExample {
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@State editFlag: boolean = false
build() {
Column() {
List({ space: 20, initialIndex: 0 }) {
ListItem() {
Text('sticky:Normal , click me edit list')
.width('100%').height(40).fontSize(12).fontColor(0xFFFFFF)
.textAlign(TextAlign.Center).backgroundColor(0x696969)
.onClick(() => {
this.editFlag = !this.editFlag
})
}.sticky(Sticky.Normal)
ForEach(this.arr, (item) => {
ListItem() {
Text('' + item)
.width('100%').height(100).fontSize(16)
.textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF)
}.editable(this.editFlag)
}, item => item)
}
.editMode(true)
.onItemDelete((index: number) => {
console.info(this.arr[index - 1] + 'Delete')
this.arr.splice(index - 1,1)
this.editFlag = false
return true
}).width('90%')
}, item => item)
}.width('90%')
}.width('100%').height('100%').backgroundColor(0xDCDCDC).padding({ top: 5 })
}
}
```
![en-us_image_0000001257138339](figures/en-us_image_0000001257138339.gif)
![en-us_image_0000001219864159](figures/en-us_image_0000001219864159.gif)
```ts
// xxx.ets
......
......@@ -4,11 +4,11 @@ The **\<ListItemGroup>** component is used to display list item groups. It must
> **NOTE**
>
> - This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Usage Guidelines
If the **listDirection** attribute of the parent **\<List>** component is set to **Axis.Vertical**, the **height** attribute of the **\<ListItemGroup>** component cannot be set. The height of a **\<ListItemGroup>** component is the sum of its header height, footer height, and total height of the list items. If the **listDirection** attribute of the parent **\<List>** component is set to **Axis.Horizontal**, the **width** attribute of the **\<ListItemGroup>** component cannot be set. The width of a **\<ListItemGroup>** component is the sum of its header width, footer width, and total width of the list items.
Currently, the list items in the **\<ListItemGroup>** component cannot be edited, selected, or dragged. That is, the **editable** and **selectable** attributes of these list items do not take effect.
The list items in the **\<ListItemGroup>** component cannot be edited, selected, or dragged. That is, the **editable** and **selectable** attributes of these list items do not take effect.
## Child Components
......@@ -38,28 +38,6 @@ ListItemGroup(options?: {header?: CustomBuilder, footer?: CustomBuilder, space?:
```ts
// xxx.ets
function itemHeadBuilder(text: string) {
@Builder function itemHead() {
Text(text)
.fontSize(20)
.backgroundColor(0xAABBCC)
.width("100%")
.padding(10)
}
return itemHead
}
function itemFootBuilder(num: number) {
@Builder function itemFoot() {
Text(''Total lessons:'+ num")
.fontSize(16)
.backgroundColor(0xAABBCC)
.width("100%")
.padding(5)
}
return itemFoot
}
@Entry
@Component
struct ListItemGroupExample {
......@@ -82,11 +60,27 @@ struct ListItemGroupExample {
}
]
@Builder itemHead(text:string) {
Text(text)
.fontSize(20)
.backgroundColor(0xAABBCC)
.width("100%")
.padding(10)
}
@Builder itemFoot(num:number) {
Text(''Total lessons:'+ num")
.fontSize(16)
.backgroundColor(0xAABBCC)
.width("100%")
.padding(5)
}
build() {
Column() {
List({ space: 20 }) {
ForEach(this.timetable, (item) => {
ListItemGroup({ header:itemHeadBuilder(item.title), footer:itemFootBuilder(item.projects.length) }) {
ListItemGroup({ header:this.itemHead(item.title), footer:this.itemFoot(item.projects.length) }) {
ForEach(item.projects, (project) => {
ListItem() {
Text(project)
......
......@@ -78,7 +78,7 @@ import router from '@ohos.router'
@Component
struct DetailExample {
// Receive the input parameters of Navigator.ets.
@State text: any = router.getParams().text
@State text: any = router.getParams()['text']
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
......
......@@ -6,6 +6,8 @@ The **\<RelativeContainer>** component is used for element alignment in complex
>
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Rules
* Components in a container are aligned horizontally or vertically.
......@@ -14,7 +16,7 @@ The **\<RelativeContainer>** component is used for element alignment in complex
* A child component can set the container or another child component as the anchor.
* To show in the **\<RelativeContainer>**, child components must have an ID. The container ID is fixed at **__container__**.
* Three positions of the child component in a direction can use three positions of the container or another child components in the same direction as anchors. If anchors are set for more than two positions in a single direction, the third position is skipped.
* The child component size set on the frontend page is not affected by the **\<RelativeContainer>** rules.
* The child component size set on the frontend page is not affected by the **\<RelativeContainer>** rules. If two or more **alignRules** values are set for one direction of the child component, you are not advised to set the size for this direction.
* If offset is required after the alignment, it can be set through **offset**.
* Exceptions
* When a mutual or circular dependency occurs, none of the child components in the container are drawn.
......@@ -37,62 +39,60 @@ RelativeContainer()
struct Index {
build() {
Row() {
Button("Extra button").width(100).height(50)
RelativeContainer() {
Button("Button 1")
.width(120)
.height(30)
Row().width(100).height(100)
.backgroundColor("#FF3333")
.alignRules({
middle: { anchor: "__container__", align: HorizontalAlign.Center },
top: {anchor: "__container__", align: VerticalAlign.Top},
left: {anchor: "__container__", align: HorizontalAlign.Start}
})
.id("bt1")
.borderWidth(1)
.borderColor(Color.Black)
.id("row1")
Text("This is text 2")
.fontSize(20)
.padding(10)
Row().width(100).height(100)
.backgroundColor("#FFCC00")
.alignRules({
bottom: { anchor: "__container__", align: VerticalAlign.Bottom },
top: { anchor: "bt1", align: VerticalAlign.Bottom },
right: { anchor: "bt1", align: HorizontalAlign.Center }
top: {anchor: "__container__", align: VerticalAlign.Top},
right: {anchor: "__container__", align: HorizontalAlign.End}
})
.id("tx2")
.borderWidth(1)
.borderColor(Color.Black)
.height(30)
Button("Button 3")
.width(100)
.height(100)
.id("row2")
Row().height(100)
.backgroundColor("#FF6633")
.alignRules({
left: { anchor: "bt1", align: HorizontalAlign.End },
top: { anchor: "tx2", align: VerticalAlign.Center },
bottom: { anchor: "__container__", align: VerticalAlign.Bottom }
top: {anchor: "row1", align: VerticalAlign.Bottom},
left: {anchor: "row1", align: HorizontalAlign.End},
right: {anchor: "row2", align: HorizontalAlign.Start}
})
.id("bt3")
.borderWidth(1)
.borderColor(Color.Black)
.id("row3")
Text("This is text 4")
.fontSize(20)
.padding(10)
Row()
.backgroundColor("#FF9966")
.alignRules({
left: { anchor: "tx2", align: HorizontalAlign.End },
right: { anchor: "__container__", align: HorizontalAlign.End },
top: { anchor: "__container__", align: VerticalAlign.Top },
bottom: { anchor: "bt3", align: VerticalAlign.Top }
top: {anchor: "row3", align: VerticalAlign.Bottom},
bottom: {anchor: "__container__", align: VerticalAlign.Bottom},
left: {anchor: "__container__", align: HorizontalAlign.Start},
right: {anchor: "row1", align: HorizontalAlign.End}
})
.id("tx4")
.borderWidth(1)
.borderColor(Color.Black)
.id("row4")
Row()
.backgroundColor("#FF66FF")
.alignRules({
top: {anchor: "row3", align: VerticalAlign.Bottom},
bottom: {anchor: "__container__", align: VerticalAlign.Bottom},
left: {anchor: "row2", align: HorizontalAlign.Start},
right: {anchor: "__container__", align: HorizontalAlign.End}
})
.id("row5")
}
.width(200).height(200)
.backgroundColor(Color.Orange)
.width(300).height(300)
.margin({left: 100})
.border({width:2, color: "#6699FF"})
}
.height('100%')
}
}
```
![relative container](figures/relativecontainer.png)
......@@ -6,12 +6,10 @@ The **\<RowSplit>** lays out child components horizontally and inserts a vertica
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
Supported
## APIs
RowSplit()
......@@ -21,7 +19,7 @@ RowSplit()
| Name| Type| Description|
| -------- | -------- | -------- |
| resizeable | boolean | Whether the divider can be dragged. The default value is **false**.|
| resizeable | boolean | Whether the divider can be dragged.<br>Default value: **false** |
> **NOTE**
>
......
......@@ -236,17 +236,21 @@ struct ScrollExample {
struct NestedScroll {
@State listPosition: number = 0; // 0 indicates scrolling to the top of the list, 1 indicates scrolling to the middle of the list, and 2 indicates scrolling to the bottom of the list.
private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
private scroller: Scroller = new Scroller()
private scrollerForScroll: Scroller = new Scroller()
private scrollerForList: Scroller = new Scroller()
build() {
Flex() {
Scroll(this.scroller) {
Scroll(this.scrollerForScroll) {
Column() {
Text("Scroll Area")
.width("100%").height("40%").backgroundColor(0X330000FF)
.fontSize(16).textAlign(TextAlign.Center)
.onClick(() => {
this.scrollerForList.scrollToIndex(5)
})
List({ space: 20 }) {
List({ space: 20, scroller: this.scrollerForList }) {
ForEach(this.arr, (item) => {
ListItem() {
Text("ListItem" + item)
......@@ -255,7 +259,9 @@ struct NestedScroll {
}.width("100%").height(100)
}, item => item)
}
.width("100%").height("50%").edgeEffect(EdgeEffect.None)
.width("100%")
.height("50%")
.edgeEffect(EdgeEffect.None)
.onReachStart(() => {
this.listPosition = 0
})
......@@ -264,7 +270,7 @@ struct NestedScroll {
})
.onScrollBegin((dx: number, dy: number) => {
if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) {
this.scroller.scrollBy(0, -dy)
this.scrollerForScroll.scrollBy(0, -dy)
return { dxRemain: dx, dyRemain: 0 }
}
this.listPosition = 1
......
......@@ -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>
......
......@@ -39,4 +39,4 @@ struct StackExample {
}
```
![en-us_image_0000001212378400](figures/en-us_image_0000001212378400.jpg)
![en-us_image_0000001219982699](figures/en-us_image_0000001219982699.PNG)
......@@ -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,14 +52,6 @@ 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.
......@@ -84,9 +76,9 @@ Stops an animation.
**Parameters**
| Name | Type | Mandatory.| Description|
| 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,15 @@ onChange(event: (index: number) => void)
Triggered when the index of the currently displayed child component changes.
**Parameters**
> **NOTE**
>
> When the **\<Swiper>** component is used together with **LazyForEach**, the subpage UI cannot be refreshed in the **onChange** event.
| Name | Type | Mandatory.| Description|
| --------- | ---------- | ------ | -------- |
| index | number | Yes | Index of the currently displayed element.|
**Return value**
| Name | Type | Description|
| --------- | ---------- | -------- |
| index | number | Index of the currently displayed element.|
## Example
......@@ -149,36 +145,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)
......@@ -23,7 +23,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Type| Description|
| -------- | -------- | -------- |
| tabBar | string \| Resource \| {<br>icon?: string \| Resource,<br>text?: string \| Resource<br>}<br>\| [CustomBuilder](ts-types.md)<sup>8+</sup> | Content displayed on the tab bar.<br>**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).<br>**NOTE**<br>If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image. |
| tabBar | string \| Resource \| {<br>icon?: string \| Resource,<br>text?: string \| Resource<br>}<br>\| [CustomBuilder](ts-types.md)<sup>8+</sup> | Content displayed on the tab bar.<br>**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).<br>> **NOTE**<br>If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image.|
> **NOTE**
> - The **\<TabContent>** component does not support setting of the common width attribute. By default, its width is the same as that of the parent **\<Tabs>** component.
......@@ -33,82 +33,164 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
## Example
Example 1:
```ts
// xxx.ets
@Entry
@Component
struct TabContentExample {
@State fontColor: string = 'rgba(0, 0, 0, 0.4)'
@State selectedFontColor: string = 'rgba(10, 30, 255, 1)'
@State fontColor: string = '#182431'
@State selectedFontColor: string = '#007DFF'
@State currentIndex: number = 0
private controller: TabsController = new TabsController()
@Builder TabBuilder(index: number) {
Column() {
Image(this.currentIndex === index ? '/resources/ic_public_contacts_filled_selected.png' : '/resources/ic_public_contacts_filled.png')
.width(10)
.height(10)
.opacity(this.currentIndex === index ? 1 : 0.4)
Image(this.currentIndex === index ? '/common/public_icon_on.svg' : '/common/public_icon_off.svg')
.width(24)
.height(24)
.margin({ bottom: 4 })
.objectFit(ImageFit.Contain)
Text(`Tab${(index > 2 ? (index - 1) : index) + 1}`)
Text(`Tab${index + 1}`)
.fontColor(this.currentIndex === index ? this.selectedFontColor : this.fontColor)
.fontSize(10)
.margin({top: 2})
}
}
@Builder AddBuilder() {
Column() {
Image(this.currentIndex === 2 ? '/resources/ic_public_add_norm_filled_selected.png' : '/resources/ic_public_add_norm_filled.png')
.width(this.currentIndex === 2 ? 26 : 24)
.height(this.currentIndex === 2 ? 26 : 24)
.opacity(this.currentIndex === 2 ? 1 : 0.4)
.objectFit(ImageFit.Contain)
.animation({duration: 200})
}
.fontWeight(500)
.lineHeight(14)
}.width('100%')
}
build() {
Column() {
Tabs({ barPosition: BarPosition.End, controller: this.controller }) {
TabContent() {
Flex({justifyContent: FlexAlign.Center}) {
Text('Tab1').fontSize(32)
}
Column() {
Text('Tab1')
.fontSize(36)
.fontColor('#182431')
.fontWeight(500)
.opacity(0.4)
.margin({ top: 30, bottom: 56.5 })
Divider()
.strokeWidth(0.5)
.color('#182431')
.opacity(0.05)
}.width('100%')
}.tabBar(this.TabBuilder(0))
TabContent() {
Flex({justifyContent: FlexAlign.Center}) {
Text('Tab2').fontSize(32)
}
Column() {
Text('Tab2')
.fontSize(36)
.fontColor('#182431')
.fontWeight(500)
.opacity(0.4)
.margin({ top: 30, bottom: 56.5 })
Divider()
.strokeWidth(0.5)
.color('#182431')
.opacity(0.05)
}.width('100%')
}.tabBar(this.TabBuilder(1))
TabContent() {
Flex({justifyContent: FlexAlign.Center}) {
Text('Add').fontSize(32)
}
}.tabBar(this.AddBuilder())
Column() {
Text('Tab3')
.fontSize(36)
.fontColor('#182431')
.fontWeight(500)
.opacity(0.4)
.margin({ top: 30, bottom: 56.5 })
Divider()
.strokeWidth(0.5)
.color('#182431')
.opacity(0.05)
}.width('100%')
}.tabBar(this.TabBuilder(2))
TabContent() {
Flex({justifyContent: FlexAlign.Center}) {
Text('Tab3').fontSize(32)
}
Column() {
Text('Tab4')
.fontSize(36)
.fontColor('#182431')
.fontWeight(500)
.opacity(0.4)
.margin({ top: 30, bottom: 56.5 })
Divider()
.strokeWidth(0.5)
.color('#182431')
.opacity(0.05)
}.width('100%')
}.tabBar(this.TabBuilder(3))
}
.vertical(false)
.barHeight(56)
.onChange((index: number) => {
this.currentIndex = index
})
.width(360)
.height(190)
.backgroundColor('#F1F3F5')
.margin({ top: 38 })
}.width('100%')
}
}
```
TabContent() {
Flex({justifyContent: FlexAlign.Center}) {
Text('Tab4').fontSize(32)
![tabContent](figures/tabContent1.gif)
Example 2:
```ts
// xxx.ets
@Entry
@Component
struct TabContentExample {
@State fontColor: string = '#182431'
@State selectedFontColor: string = '#007DFF'
@State currentIndex: number = 0
private controller: TabsController = new TabsController()
@Builder TabBuilder(index: number) {
Column() {
Image(this.currentIndex === index ? '/common/public_icon_on.svg' : '/common/public_icon_off.svg')
.width(24)
.height(24)
.margin({ bottom: 4 })
.objectFit(ImageFit.Contain)
Text('Tab')
.fontColor(this.currentIndex === index ? this.selectedFontColor : this.fontColor)
.fontSize(10)
.fontWeight(500)
.lineHeight(14)
}.width('100%').height('100%').justifyContent(FlexAlign.Center)
}
}.tabBar(this.TabBuilder(4))
build() {
Column() {
Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
TabContent()
.tabBar(this.TabBuilder(0))
TabContent()
.tabBar(this.TabBuilder(1))
TabContent()
.tabBar(this.TabBuilder(2))
TabContent()
.tabBar(this.TabBuilder(3))
}
.vertical(false)
.barWidth(300).barHeight(56)
.vertical(true)
.barWidth(96)
.barHeight(414)
.onChange((index: number) => {
this.currentIndex = index
})
.width('90%').backgroundColor('rgba(241, 243, 245, 0.95)')
}.width('100%').height(200).margin({ top: 5 })
.width(96)
.height(414)
.backgroundColor('#F1F3F5')
.margin({ top: 52 })
}.width('100%')
}
}
```
![en-us_image_0000001256978331](figures/en-us_image_0000001256978331.gif)
![tabContent](figures/tabContent2.gif)
......@@ -2,14 +2,14 @@
The **\<Tabs>** component is a container component that allows users to switch between content views through tabs. Each tab page corresponds to a content view.
> **NOTE**
> **NOTE**<br>
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
This component can contain multiple [\<TabContent>](ts-container-tabcontent.md) components.
Only the [\<TabContent>](ts-container-tabcontent.md) child component is supported.
## APIs
......@@ -20,7 +20,7 @@ Tabs(value?: {barPosition?: BarPosition, index?: number, controller?: [TabsContr
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| barPosition | BarPosition | No| Tab bar position for creating the **\<Tabs>** container component.<br>Default value: **BarPosition.Start**|
| barPosition | BarPosition | No| Position of the **\<Tabs>** component.<br>Default value: **BarPosition.Start**|
| index | number | No| Initial tab index.<br>Default value: **0**|
| controller | [TabsController](#tabscontroller) | No| Tab controller.|
......@@ -49,8 +49,8 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| Name| Description|
| -------- | -------- |
| Scrollable | The width of each tab is defined by its label length. The tabs are scrollable when the total width exceeds the tab bar width.|
| Fixed | The width of each tab is fixed, determined by evenly allocating the tab bar width among the tabs.|
| Scrollable | The width of each tab is determined by the actual layout. The tabs are scrollable in the following case: In horizontal layout, the total width exceeds the tab bar width; in horizontal layout, the total height exceeds the tab bar height.|
| Fixed | The width of each tab is determined by equally dividing the number of tabs by the bar width (or the bar height in vertical layout).|
## Events
......@@ -62,7 +62,7 @@ In addition to the [universal events](ts-universal-events-click.md), the followi
## TabsController
Defines a tab controller, which is used to control switching of tabs.
Defines a tab controller, which is used to control switching of tabs. One **TabsController** cannot control multiple **\<Tabs>** components.
### Objects to Import
......@@ -91,36 +91,60 @@ Switches to the specified tab.
@Entry
@Component
struct TabsExample {
@State fontColor: string = '#182431'
@State selectedFontColor: string = '#007DFF'
@State currentIndex: number = 0
private controller: TabsController = new TabsController()
@Builder TabBuilder(index: number, name: string) {
Column() {
Text(name)
.fontColor(this.currentIndex === index ? this.selectedFontColor : this.fontColor)
.fontSize(16)
.fontWeight(this.currentIndex === index ? 500 : 400)
.lineHeight(22)
.margin({ top: 17, bottom: 7 })
Divider()
.strokeWidth(2)
.color('#007DFF')
.opacity(this.currentIndex === index ? 1 : 0)
}.width('100%')
}
build() {
Column() {
Tabs({ barPosition: BarPosition.Start, controller: this.controller }) {
TabContent() {
Column().width('100%').height('100%').backgroundColor(Color.Pink)
}.tabBar('pink')
Column().width('100%').height('100%').backgroundColor('#00CB87')
}.tabBar(this.TabBuilder(0, 'green'))
TabContent() {
Column().width('100%').height('100%').backgroundColor(Color.Yellow)
}.tabBar('yellow')
Column().width('100%').height('100%').backgroundColor('#007DFF')
}.tabBar(this.TabBuilder(1, 'blue'))
TabContent() {
Column().width('100%').height('100%').backgroundColor(Color.Blue)
}.tabBar('blue')
Column().width('100%').height('100%').backgroundColor('#FFBF00')
}.tabBar(this.TabBuilder(2, 'yellow'))
TabContent() {
Column().width('100%').height('100%').backgroundColor(Color.Green)
}.tabBar('green')
Column().width('100%').height('100%').backgroundColor('#E67C92')
}.tabBar(this.TabBuilder(3, 'pink'))
}
.vertical(true).scrollable(true).barMode(BarMode.Fixed)
.barWidth(70).barHeight(150).animationDuration(400)
.vertical(false)
.barMode(BarMode.Fixed)
.barWidth(360)
.barHeight(56)
.animationDuration(400)
.onChange((index: number) => {
console.info(index.toString())
this.currentIndex = index
})
.width('90%').backgroundColor(0xF5F5F5)
}.width('100%').height(150).margin({ top: 5 })
.width(360)
.height(296)
.margin({ top: 52 })
.backgroundColor('#F1F3F5')
}.width('100%')
}
}
```
![en-us_image_0000001212218430](figures/en-us_image_0000001212218430.gif)
![tabs2](figures/tabs2.gif)
# WaterFlow
The **\<WaterFlow>** component is a container that consists of cells formed by rows and columns and arranges items of different sizes from top to bottom according to the preset rules.
> **NOTE**
>
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Child Components
The [\<FlowItem>](ts-container-flowitem.md) child component is supported.
## APIs
WaterFlow(options?: {footer?: CustomBuilder, scroller?: Scroller})
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ----------------------------------------------- | ------ | -------------------------------------------- |
| footer | [CustomBuilder](ts-types.md#custombuilder8) | No | Footer of the **\<WaterFlow>** component. |
| scroller | [Scroller](ts-container-scroll.md#scroller) | No | Controller, which can be bound to scrollable components.<br>The **\<WaterFlow>** component supports only the **scrollToIndex** API of the **\<Scroller>** component.|
## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name| Type| Description|
| -------- | -------- | -------- |
| columnsTemplate | string | Number of columns in the layout. If this attribute is not set, one column is used by default.<br>For example, **'1fr 1fr 2fr'** indicates three columns, with the first column taking up 1/4 of the parent component's full width, the second column 1/4, and the third column 2/4. This attribute supports [auto-fill](#auto-fill).<br>Default value: **'1fr'**|
| rowsTemplate | string | Number of rows in the layout. If this attribute is not set, one row is used by default.<br>For example, **'1fr 1fr 2fr'** indicates three rows, with the first row taking up 1/4 of the parent component's full height, the second row 1/4, and the third row 2/4. This attribute supports [auto-fill](#auto-fill).<br>Default value: **'1fr'**|
| itemConstraintSize | [ConstraintSizeOptions](ts-types.md#constraintsizeoptions) | Size constraints of the child components during layout. |
| columnsGap | Length |Gap between columns.<br>Default value: **0**|
| rowsGap | Length |Gap between rows.<br> Default value: **0**|
| layoutDirection | [FlexDirection](ts-appendix-enums.md#flexdirection) |Main axis direction of the layout.<br>Default value: **FlexDirection.Column**|
The priority of **layoutDirection** is higher than that of **rowsTemplate** and **columnsTemplate**. Depending on the **layoutDirection** settings, there are three layout modes:
- **layoutDirection** is set to **FlexDirection.Column** or **FlexDirection.ColumnReverse**
In this case, **columnsTemplate** is valid. If it is not set, the default value is used. For example, if **columnsTemplate** is set to **"1fr 1fr"** and **rowsTemplate** **"1fr 1fr 1fr"**, child components are arranged in vertical layout, with the cross axis equally divided into two columns.
- **layoutDirection** set to **FlexDirection.Row** or **FlexDirection.RowReverse**
In this case, **rowsTemplate** is valid. If it is not set, the default value is used. For example, if **columnsTemplate** is set to **"1fr 1fr"** and **rowsTemplate** **"1fr 1fr 1fr"**, child components are arranged in horizontal layout, with the cross axis equally divided into three columns.
- **layoutDirection** is not set
In this case, the default value of **layoutDirection** is used, which is **FlexDirection.Column**, and **columnsTemplate** is valid. For example, if **columnsTemplate** is set to **"1fr 1fr"** and **rowsTemplate** **"1fr 1fr 1fr"**, child components are arranged in vertical layout, with the cross axis equally divided into two columns.
## Events
In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| Name| Description|
| -------- | -------- |
| onReachStart(event: () => void) | Triggered when the component reaches the start.|
| onReachEnd(event: () => void) | Triggered when the component reaches the end.|
## auto-fill
The **columnsTemplate** and **rowsTemplate** attributes supports **auto-fill** in the following format:
```css
repeat(auto-fill, track-size)
```
Where, **repeat** and **auto-fill** are keywords, and **track-size** indicates the row height or column width. The supported units include px, vp, %, and digits. The value of **track-size** must contain at least one valid row height or column width.
## Example
```ts
// WaterFlowDataSource.ets
// Object that implements the IDataSource API, which is used by the <WaterFlow> component to load data.
export class WaterFlowDataSource implements IDataSource {
private dataArray: number[] = []
private listeners: DataChangeListener[] = []
constructor() {
for (let i = 0; i < 100; i++) {
this.dataArray.push(i)
}
}
// Obtain the data corresponding to the specified index.
public getData(index: number): any {
return this.dataArray[index]
}
// Notify the controller of data reloading.
notifyDataReload(): void {
this.listeners.forEach(listener => {
listener.onDataReloaded()
})
}
// Notify the controller of data addition.
notifyDataAdd(index: number): void {
this.listeners.forEach(listener => {
listener.onDataAdded(index)
})
}
// Notify the controller of data changes.
notifyDataChange(index: number): void {
this.listeners.forEach(listener => {
listener.onDataChanged(index)
})
}
// Notify the controller of data deletion.
notifyDataDelete(index: number): void {
this.listeners.forEach(listener => {
listener.onDataDeleted(index)
})
}
// Notify the controller of the data location change.
notifyDataMove(from: number, to: number): void {
this.listeners.forEach(listener => {
listener.onDataMoved(from, to)
})
}
// Obtain the total number of data records.
public totalCount(): number {
return this.dataArray.length
}
// Register the data change listener.
registerDataChangeListener(listener: DataChangeListener): void {
if (this.listeners.indexOf(listener) < 0) {
this.listeners.push(listener)
}
}
// Unregister the data change listener.
unregisterDataChangeListener(listener: DataChangeListener): void {
const pos = this.listeners.indexOf(listener)
if (pos >= 0) {
this.listeners.splice(pos, 1)
}
}
// Add data.
public Add1stItem(): void {
this.dataArray.splice(0, 0, this.dataArray.length)
this.notifyDataAdd(0)
}
// Add an item to the end of the data.
public AddLastItem(): void {
this.dataArray.splice(this.dataArray.length, 0, this.dataArray.length)
this.notifyDataAdd(this.dataArray.length-1)
}
// Add an item to the position corresponding to the specified index.
public AddItem(index: number): void {
this.dataArray.splice(index, 0, this.dataArray.length)
this.notifyDataAdd(index)
}
// Delete the first item.
public Delete1stItem(): void {
this.dataArray.splice(0, 1)
this.notifyDataDelete(0)
}
// Delete the second item.
public Delete2ndItem(): void {
this.dataArray.splice(1, 1)
this.notifyDataDelete(1)
}
// Delete the last item.
public DeleteLastItem(): void {
this.dataArray.splice(-1, 1)
this.notifyDataDelete(this.dataArray.length)
}
// Reload data.
public Reload(): void {
this.dataArray.splice(1, 1)
this.dataArray.splice(3, 2)
this.notifyDataReload()
}
}
```
```ts
// WaterflowDemo.ets
import { WaterFlowDataSource } from './WaterFlowDataSource'
@Entry
@Component
struct WaterflowDemo {
@State minSize: number = 50
@State maxSize: number = 100
@State fontSize: number = 24
@State colors: number[] = [0xFFC0CB, 0xDA70D6, 0x6B8E23, 0x6A5ACD, 0x00FFFF, 0x00FF7F]
scroller: Scroller = new Scroller()
datasource: WaterFlowDataSource = new WaterFlowDataSource()
private itemWidthArray: number[] = []
private itemHeightArray: number[] = []
// Calculate the width and height of a flow item.
getSize() {
let ret = Math.floor(Math.random() * this.maxSize)
return (ret > this.minSize ? ret : this.minSize)
}
// Save the width and height of the flow item.
getItemSizeArray() {
for (let i = 0; i < 100; i++) {
this.itemWidthArray.push(this.getSize())
this.itemHeightArray.push(this.getSize())
}
}
aboutToAppear() {
this.getItemSizeArray()
}
@Builder itemFoot() {
Column() {
Text(`Footer`)
.fontSize(10)
.backgroundColor(Color.Red)
.width(50)
.height(50)
.align(Alignment.Center)
.margin({ top: 2 })
}
}
build() {
Column({ space: 2 }) {
WaterFlow({ footer: this.itemFoot, scroller: this.scroller }) {
LazyForEach(this.datasource, (item: number) => {
FlowItem() {
Column() {
Text("N" + item).fontSize(12).height('16')
Image('res/waterFlowTest(' + item % 5 + ').jpg')
.objectFit(ImageFit.Fill)
}
}
.width(this.itemWidthArray[item])
.height(this.itemHeightArray[item])
.backgroundColor(this.colors[item % 5])
}, item => item)
}
.columnsTemplate("1fr 1fr 1fr 1fr")
.itemConstraintSize({
minWidth: 0,
maxWidth: '100%',
minHeight: 0,
maxHeight: '100%'
})
.columnsGap(10)
.rowsGap(5)
.onReachStart(() => {
console.info("onReachStart")
})
.onReachEnd(() => {
console.info("onReachEnd")
})
.backgroundColor(0xFAEEE0)
.width('100%')
.height('80%')
.layoutDirection(FlexDirection.Column)
}
}
}
```
![en-us_image_WaterFlow.gif](figures/waterflow.gif)
......@@ -36,7 +36,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| strokeDashOffset | number \| string | Offset of the start point for drawing the stroke.<br>Default value: **0**|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | Cap style of the stroke.<br>Default value: **LineCapStyle.Butt**|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | Join style of the stroke.<br>Default value: **LineJoinStyle.Miter**|
| strokeMiterLimit | number \| string | Limit value when the sharp angle is drawn as a miter.<br>Default value: **4**<br>**NOTE**<br>This attribute does not take effect because the **\<Circle>** component cannot be used to draw a shape with a sharp angle.|
| strokeMiterLimit | number \| string | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join.<br>Default value: **4**<br>**NOTE**<br>This attribute does not take effect for the **\<Circle>** component, because it does not have a miter join.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| Stroke opacity.<br>Default value: **1**<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.|
| strokeWidth | Length | Stroke width.<br>Default value: **1**|
| antiAlias | boolean | Whether anti-aliasing is enabled.<br>Default value: **true**|
......@@ -53,7 +53,7 @@ struct CircleExample {
Column({ space: 10 }) {
// Draw a circle whose diameter is 150.
Circle({ width: 150, height: 150 })
// Draw a circle with the diameter of 150 and red dashes. (If the width and height are different, the shorter value is used as the diameter.)
// Draw a circle whose diameter is 150 and stroke color is red. (If the width and height values are different, the smaller value will be used as the diameter.)
Circle()
.width(150)
.height(200)
......
......@@ -32,11 +32,11 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.|
| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.|
| stroke | [ResourceColor](ts-types.md) | - |Stroke color. If this attribute is not set, the component does not have any stroke.|
| strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes. |
| strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.|
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.|
| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join.<br>**NOTE**<br>This attribute does not take effect for the **\<Ellipse>** component, because it does not have a miter join.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.|
| strokeWidth | Length | 1 | Stroke width.|
| antiAlias | boolean | true | Whether anti-aliasing is enabled.|
......
# Line
The **\<Line>** component is used to draw a straight line.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components
Not supported
......
......@@ -37,7 +37,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.|
| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>**NOTE**<br>This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the stroke.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.|
| strokeWidth | Length | 1 | Width of the stroke.|
| antiAlias | boolean | true | Whether anti-aliasing is enabled.|
......
......@@ -34,11 +34,11 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.|
| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.|
| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.|
| strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes. |
| strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.|
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.|
| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>**NOTE**<br>This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.|
| strokeWidth | Length | 1 | Stroke width.|
| antiAlias | boolean | true | Whether anti-aliasing is enabled.|
......
......@@ -38,7 +38,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.|
| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>**NOTE**<br>This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.|
| strokeWidth | Length | 1 | Stroke width.|
| antiAlias | boolean | true | Whether anti-aliasing is enabled.|
......
......@@ -44,7 +44,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.|
| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>**NOTE**<br>This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.|
| strokeWidth | Length | 1 | Stroke width.|
| antiAlias | boolean | true | Whether anti-aliasing is enabled.|
......
......@@ -42,7 +42,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.|
| strokeLineJoin | [LineJoinStyle](ts-appendix-enums.md#linejoinstyle) | LineJoinStyle.Miter | Join style of the stroke.|
| strokeMiterLimit | number \| string | 4 | Limit value when the sharp angle is drawn as a miter.|
| strokeMiterLimit | number \| string | 4 | Limit on the ratio of the miter length to the value of **strokeWidth** used to draw a miter join. The miter length indicates the distance from the outer tip to the inner corner of the miter.<br>**NOTE**<br>This attribute must be set to a value greater than or equal to 1 and takes effect when **strokeLineJoin** is set to **LineJoinStyle.Miter**.|
| strokeOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Stroke opacity.<br>**NOTE**<br>The value range is [0.0, 1.0]. If the set value is less than 0.0, **0.0** will be used. If the set value is greater than 1.0, **1.0** will be used.|
| strokeWidth | number \| string | 1 | Stroke width.|
| antiAlias | boolean | true | Whether anti-aliasing is enabled.|
......
......@@ -7,10 +7,12 @@ You can create explicit animation with your custom settings.
> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| animateTo(value: [AnimateParam](#animateparam), event: ()=&gt; void) : void | Provides a transition animation when the status changes due to the closure code.<br>**event** specifies the closure function that displays the dynamic effect. The system automatically inserts the transition animation if the status changes in the closure function.|
animateTo(value: AnimateParam, event: () => void): void
| Name | Type | Mandatory | Description |
| ---------------- | ------------ | -------------------- | -------------------- |
| value | [AnimateParam](#animateparam)| Yes| Animation settings.|
| event | () => void | Yes| Closure function that displays the dynamic effect. The system automatically inserts the transition animation if the status changes in the closure function.|
## AnimateParam
......@@ -18,14 +20,13 @@ You can create explicit animation with your custom settings.
| -------- | -------- | -------- |
| duration | number | Animation duration, in ms.<br>Default value: **1000**|
| tempo | number | Animation playback speed. A larger value indicates faster animation playback, and a smaller value indicates slower animation playback. The value **0** means that there is no animation.<br>Default value: **1.0**|
| curve | Curve \| Curves | Animation curve.<br>Default value: **Curve.Linear**|
| curve | [Curve](ts-appendix-enums.md#curve) \| [ICurve](../apis/js-apis-curve.md#icurve) \| string | Animation curve.<br>Default value: **Curve.Linear**|
| delay | number | Delay of animation playback, in ms. By default, the playback is not delayed.<br>Default value: **0**|
| iterations | number | Number of times that the animation is played. By default, the animation is played once. The value **-1** indicates that the animation is played for an unlimited number of times.<br>Default value: **1**|
| playMode | [PlayMode](ts-appendix-enums.md#playmode) | Animation playback mode. By default, the animation is played from the beginning after the playback is complete.<br>Default value: **PlayMode.Normal**|
| onFinish | () =&gt; void | Callback invoked when the animation playback is complete.|
## Example
```ts
......@@ -33,26 +34,24 @@ You can create explicit animation with your custom settings.
@Entry
@Component
struct AnimateToExample {
@State widthSize: number = 200
@State widthSize: number = 250
@State heightSize: number = 100
@State rotateAngle: number = 0
private flag: boolean = true
build() {
Column() {
Button('click me')
Button('change width and height')
.width(this.widthSize)
.height(this.heightSize)
.backgroundColor(0x317aff)
.onClick((event: ClickEvent) => {
// Animation configuration for the width and height attributes of the <Button> component
.margin(30)
.onClick(() => {
if (this.flag) {
animateTo({
duration: 1000, // Animation duration
tempo: 0.5, // Playback speed
curve: Curve.EaseInOut, // Animation curve
delay: 200, // Animation delay
iterations: 1, // Number of playback times
playMode: PlayMode.Normal // Animation playback mode
duration: 2000,
curve: Curve.EaseOut,
iterations: 3,
playMode: PlayMode.Normal,
onFinish: () => {
console.info('play end')
}
......@@ -61,25 +60,39 @@ struct AnimateToExample {
this.heightSize = 50
})
} else {
animateTo({}, () => {
this.widthSize = 250
this.heightSize = 100
})
}
this.flag = !this.flag
})
Button('change rotate angle')
.margin(50)
.rotate({ x: 0, y: 0, z: 1, angle: this.rotateAngle })
.onClick(() => {
animateTo({
duration: 200, // Animation duration
curve: Curve.Ease, // Animated curve
delay: 200, // Animation delay
iterations: 1, // Number of playback times
playMode: PlayMode.Normal // Animation playback mode
duration: 1200,
curve: Curve.Friction,
delay: 500,
iterations: -1, // The value -1 indicates that the animation is played for an unlimited number of times.
playMode: PlayMode.AlternateReverse,
onFinish: () => {
console.info('play end')
}
}, () => {
this.widthSize = 200
this.heightSize = 100
this.rotateAngle = 90
})
}
this.flag = !this.flag
})
}.width('100%').margin({ top: 5 })
}
}
```
![en-us_image_0000001256978345](figures/en-us_image_0000001256978345.gif)
The figure below shows two buttons in their initial state.
![animation](figures/animation.PNG)
Clicking the first button plays the animation of resizing the button, and clicking the second button plays the animation of rotating the button clockwise by 90 degrees. The figure below shows the two buttons when the animations have finished.
![animation1](figures/animation1.PNG)
......@@ -15,7 +15,7 @@ Use the following attributes to bind gesture recognition to a component. When a
| --------------- | ---------------------------------------- | --------------------------------------- | ---------------------------------------- |
| gesture | gesture: [GestureType](#gesturetype),<br>mask?: [GestureMask](#gesturemask) | gesture: -,<br>mask: GestureMask.Normal | Gesture to bind.<br>- **gesture**: type of the gesture to bind.<br>- **mask**: event response setting. |
| priorityGesture | gesture: [GestureType](#gesturetype),<br>mask?: [GestureMask](#gesturemask) | gesture: -,<br>mask: GestureMask.Normal | Gesture to preferentially recognize.<br>- **gesture**: type of the gesture to bind.<br>- **mask**: event response setting.<br>By default, a component recognizes gestures bound through **gesture**. When **priorityGesture** is configured for its parent component, the component preferentially recognizes gestures bound through **priorityGesture**. |
| parallelGesture | gesture: [GestureType](#gesturetype),<br>mask?: [GestureMask](#gesturemask) | gesture: -,<br>mask: GestureMask.Normal | Gesture that can be triggered together with the child component gesture.<br>- **gesture**: type of the gesture to bind. <br>- **mask**: event response setting.<br>The gesture event is not a bubbling event. When **parallelGesture** is set for the parent component, gesture events that are the same for the parent component and child components can be triggered, thereby implementing a bubbling effect. |
| parallelGesture | gesture: [GestureType](#gesturetype),<br>mask?: [GestureMask](#gesturemask) | gesture: -,<br>mask: GestureMask.Normal | Gesture that can be triggered together with the child component gesture.<br>- **gesture**: type of the gesture to bind. <br>- **mask**: event response setting.<br>The gesture event is not a bubbling event. When **parallelGesture** is set for the parent component, gesture events that are the same for the parent and child components can be triggered, thereby implementing a bubbling effect. If both the single-tap gesture event and the double-tap gesture event are bound to the parent and child components, only the single-tap gesture event is responded. |
## GestureType
......@@ -40,17 +40,18 @@ Use the following attributes to bind gesture recognition to a component. When a
The component binds gesture objects of different **GestureType**s through gesture events. Each gesture object provides gesture-related information in the gesture response event. In the following example, the **TapGesture** object provides gesture-related information in the **onAction** event. For details about the event definitions of other gestures, see the corresponding gesture sections. To bind multiple gestures, use [combined gestures](ts-combined-gestures.md).
- TapGesture
| Name | Description |
| ---------------------------------------- | ---------------------------------------- |
| onAction((event?:GestureEvent) =&gt; void) | Callback invoked when a tap gesture is recognized. |
**TapGesture**
| Name | Description |
| ---------------------------------------- | ---------------------------------------- |
| onAction((event?:GestureEvent) =&gt; void) | Callback invoked when a tap gesture is recognized. |
## GestureEvent
| Name | Type | Description |
| ----------------------- | ---------------------------------------- | ---------------------------------------- |
| repeat | boolean | Whether the event is triggered repeatedly. This attribute is used for the **LongPressGesture** event. |
| offsetX | number | Offset of the gesture event on the x-axis, in vp. This attribute is used for the **PanGesture** event. A positive value means panning from left to right, and a negative value means the opposite. |
| offsetY | number | Offset of the gesture event on the y-axis, in vp. This attribute is used for the **PanGesture** event. A positive value means panning from top to bottom, and a negative value means the opposite. |
| offsetX | number | Offset of the gesture event on the x-axis, in vp. This attribute is used for the **PanGesture** event. A positive value means to pan from left to right, and a negative value means the opposite. |
| offsetY | number | Offset of the gesture event on the y-axis, in vp. This attribute is used for the **PanGesture** event. A positive value means to pan from top to bottom, and a negative value means the opposite. |
| angle | number | Rotation angle for the **RotationGesture** event;<br>angle of the swipe gesture for the **SwipeGesture** event, that is, the change in the included angle between the line segment created by the two fingers and the horizontal direction.<br>**NOTE**<br>Angle calculation method: After a swipe gesture is recognized, a line connecting the two fingers is identified as the initial line. As the fingers swipe, the line between the fingers rotates. Based on the coordinates of the initial line's and current line's end points, an arc tangent function is used to calculate the respective included angle of the points relative to the horizontal direction by using the following formula: Rotation angle = arctan2(cy2-cy1,cx2-cx1) – arctan2(y2-y1,x2-x1) The initial line is used as the coordinate system. The clockwise rotation is 0 to 180 degrees, and the counter-clockwise rotation is –180 to 0 degrees. |
| scale | number | Scale ratio. This attribute is used for the **PinchGesture** event. |
| pinchCenterX | number | X-coordinate of the center of the pinch gesture, in px relative to the upper left corner of the current component. This attribute is used for the **PinchGesture** event. |
......@@ -60,6 +61,10 @@ The component binds gesture objects of different **GestureType**s through gestur
| timestamp<sup>8+</sup> | number | Timestamp of the event. |
| target<sup>8+</sup> | [EventTarget](ts-universal-events-click.md#eventtarget8) | Display area of the element that triggers the gesture event. |
| source<sup>8+</sup> | [SourceType](#sourcetype) | Event input device. |
| pressure<sup>9+</sup> | number | Press pressure. |
| tiltX<sup>9+</sup> | number | Angle between the projection of the stylus on the device plane and the x-axis. |
| tiltY<sup>9+</sup> | number | Angle between the projection of the stylus on the device plane and the y-axis. |
| sourceTool<sup>9+</sup> | [SourceTool](#sourcetool) | Event input source. |
## SourceType
| Name | Description |
......@@ -77,6 +82,13 @@ The component binds gesture objects of different **GestureType**s through gestur
| localX | number | X-coordinate relative to the upper left corner of the current component. |
| localY | number | Y-coordinate relative to the upper left corner of the current component. |
## SourceTool
| Name | Description |
| ------- | --------------------- |
| Unknown | Unknown input source. |
| Finger | Finger input. |
| Pen | Stylus input. |
## Example
......
......@@ -22,12 +22,12 @@ Video(value: {src?: string | Resource, currentProgressRate?: number | string | P
**Parameters**
| Name | Type | Mandatory| Description |
| ------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| src | string \| [Resource](ts-types.md) | No | Path of the video source, which can be a local path or a URL.<br>The video resources can be stored in the **video** or **rawfile** folder under **resources**.<br>The path can include a **dataability://** prefix, which is used to access the video path provided by a Data ability. For details about the path, see [Data Ability Development](../../ability/fa-dataability.md).<br>**NOTE**<br>The supported video formats are MP4, MKV, WebM, and TS. |
| currentProgressRate | number \| string \| PlaybackSpeed<sup>8+</sup> | No | Video playback speed.<br>**NOTE**<br>The value of the number type can only be **0.75**, **1.0**, **1.25**, **1.75**, or **2.0**.<br>Default value: **1.0** \| PlaybackSpeed.Speed_Forward_1_00_X |
| Name | Type | Mandatory | Description |
| ------------------- | ---------------------------------------- | ---- | ---------------------------------------- |
| src | string \| [Resource](ts-types.md) | No | Path of the video source, which can be a local path or a URL.<br>The video resources can be stored in the **video** or **rawfile** folder under **resources**.<br>The path can include a **dataability://** prefix, which indicates that the path is provided by a Data ability. For details about the path, see [Data Ability Development](../../application-models/dataability-overview.md).<br>**NOTE**<br>The supported video formats are MP4, MKV, WebM, and TS. |
| currentProgressRate | number \| string \| PlaybackSpeed<sup>8+</sup> | No | Video playback speed.<br>**NOTE**<br>The value of the number type can only be **0.75**, **1.0**, **1.25**, **1.75**, or **2.0**.<br>Default value: **1.0** \| **PlaybackSpeed.Speed_Forward_1_00_X** |
| previewUri | string \| PixelMap<sup>8+</sup> \| [Resource](ts-types.md) | No | Path of the preview image. |
| controller | [VideoController](#videocontroller) | No | Controller. |
| controller | [VideoController](#videocontroller) | No | Video controller. |
## PlaybackSpeed<sup>8+</sup>
......@@ -44,7 +44,7 @@ Video(value: {src?: string | Resource, currentProgressRate?: number | string | P
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type | Description |
| --------- | ---------------------------------------- | ----------------------------------------------- |
| --------- | ---------------------------------------- | ---------------------------- |
| muted | boolean | Whether to mute the video.<br>Default value: **false** |
| autoPlay | boolean | Whether to enable auto play.<br>Default value: **false** |
| controls | boolean | Whether to display the video playback control bar.<br>Default value: **true**|
......@@ -56,7 +56,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
In addition to the [universal events](ts-universal-events-click.md), the following events are supported.
| Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| ---------------------------------------- | ---------------------------------------- |
| onStart(event:() =&gt; void) | Triggered when the video is played. |
| onPause(event:() =&gt; void) | Triggered when the video playback is paused. |
| onFinish(event:() =&gt; void) | Triggered when the video playback is finished. |
......@@ -65,7 +65,7 @@ In addition to the [universal events](ts-universal-events-click.md), the followi
| onSeeking(callback:(event?: { time: number }) =&gt; void) | Triggered to report the time (in seconds) when the progress bar is being dragged. |
| onSeeked(callback:(event?: { time: number }) =&gt; void) | Triggered to report the playback time (in seconds) when the user finishes dragging the progress bar. |
| onUpdate(callback:(event?: { time: number }) =&gt; void) | Triggered once per 250 ms when the playback progress changes. The unit of the current playback time is second. |
| onFullscreenChange(callback:(event?: { fullscreen: boolean }) =&gt; void) | Triggered when the playback mode is switched between full-screen mode and non-full-screen mode. The value **true** means that the playback is in full-screen mode, and **false** means that the playback is non-full-screen mode. |
| onFullscreenChange(callback:(event?: { fullscreen: boolean }) =&gt; void) | Triggered when the playback mode is switched between full-screen mode and non-full-screen mode. The value **true** means that the playback is in full-screen mode, and **false** means that the playback is non-full-screen mode.|
## VideoController
......@@ -76,7 +76,7 @@ Defines a **VideoController** object to control one or more videos.
### Objects to Import
```ts
controller: VideoController = new VideoController();
controller: VideoController = new VideoController()
```
......@@ -90,13 +90,13 @@ Starts playback.
pause(): void
Pauses playback.
Pauses playback. The current frame is then displayed, and playback will be resumed from this paused position.
### stop
stop(): void
Stops playback.
Stops playback. The current frame is then displayed, and playback will restart from the very beginning.
### setCurrentTime
......@@ -106,8 +106,8 @@ Sets the video playback position.
**Parameters**
| Name| Type| Mandatory| Description |
| ------ | -------- | ---- | --------------------------- |
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | -------------- |
| value | number | Yes | Video playback position, in seconds.|
### requestFullscreen
......@@ -119,7 +119,7 @@ Requests full-screen mode.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ------- |
| ----- | ------- | ---- | --------------------- |
| value | boolean | Yes | Whether the playback is in full-screen mode.<br>Default value: **false**|
### exitFullscreen
......@@ -136,9 +136,9 @@ Sets the video playback position with the specified seek mode.
**Parameters**
| Name | Type| Mandatory| Description |
| -------- | -------- | ---- | ------------------ |
| value | number | Yes | Video playback position.|
| Name | Type | Mandatory | Description |
| -------- | -------- | ---- | -------------- |
| value | number | Yes | Video playback position, in seconds.|
| seekMode | SeekMode | Yes | Seek mode. |
## SeekMode<sup>8+</sup>
......@@ -159,77 +159,89 @@ Sets the video playback position with the specified seek mode.
@Entry
@Component
struct VideoCreateComponent {
@State srcs: Resource = $rawfile('video1.mp4');
@State previewUris: Resource = $r('app.media.img');
@State currentProgressRates: number = 1;
@State autoPlays: boolean = false;
@State controlsss: boolean = true;
controller: VideoController = new VideoController();
@State videoSrc: Resource = $rawfile('video1.mp4')
@State previewUri: Resource = $r('app.media.poster1')
@State curRate: PlaybackSpeed = PlaybackSpeed.Speed_Forward_1_00_X
@State isAutoPlay: boolean = false
@State showControls: boolean = true
controller: VideoController = new VideoController()
build() {
Column() {
Video({
src: this.srcs,
previewUri: this.previewUris,
currentProgressRate: this.currentProgressRates,
src: this.videoSrc,
previewUri: this.previewUri,
currentProgressRate: this.curRate,
controller: this.controller
}).width(700).height(500)
.autoPlay(this.autoPlays)
.controls(this.controlsss)
}).width(800).height(600)
.autoPlay(this.isAutoPlay)
.controls(this.showControls)
.onStart(() => {
console.error('onStart');
console.info('onStart')
})
.onPause(() => {
console.error('onPause');
console.info('onPause')
})
.onFinish(() => {
console.error('onFinish');
console.info('onFinish')
})
.onError(() => {
console.error('onFinish');
console.info('onFinish')
})
.onPrepared((e) => {
console.error('onPrepared is ' + e.duration);
console.info('onPrepared is ' + e.duration)
})
.onSeeking((e) => {
console.error('onSeeking is ' + e.time);
console.info('onSeeking is ' + e.time)
})
.onSeeked((e) => {
console.error('onSeekedis ' + e.time);
console.info('onSeeked is ' + e.time)
})
.onUpdate((e) => {
console.error('onUpdateis ' + e.time);
console.info('onUpdate is ' + e.time)
})
Row() {
Button("src").onClick(() => {
this.srcs = $rawfile('video2.mp4');
});
Button("previewUri").onClick(() => {
this.previewUris = $r('app.media.img1');
});
Button("controlsss").onClick(() => {
this.controlsss = !this.controlsss;
});
Button('src').onClick(() => {
this.videoSrc = $rawfile('video2.mp4') // Switch the video source.
}).margin(5)
Button('previewUri').onClick(() => {
this.previewUri = $r('app.media.poster2') // Switch the preview image.
}).margin(5)
Button('controls').onClick(() => {
this.showControls = !this.showControls // Specify whether to show the control bar.
}).margin(5)
}
Row() {
Button("start").onClick(() => {
this.controller.start();
});
Button("pause").onClick(() => {
this.controller.pause();
});
Button("stop").onClick(() => {
this.controller.stop();
});
Button('start').onClick(() => {
this.controller.start() // Start playback.
}).margin(5)
Button('pause').onClick(() => {
this.controller.pause() // Pause playback.
}).margin(5)
Button('stop').onClick(() => {
this.controller.stop() // Stop playback.
}).margin(5)
Button('setTime').onClick(() => {
this.controller.setCurrentTime(10, SeekMode.Accurate) // Seek to the 10s position of the video.
}).margin(5)
}
Row() {
Button("setCurrentTime").onClick(() => {
this.controller.setCurrentTime(9, SeekMode.Accurate);
});
Button('rate 0.75').onClick(() => {
this.curRate = PlaybackSpeed.Speed_Forward_0_75_X // Play the video at the 0.75x speed.
}).margin(5)
Button('rate 1').onClick(() => {
this.curRate = PlaybackSpeed.Speed_Forward_1_00_X // Play the video at the 1x speed.
}).margin(5)
Button('rate 2').onClick(() => {
this.curRate = PlaybackSpeed.Speed_Forward_2_00_X // Play the video at the 2x speed.
}).margin(5)
}
}
}
}
```
<!--no_check-->
\ No newline at end of file
......@@ -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: () => {
......@@ -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: () => {
......@@ -96,4 +118,4 @@ struct AlertDialogExample {
}
```
![en-us_image_0000001256978387](figures/en-us_image_0000001256978387.gif)
![en-us_image_0000001174582844](figures/en-us_image_0000001174582844.gif)
......@@ -6,44 +6,45 @@ A date picker dialog box is a dialog box that allows users to select a date from
>
> 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
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(() => {
Column() {
Button("DatePickerDialog")
.margin(20)
.onClick(() => {
DatePickerDialog.show({
start: new Date("2000-1-1"),
end: new Date("2005-1-1"),
end: new Date("2100-12-31"),
selected: this.selectedDate,
lunar: this.isLunar,
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))
},
......@@ -55,28 +56,15 @@ struct DatePickerDialogExample01 {
}
})
})
}
}
}
```
### 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(() => {
Button("Lunar DatePickerDialog")
.margin(20)
.onClick(() => {
DatePickerDialog.show({
start: new Date("2000-1-1"),
end: new Date("2005-1-1"),
end: new Date("2100-12-31"),
selected: this.selectedDate,
lunar: this.isLunar,
lunar: true,
onAccept: (value: DatePickerResult) => {
this.selectedDate.setFullYear(value.year, value.month, value.day)
console.info("DatePickerDialog:onAccept()" + JSON.stringify(value))
......@@ -89,7 +77,7 @@ struct DatePickerDialogExample02 {
}
})
})
}
}.width('100%')
}
}
```
......@@ -8,9 +8,10 @@ The menu bound to a component through [bindContextMenu](./ts-universal-attribute
## ContextMenu.close
|Name|Description|
|----|---|
| close(): void | Closes the menu bound to this component through [bindContextMenu](./ts-universal-attributes-menu.md#attributes) on a page. |
| close(): void | Closes the menu bound to this component through [bindContextMenu](./ts-universal-attributes-menu.md#attributes) on a page.|
## Example
......@@ -22,25 +23,36 @@ The menu bound to a component through [bindContextMenu](./ts-universal-attribute
struct Index {
@Builder MenuBuilder() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('close')
.fontSize(30)
.fontWeight(FontWeight.Bold)
.onClick(() => {
ContextMenu.close();
})
}.height(400)
.backgroundColor(Color.Pink)
Button('Test ContextMenu1')
Divider().strokeWidth(2).margin(5)
Button('Test ContextMenu2')
Divider().strokeWidth(2).margin(5)
Button('Test ContextMenu3')
}
.width(200)
.height(160)
}
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.Start }) {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Column() {
Text("Text")
}.bindContextMenu(this.MenuBuilder, ResponseType.LongPress)
Text("Test ContextMenu")
.fontSize(20)
.width('100%')
.height(500)
.backgroundColor(0xAFEEEE)
.textAlign(TextAlign.Center)
}
.bindContextMenu(this.MenuBuilder, ResponseType.LongPress)
.onDragStart(()=>{
// Close the menu when the component is dragged.
ContextMenu.close()
})
}
.width('100%')
.height('100%')
}
}
```
![contextmenu_close.gif](figures/contextmenu_close.gif)
......@@ -6,28 +6,31 @@ A text picker dialog box is a dialog box that allows users to select text from t
>
> 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
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,19 +39,21 @@ 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(() => {
Column() {
Button("TextPickerDialog")
.margin(20)
.onClick(() => {
TextPickerDialog.show({
range: this.fruits,
selected: this.select,
onAccept: (value: TextPickerResult) => {
console.info("TextPickerDialog:onAccept()" + JSON.stringify(value))
// 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()")
......@@ -58,7 +63,7 @@ struct TextPickerDialogExample {
}
})
})
}
}.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))
}
})
})
......
......@@ -11,7 +11,7 @@ The motion path animation is used to animate a component along a custom path.
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| motionPath | {<br>path: string,<br>from?: number,<br>to?: number,<br>rotatable?: boolean<br>}<br>**NOTE**<br>In a path, **start** and **end** can be used to replace the start point and end point. Example:<br>'Mstart.x start.y L50 50 Lend.x end.y Z'| {<br>"",<br>0.0,<br>1.0,<br>false<br>} | Motion path of the component. The input parameters are described as follows:<br>- **path**: motion path of the translation animation. The value is an SVG path string.<br>- **from**: start point of the motion path. The default value is **0.0**.<br>- **to**: end point of the motion path. The default value is **1.0**.<br>- **rotatable**: whether to rotate along the path.|
| motionPath | {<br>path: string,<br>from?: number,<br>to?: number,<br>rotatable?: boolean<br>}<br>**NOTE**<br>In a path, **start** and **end** can be used to replace the start point and end point. Example:<br>'Mstart.x start.y L50 50 Lend.x end.y Z'<br>For more information, see [Path Drawing](../../ui/ui-js-components-svg-path.md).| {<br>'',<br>0.0,<br>1.0,<br>false<br>} | Motion path of the component.<br>- **path**: motion path of the translation animation. The value is an SVG path string.<br>- **from**: start point of the motion path. The default value is **0.0**.<br>- **to**: end point of the motion path. The default value is **1.0**.<br>- **rotatable**: whether to rotate along the path. |
## Example
......@@ -28,11 +28,11 @@ struct MotionPathExample {
Button('click me')
// Execute the animation: Move from the start point to (300,200), then to (300,500), and finally to the end point.
.motionPath({ path: 'Mstart.x start.y L300 200 L300 500 Lend.x end.y', from: 0.0, to: 1.0, rotatable: true })
.onClick((event: ClickEvent) => {
.onClick(() => {
animateTo({ duration: 4000, curve: Curve.Linear }, () => {
this.toggle = !this.toggle;
this.toggle =! this.toggle // Use this.toggle to change the position of the component.
})
})
}).backgroundColor(0x317aff)
}.width('100%').height('100%').alignItems(this.toggle ? HorizontalAlign.Start : HorizontalAlign.Center)
}
}
......
......@@ -24,24 +24,24 @@ OffscreenCanvasRenderingContext2D(width: number, height: number, setting: Render
## Attributes
| Name | Type | Description |
| ----------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.<br>- When the type is **string**, this attribute indicates the color of the filling area.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. |
| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| [fillStyle](#fillstyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Style to fill an area.<br>- When the type is **string**, this attribute indicates the color of the filling area.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.|
| [lineWidth](#linewidth) | number | Line width. |
| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.<br>- When the type is **\<color>**, this parameter indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API. |
| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:<br>- **butt**: The endpoints of the line are squared off.<br>- **round**: The endpoints of the line are rounded.<br>- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.<br>- Default value: **'butt'** |
| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:<br>- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.<br>- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.<br>- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.<br>- Default value: **'miter'** |
| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.<br>- Default value: **10** |
| [font](#font) | string | Font style.<br>Syntax: ctx.font='font-size font-family'<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>(Optional) **font-family**: font family.<br>Syntax: ctx.font='font-style font-weight font-size font-family'<br>- (Optional) **font-style**: font style. Available values are **normal** and **italic**.<br>- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.<br>Default value: **'normal normal 14px sans-serif'** |
| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:<br>- **left**: The text is left-aligned.<br>- **right**: The text is right-aligned.<br>- **center**: The text is center-aligned.<br>- **start**: The text is aligned with the start bound.<br>- **end**: The text is aligned with the end bound.<br>**NOTE**<br>In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.<br>- Default value: **'left'** |
| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:<br>- **alphabetic**: The text baseline is the normal alphabetic baseline.<br>- **top**: The text baseline is on the top of the text bounding box.<br>- **hanging**: The text baseline is a hanging baseline over the text.<br>- **middle**: The text baseline is in the middle of the text bounding box.<br>**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br>- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.<br>- Default value: **'alphabetic'** |
| [strokeStyle](#strokestyle) | string \| [CanvasGradient](ts-components-canvas-canvasgradient.md) \| [CanvasPattern](#canvaspattern) | Stroke style.<br>- When the type is **\<color>**, this parameter indicates the stroke color.<br>- When the type is **CanvasGradient**, this attribute indicates a gradient object, which is created using the **[createLinearGradient](#createlineargradient)** API.<br>- When the type is **CanvasPattern**, this attribute indicates a pattern, which is created using the **[createPattern](#createpattern)** API.|
| [lineCap](#linecap) | CanvasLineCap | Style of the line endpoints. The options are as follows:<br>- **butt**: The endpoints of the line are squared off.<br>- **round**: The endpoints of the line are rounded.<br>- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.<br>- Default value: **'butt'**|
| [lineJoin](#linejoin) | CanvasLineJoin | Style of the shape used to join line segments. The options are as follows:<br>- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.<br>- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.<br>- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.<br>- Default value: **'miter'**|
| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.<br>- Default value: **10**|
| [font](#font) | string | Font style.<br>Syntax: ctx.font='font-size font-family'<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>(Optional) **font-family**: font family.<br>Syntax: ctx.font='font-style font-weight font-size font-family'<br>- (Optional) **font-style**: font style. Available values are **normal** and **italic**.<br>- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.<br>- (Optional) **font-size**: font size and row height. The unit can only be pixels.<br>- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.<br>Default value: **'normal normal 14px sans-serif'**|
| [textAlign](#textalign) | CanvasTextAlign | Text alignment mode. Available values are as follows:<br>- **left**: The text is left-aligned.<br>- **right**: The text is right-aligned.<br>- **center**: The text is center-aligned.<br>- **start**: The text is aligned with the start bound.<br>- **end**: The text is aligned with the end bound.<br>**NOTE**<br>In the **ltr** layout mode, the value **'start'** equals **'left'**. In the **rtl** layout mode, the value **'start'** equals **'right'**.<br>- Default value: **'left'**|
| [textBaseline](#textbaseline) | CanvasTextBaseline | Horizontal alignment mode of text. Available values are as follows:<br>- **alphabetic**: The text baseline is the normal alphabetic baseline.<br>- **top**: The text baseline is on the top of the text bounding box.<br>- **hanging**: The text baseline is a hanging baseline over the text.<br>- **middle**: The text baseline is in the middle of the text bounding box.<br>**'ideographic'**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excess character.<br>- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.<br>- Default value: **'alphabetic'**|
| [globalAlpha](#globalalpha) | number | Opacity.<br>**0.0**: completely transparent.<br>**1.0**: completely opaque. |
| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.<br>- Default value: **0.0** |
| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.<br>- Default value: **'source-over'** |
| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.<br>- Default value: **0.0** |
| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.<br>- Default value: **0.0**|
| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **'source-over'**, **'source-atop'**, **'source-in'**, **'source-out'**, **'destination-over'**, **'destination-atop'**, **'destination-in'**, **'destination-out'**, **'lighter'**, **'copy'**, and **'xor'**.<br>- Default value: **'source-over'**|
| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.<br>- Default value: **0.0**|
| [shadowColor](#shadowcolor) | string | Shadow color. |
| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. |
| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. |
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.<br>- Default value: **true** |
| [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.<br>- Default value: **true**|
> **NOTE**
>
......@@ -78,7 +78,7 @@ struct FillStyleExample {
}
```
![en-us_image_0000001211898510](figures/en-us_image_0000001211898510.png)
![en-us_image_0000001193872516](figures/en-us_image_0000001193872516.png)
### lineWidth
......@@ -111,7 +111,7 @@ struct LineWidthExample {
}
```
![en-us_image_0000001257058439](figures/en-us_image_0000001257058439.png)
![en-us_image_0000001238832403](figures/en-us_image_0000001238832403.png)
### strokeStyle
......@@ -145,7 +145,7 @@ struct StrokeStyleExample {
}
```
![en-us_image_0000001257058429](figures/en-us_image_0000001257058429.png)
![en-us_image_0000001238712437](figures/en-us_image_0000001238712437.png)
### lineCap
......@@ -182,7 +182,7 @@ struct LineCapExample {
}
```
![en-us_image_0000001256858427](figures/en-us_image_0000001256858427.png)
![en-us_image_0000001194192454](figures/en-us_image_0000001194192454.PNG)
### lineJoin
......@@ -220,7 +220,7 @@ struct LineJoinExample {
}
```
![en-us_image_0000001256858429](figures/en-us_image_0000001256858429.png)
![en-us_image_0000001194352450](figures/en-us_image_0000001194352450.png)
### miterLimit
......@@ -258,7 +258,7 @@ struct MiterLimit {
}
```
![en-us_image_0000001212218472](figures/en-us_image_0000001212218472.png)
![en-us_image_0000001238952397](figures/en-us_image_0000001238952397.png)
### font
......@@ -291,7 +291,7 @@ struct Fonts {
}
```
![en-us_image_0000001211898508](figures/en-us_image_0000001211898508.png)
![en-us_image_0000001194032476](figures/en-us_image_0000001194032476.png)
### textAlign
......@@ -339,7 +339,7 @@ struct CanvasExample {
}
```
![en-us_image_0000001257138377](figures/en-us_image_0000001257138377.png)
![en-us_image_0000001239032423](figures/en-us_image_0000001239032423.png)
### textBaseline
......@@ -387,7 +387,7 @@ struct TextBaseline {
}
```
![en-us_image_0000001256978375](figures/en-us_image_0000001256978375.png)
![en-us_image_0000001193872518](figures/en-us_image_0000001193872518.png)
### globalAlpha
......@@ -423,7 +423,7 @@ struct GlobalAlpha {
}
```
![en-us_image_0000001211898506](figures/en-us_image_0000001211898506.png)
![en-us_image_0000001238832405](figures/en-us_image_0000001238832405.png)
### lineDashOffset
......@@ -458,7 +458,7 @@ struct LineDashOffset {
}
```
![en-us_image_0000001212058506](figures/en-us_image_0000001212058506.png)
![en-us_image_0000001238712439](figures/en-us_image_0000001238712439.png)
### globalCompositeOperation
......@@ -513,7 +513,7 @@ struct GlobalCompositeOperation {
}
```
![en-us_image_0000001212218474](figures/en-us_image_0000001212218474.png)
![en-us_image_0000001194192456](figures/en-us_image_0000001194192456.png)
### shadowBlur
......@@ -548,7 +548,7 @@ struct ShadowBlur {
}
```
![en-us_image_0000001211898514](figures/en-us_image_0000001211898514.png)
![en-us_image_0000001194352452](figures/en-us_image_0000001194352452.png)
### shadowColor
......@@ -583,7 +583,7 @@ struct ShadowColor {
}
```
![en-us_image_0000001212058502](figures/en-us_image_0000001212058502.png)
![en-us_image_0000001238952399](figures/en-us_image_0000001238952399.png)
### shadowOffsetX
......@@ -619,7 +619,7 @@ struct ShadowOffsetX {
}
```
![en-us_image_0000001257138379](figures/en-us_image_0000001257138379.png)
![en-us_image_0000001194032478](figures/en-us_image_0000001194032478.png)
### shadowOffsetY
......@@ -655,7 +655,7 @@ struct ShadowOffsetY {
}
```
![en-us_image_0000001257058427](figures/en-us_image_0000001257058427.png)
![en-us_image_0000001239032425](figures/en-us_image_0000001239032425.png)
### imageSmoothingEnabled
......@@ -689,7 +689,7 @@ struct ImageSmoothingEnabled {
}
```
![en-us_image_0000001257138385](figures/en-us_image_0000001257138385.png)
![en-us_image_0000001193872520](figures/en-us_image_0000001193872520.png)
## Methods
......@@ -739,7 +739,7 @@ Fills a rectangle on the canvas.
}
```
![en-us_image_0000001257138375](figures/en-us_image_0000001257138375.png)
![en-us_image_0000001194192436](figures/en-us_image_0000001194192436.png)
### strokeRect
......@@ -748,7 +748,7 @@ strokeRect(x: number, y: number, w: number, h: number): void
Draws an outlined rectangle on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ------------ |
......@@ -757,7 +757,7 @@ Draws an outlined rectangle on the canvas.
| width | number | Yes | 0 | Width of the rectangle. |
| height | number | Yes | 0 | Height of the rectangle. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -786,7 +786,7 @@ Draws an outlined rectangle on the canvas.
}
```
![en-us_image_0000001212378436](figures/en-us_image_0000001212378436.png)
![en-us_image_0000001194352436](figures/en-us_image_0000001194352436.png)
### clearRect
......@@ -795,7 +795,7 @@ clearRect(x: number, y: number, w: number, h: number): void
Clears the content in a rectangle on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ------------- |
......@@ -804,7 +804,7 @@ Clears the content in a rectangle on the canvas.
| width | number | Yes | 0 | Width of the rectangle. |
| height | number | Yes | 0 | Height of the rectangle. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -835,7 +835,7 @@ Clears the content in a rectangle on the canvas.
}
```
![en-us_image_0000001212058500](figures/en-us_image_0000001212058500.png)
![en-us_image_0000001238952377](figures/en-us_image_0000001238952377.png)
### fillText
......@@ -853,7 +853,7 @@ Draws filled text on the canvas.
| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.|
| maxWidth | number | No | - | Maximum width allowed for the text. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -883,7 +883,7 @@ Draws filled text on the canvas.
}
```
![en-us_image_0000001257058437](figures/en-us_image_0000001257058437.png)
![en-us_image_0000001194032458](figures/en-us_image_0000001194032458.png)
### strokeText
......@@ -901,7 +901,7 @@ Draws a text stroke on the canvas.
| y | number | Yes | 0 | Y-coordinate of the lower left corner of the text.|
| maxWidth | number | No | - | Maximum width of the text to be drawn. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -931,7 +931,7 @@ Draws a text stroke on the canvas.
}
```
![en-us_image_0000001212218466](figures/en-us_image_0000001212218466.png)
![en-us_image_0000001238952401](figures/en-us_image_0000001238952401.png)
### measureText
......@@ -940,13 +940,13 @@ measureText(text: string): TextMetrics
Returns a **TextMetrics** object used to obtain the width of specified text.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ---------- |
| text | string | Yes | "" | Text to be measured.|
**Return value**
**Return value**
| Type | Description |
| ----------- | ------- |
......@@ -970,7 +970,7 @@ Returns a **TextMetrics** object used to obtain the width of specified text.
| hangingBaseline | number | Distance from the horizontal line specified by the **CanvasRenderingContext2D.textBaseline** attribute to the hanging baseline of the line box. The current value is **0**.|
| ideographicBaseline | number | Distance from the horizontal line indicated by the **CanvasRenderingContext2D.textBaseline** attribute to the ideographic baseline of the line box. The current value is **0**.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1001,7 +1001,7 @@ Returns a **TextMetrics** object used to obtain the width of specified text.
}
```
![en-us_image_0000001256858431](figures/en-us_image_0000001256858431.png)
![en-us_image_0000001194032480](figures/en-us_image_0000001194032480.png)
### stroke
......@@ -1010,13 +1010,13 @@ stroke(path?: Path2D): void
Strokes a path.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ---------------------------------------- | ---- | ---- | ------------ |
| path | [Path2D](ts-components-canvas-path2d.md) | No | null | A **Path2D** path to draw.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1050,7 +1050,7 @@ Strokes a path.
}
```
![en-us_image_0000001257138373](figures/en-us_image_0000001257138373.png)
![en-us_image_0000001238832389](figures/en-us_image_0000001238832389.png)
### beginPath
......@@ -1059,7 +1059,7 @@ beginPath(): void
Creates a drawing path.
**Example**
**Example**
```ts
// xxx.ets
......@@ -1093,7 +1093,7 @@ Creates a drawing path.
}
```
![en-us_image_0000001212378440](figures/en-us_image_0000001212378440.png)
![en-us_image_0000001193872522](figures/en-us_image_0000001193872522.png)
### moveTo
......@@ -1102,14 +1102,14 @@ moveTo(x: number, y: number): void
Moves a drawing path to a target position on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------- |
| x | number | Yes | 0 | X-coordinate of the target position.|
| y | number | Yes | 0 | Y-coordinate of the target position.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1141,7 +1141,7 @@ Moves a drawing path to a target position on the canvas.
}
```
![en-us_image_0000001212058498](figures/en-us_image_0000001212058498.png)
![en-us_image_0000001238832409](figures/en-us_image_0000001238832409.png)
### lineTo
......@@ -1150,14 +1150,14 @@ lineTo(x: number, y: number): void
Connects the current point to a target position using a straight line.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------- |
| x | number | Yes | 0 | X-coordinate of the target position.|
| y | number | Yes | 0 | Y-coordinate of the target position.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1189,7 +1189,7 @@ Connects the current point to a target position using a straight line.
}
```
![en-us_image_0000001257058435](figures/en-us_image_0000001257058435.png)
![en-us_image_0000001238712443](figures/en-us_image_0000001238712443.png)
### closePath
......@@ -1198,7 +1198,7 @@ closePath(): void
Draws a closed path.
**Example**
**Example**
```ts
// xxx.ets
......@@ -1232,7 +1232,7 @@ Draws a closed path.
}
```
![en-us_image_0000001257058431](figures/en-us_image_0000001257058431.png)
![en-us_image_0000001194192460](figures/en-us_image_0000001194192460.png)
### createPattern
......@@ -1254,7 +1254,7 @@ Creates a pattern for image filling based on a specified source image and repeti
| ------------------------------- | ----------------------- |
| [CanvasPattern](#canvaspattern) | Created pattern for image filling based on a specified source image and repetition mode.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1286,7 +1286,7 @@ Creates a pattern for image filling based on a specified source image and repeti
}
```
![en-us_image_0000001257138387](figures/en-us_image_0000001257138387.png)
![en-us_image_0000001194352456](figures/en-us_image_0000001194352456.png)
### bezierCurveTo
......@@ -1295,7 +1295,7 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number,
Draws a cubic bezier curve on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | -------------- |
......@@ -1306,7 +1306,7 @@ Draws a cubic bezier curve on the canvas.
| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve. |
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -1338,7 +1338,7 @@ Draws a cubic bezier curve on the canvas.
}
```
![en-us_image_0000001212378442](figures/en-us_image_0000001212378442.png)
![en-us_image_0000001238952403](figures/en-us_image_0000001238952403.png)
### quadraticCurveTo
......@@ -1347,7 +1347,7 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void
Draws a quadratic curve on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------- |
......@@ -1356,7 +1356,7 @@ Draws a quadratic curve on the canvas.
| x | number | Yes | 0 | X-coordinate of the end point on the bezier curve.|
| y | number | Yes | 0 | Y-coordinate of the end point on the bezier curve.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1388,7 +1388,7 @@ Draws a quadratic curve on the canvas.
}
```
![en-us_image_0000001256978383](figures/en-us_image_0000001256978383.png)
![en-us_image_0000001194032482](figures/en-us_image_0000001194032482.png)
### arc
......@@ -1397,7 +1397,7 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number,
Draws an arc on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------------- | ------- | ---- | ----- | ---------- |
......@@ -1408,7 +1408,7 @@ Draws an arc on the canvas.
| endAngle | number | Yes | 0 | End radian of the arc. |
| counterclockwise | boolean | No | false | Whether to draw the arc counterclockwise.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1439,7 +1439,7 @@ Draws an arc on the canvas.
}
```
![en-us_image_0000001212378430](figures/en-us_image_0000001212378430.png)
![en-us_image_0000001239032429](figures/en-us_image_0000001239032429.png)
### arcTo
......@@ -1448,7 +1448,7 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void
Draws an arc based on the radius and points on the arc.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | --------------- |
......@@ -1458,7 +1458,7 @@ Draws an arc based on the radius and points on the arc.
| y2 | number | Yes | 0 | Y-coordinate of the second point on the arc.|
| radius | number | Yes | 0 | Radius of the arc. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -1489,7 +1489,7 @@ Draws an arc based on the radius and points on the arc.
}
```
![en-us_image_0000001257138383](figures/en-us_image_0000001257138383.png)
![en-us_image_0000001193872524](figures/en-us_image_0000001193872524.png)
### ellipse
......@@ -1498,7 +1498,7 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number
Draws an ellipse in the specified rectangular region on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------------- | ------- | ---- | ----- | ----------------- |
......@@ -1511,7 +1511,7 @@ Draws an ellipse in the specified rectangular region on the canvas.
| endAngle | number | Yes | 0 | Angle of the end point for drawing the ellipse. The unit is radian.|
| counterclockwise | boolean | No | false | Whether to draw the ellipse counterclockwise.<br>**true**: Draw the ellipse counterclockwise.<br>**false**: Draw the ellipse clockwise. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -1541,7 +1541,7 @@ Draws an ellipse in the specified rectangular region on the canvas.
}
```
![en-us_image_0000001256858423](figures/en-us_image_0000001256858423.png)
![en-us_image_0000001194192440](figures/en-us_image_0000001194192440.png)
### rect
......@@ -1550,7 +1550,7 @@ rect(x: number, y: number, w: number, h: number): void
Creates a rectangle on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ------------- |
......@@ -1559,7 +1559,7 @@ Creates a rectangle on the canvas.
| w | number | Yes | 0 | Width of the rectangle. |
| h | number | Yes | 0 | Height of the rectangle. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -1589,7 +1589,7 @@ Creates a rectangle on the canvas.
}
```
![en-us_image_0000001257138381](figures/en-us_image_0000001257138381.png)
![en-us_image_0000001238712445](figures/en-us_image_0000001238712445.png)
### fill
......@@ -1632,7 +1632,7 @@ Fills the area inside a closed path on the canvas.
}
```
![en-us_image_0000001256858421](figures/en-us_image_0000001256858421.png)
![en-us_image_0000001194192462](figures/en-us_image_0000001194192462.png)
fill(path: Path2D, fillRule?: CanvasFillRule): void
......@@ -1674,7 +1674,7 @@ struct Fill {
region.lineTo(270, 90)
region.closePath()
// Fill path
this.offContext.fillStyle = 'green'
this.offContext.fillStyle = '#00ff00'
this.offContext.fill(region, "evenodd")
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
......@@ -1702,7 +1702,7 @@ Sets the current path to a clipping path.
| -------- | -------------- | ---- | --------- | ---------------------------------------- |
| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to clip.<br>The options are **"nonzero"** and **"evenodd"**.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1735,7 +1735,7 @@ Sets the current path to a clipping path.
}
```
![en-us_image_0000001257058441](figures/en-us_image_0000001257058441.png)
![en-us_image_0000001194032462](figures/en-us_image_0000001194032462.png)
clip(path:Path2D, fillRule?: CanvasFillRule): void
......@@ -1749,7 +1749,7 @@ Sets a closed path to a clipping path.
| path | Path2D | Yes | | A **Path2D** path to clip.|
| fillRule | CanvasFillRule | No | "nonzero" | Rule by which to determine whether a point is inside or outside the area to clip.<br>The options are **"nonzero"** and **"evenodd"**.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1827,13 +1827,13 @@ rotate(angle: number): void
Rotates a canvas clockwise around its coordinate axes.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ---------------------------------------- |
| angle | number | Yes | 0 | Clockwise rotation angle. You can use **Math.PI / 180** to convert the angle to a radian.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1851,7 +1851,7 @@ Rotates a canvas clockwise around its coordinate axes.
.height('100%')
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.rotate(45 * Math.PI / 180) // Rotate the rectangle 45 degrees
this.offContext.rotate(45 * Math.PI / 180)
this.offContext.fillRect(70, 20, 50, 50)
var image = this.offContext.transferToImageBitmap()
this.context.transferFromImageBitmap(image)
......@@ -1863,7 +1863,7 @@ Rotates a canvas clockwise around its coordinate axes.
}
```
![en-us_image_0000001212218478](figures/en-us_image_0000001212218478.png)
![en-us_image_0000001238952405](figures/en-us_image_0000001238952405.png)
### scale
......@@ -1872,14 +1872,14 @@ scale(x: number, y: number): void
Scales the canvas based on scale factors.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------- |
| x | number | Yes | 0 | Horizontal scale factor.|
| y | number | Yes | 0 | Vertical scale factor.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1911,7 +1911,7 @@ Scales the canvas based on scale factors.
}
```
![en-us_image_0000001211898516](figures/en-us_image_0000001211898516.png)
![en-us_image_0000001193872498](figures/en-us_image_0000001193872498.png)
### transform
......@@ -1939,7 +1939,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para
| e | number | Yes | 0 | X-axis translation.|
| f | number | Yes | 0 | Y-axis translation.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -1975,7 +1975,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para
}
```
![en-us_image_0000001212378438](figures/en-us_image_0000001212378438.png)
![en-us_image_0000001239032431](figures/en-us_image_0000001239032431.png)
### setTransform
......@@ -1995,7 +1995,7 @@ Resets the existing transformation matrix and creates a new transformation matri
| e | number | Yes | 0 | X-axis translation.|
| f | number | Yes | 0 | Y-axis translation.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -2037,14 +2037,14 @@ translate(x: number, y: number): void
Moves the origin of the coordinate system.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | -------- |
| x | number | Yes | 0 | X-axis translation.|
| y | number | Yes | 0 | Y-axis translation.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -2088,7 +2088,7 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh:
Draws an image on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ---------------------------------------- | ---- | ---- | ----------------------------- |
......@@ -2102,8 +2102,7 @@ Draws an image on the canvas.
| dw | number | No | 0 | Width of the drawing area. |
| dh | number | No | 0 | Height of the drawing area. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -2132,7 +2131,7 @@ Draws an image on the canvas.
}
```
![en-us_image_0000001256978377](figures/en-us_image_0000001256978377.png)
![en-us_image_0000001238712447](figures/en-us_image_0000001238712447.png)
### createImageData
......@@ -2141,7 +2140,7 @@ createImageData(sw: number, sh: number): ImageData
Creates an **[ImageData](ts-components-canvas-imagedata.md)** object with the specified dimensions.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ------------- |
......@@ -2153,7 +2152,7 @@ createImageData(imageData: ImageData): ImageData
Creates an **[ImageData](ts-components-canvas-imagedata.md)** object by copying an existing **ImageData** object.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | ---------------------------------------- | ---- | ---- | ---------------- |
......@@ -2171,7 +2170,7 @@ getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap
Obtains the **[PixelMap](../apis/js-apis-image.md#pixelmap7)** object created with the pixels within the specified area on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------------- |
......@@ -2193,7 +2192,7 @@ getImageData(sx: number, sy: number, sw: number, sh: number): ImageData
Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created with the pixels within the specified area on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------------- |
......@@ -2208,7 +2207,6 @@ Obtains the **[ImageData](ts-components-canvas-imagedata.md)** object created wi
| ---------------------------------------- | ------------- |
| [ImageData](ts-components-canvas-imagedata.md) | New **ImageData** object.|
**Example**
```ts
......@@ -2252,7 +2250,7 @@ putImageData(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY:
Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectangular area on the canvas.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----------- | ------ | ---- | ------------ | ----------------------------- |
......@@ -2264,7 +2262,7 @@ Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectang
| dirtyWidth | number | No | Width of the **ImageData** object| Width of the rectangular area to crop the source image. |
| dirtyHeight | number | No | Height of the **ImageData** object| Height of the rectangular area to crop the source image. |
**Example**
**Example**
```ts
// xxx.ets
......@@ -2299,7 +2297,7 @@ Puts an **[ImageData](ts-components-canvas-imagedata.md)** object onto a rectang
}
```
![en-us_image_0000001212058496](figures/en-us_image_0000001212058496.png)
![en-us_image_0000001194192464](figures/en-us_image_0000001194192464.png)
### setLineDash
......@@ -2455,7 +2453,7 @@ imageSmoothingQuality(quality: imageSmoothingQuality)
Sets the quality of image smoothing. This API is a void API.
**Parameters**
**Parameters**
| Name | Type | Description |
| ------- | --------------------- | ---------------------------------------- |
......@@ -2474,8 +2472,7 @@ Creates an **ImageBitmap** object on the most recently rendered image of the **O
| ---------------------------------------- | --------------- |
| [ImageBitmap](ts-components-canvas-imagebitmap.md) | Pixel data rendered on the **OffscreenCanvas**.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -2518,7 +2515,7 @@ restore(): void
Restores the saved drawing context.
**Example**
**Example**
```ts
// xxx.ets
......@@ -2537,7 +2534,7 @@ struct CanvasExample {
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.save() // save the default state
this.offContext.fillStyle = "green"
this.offContext.fillStyle = "#00ff00"
this.offContext.fillRect(20, 20, 100, 100)
this.offContext.restore() // restore to the default state
this.offContext.fillRect(150, 75, 100, 100)
......@@ -2559,7 +2556,7 @@ save(): void
Saves the current drawing context.
**Example**
**Example**
```ts
// xxx.ets
......@@ -2578,7 +2575,7 @@ struct CanvasExample {
.backgroundColor('#ffff00')
.onReady(() =>{
this.offContext.save() // save the default state
this.offContext.fillStyle = "green"
this.offContext.fillStyle = "#00ff00"
this.offContext.fillRect(20, 20, 100, 100)
this.offContext.restore() // restore to the default state
this.offContext.fillRect(150, 75, 100, 100)
......@@ -2600,7 +2597,7 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): void
Creates a linear gradient.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | -------- |
......@@ -2609,7 +2606,7 @@ Creates a linear gradient.
| x1 | number | Yes | 0 | X-coordinate of the end point.|
| y1 | number | Yes | 0 | Y-coordinate of the end point.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -2628,9 +2625,9 @@ Creates a linear gradient.
.backgroundColor('#ffff00')
.onReady(() =>{
var grad = this.offContext.createLinearGradient(50,0, 300,100)
grad.addColorStop(0.0, 'red')
grad.addColorStop(0.5, 'white')
grad.addColorStop(1.0, 'green')
grad.addColorStop(0.0, '#ff0000')
grad.addColorStop(0.5, '#ffffff')
grad.addColorStop(1.0, '#00ff00')
this.offContext.fillStyle = grad
this.offContext.fillRect(0, 0, 500, 500)
var image = this.offContext.transferToImageBitmap()
......@@ -2643,7 +2640,7 @@ Creates a linear gradient.
}
```
![en-us_image_0000001212378434](figures/en-us_image_0000001212378434.png)
![en-us_image_0000001194352460](figures/en-us_image_0000001194352460.png)
### createRadialGradient
......@@ -2652,7 +2649,7 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number,
Creates a linear gradient.
**Parameters**
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------------- |
......@@ -2663,7 +2660,7 @@ Creates a linear gradient.
| y1 | number | Yes | 0 | Y-coordinate of the center of the end circle. |
| r1 | number | Yes | 0 | Radius of the end circle, which must be a non-negative finite number.|
**Example**
**Example**
```ts
// xxx.ets
......@@ -2682,9 +2679,9 @@ Creates a linear gradient.
.backgroundColor('#ffff00')
.onReady(() =>{
var grad = this.offContext.createRadialGradient(200,200,50, 200,200,200)
grad.addColorStop(0.0, 'red')
grad.addColorStop(0.5, 'white')
grad.addColorStop(1.0, 'green')
grad.addColorStop(0.0, '#ff0000')
grad.addColorStop(0.5, '#ffffff')
grad.addColorStop(1.0, '#00ff00')
this.offContext.fillStyle = grad
this.offContext.fillRect(0, 0, 500, 500)
var image = this.offContext.transferToImageBitmap()
......@@ -2697,7 +2694,7 @@ Creates a linear gradient.
}
```
![en-us_image_0000001212218480](figures/en-us_image_0000001212218480.png)
![en-us_image_0000001238952407](figures/en-us_image_0000001238952407.png)
## CanvasPattern
......
......@@ -5,27 +5,28 @@ The page transition navigates users between pages. You can customize page transi
> **NOTE**
>
> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
>
| Name | Parameter | Description |
| ------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| PageTransitionEnter | {<br>type: RouteType,<br>duration: number,<br>curve: Curve \| Curves,<br>delay: number<br>} | Page entrance animation.<br>- **type**:If this parameter is not set, the reverse playback effect as **pop** switches to **push** is used.<br>- **duration**: animation duration, in milliseconds.<br>- **curve**: animation curve. For details about the valid values, see [Curve](ts-animatorproperty.md).<br>Default value: **Curve.Linear**<br>- **delay**: animation delay, in milliseconds. By default, the animation is played without delay.|
| PageTransitionExit | {<br>type: RouteType,<br>duration: number,<br>curve: Curve \| Curves,<br>delay: number<br>} | Page exit animation.<br>- **type**:If this parameter is not set, the reverse playback effect as **pop** switches to **push** is used.<br>- **duration**: animation duration, in milliseconds.<br>- **curve**: animation curve. For details about the valid values, see [Curve](ts-animatorproperty.md).<br>Default value: **Curve.Linear**<br>- **delay**: animation delay, in milliseconds. By default, the animation is played without delay.|
| PageTransitionEnter | {<br>type?: RouteType,<br>duration?: number,<br>curve?: [Curve](ts-appendix-enums.md#curve) \| string,<br>delay?: number<br>} | Page entrance animation.<br>- **type**: route type for the page transition effect to take effect.<br>Default value: **RouteType.None**<br>**Note**: If no match is found, the default page transition effect is used (which may vary according to the device). To disable the default page transition effect, set **duration** to **0**.<br>- **duration**: animation duration, in milliseconds.<br>- **curve**: animation curve. The value of the string type can be any of the following: "ease", "ease-in", "ease-out", "ease-in-out", "extreme-deceleration", "fast-out-linear-in", "fast-out-slow-in", "friction", "linear", "linear-out-slow-in", "rhythm", "sharp", "smooth".<br>Default value: **Curve.Linear**<br>- **delay**: animation delay, in milliseconds. By default, the animation is played without delay.|
| PageTransitionExit | {<br>type?: RouteType,<br>duration?: number,<br>curve?: [Curve](ts-appendix-enums.md#curve) \| string,<br>delay?: number<br>} | Page exit animation.<br>- **type**: route type for the page transition effect to take effect.<br>Default value: **RouteType.None**<br>**Note**: If no match is found, the default page transition effect is used (which may vary according to the device). To disable the default page transition effect, set **duration** to **0**.<br>- **duration**: animation duration, in milliseconds.<br>- **curve**: animation curve. The value range of the string type is the same as that of **PageTransitionEnter**.<br>Default value: **Curve.Linear**<br>- **delay**: animation delay, in milliseconds. By default, the animation is played without delay.|
## RouteType enums
| Name| Description |
| ---- | ------------------------------------------------------------ |
| Pop | Redirects to a specified page. When the user is redirected from page A to page B, page A is Exit+Push, and page B is Enter+Push.|
| Push | Redirects to the next page. When the user is redirected back from page B to page A, page A is Enter+Pop, and page B is Exit+Pop.|
| None | The page is not redirected. |
| Pop | Redirects to a specified page. To redirect the user from page B back to page A, set **RouteType** of **PageTransitionExit** to **None** or **Pop** for page B and set **RouteType** of **PageTransitionEnter** to **None** or **Pop** for page A.|
| Push | Redirects to the next page. To redirect the user from page A to page B, set **RouteType** of **PageTransitionExit** to **None** or **Push** for page A and set **RouteType** of **PageTransitionEnter** to **None** or **Push** for page B.|
| None | The page is not redirected. The animation specified by **PageTransitionEnter** takes effect for page entrance, and the animation specified by **PageTransitionExit** takes effect for page exit.|
## Attributes
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| slide | SlideEffect | No | Slide effect during page transition.<br>Default value: **SlideEffect.Right**|
| slide | [SlideEffect](#slideeffect) | No | Slide effect during page transition.<br>Default value: **SlideEffect.Right**|
| translate | {<br>x? : number \| string,<br>y? : number \| string,<br>z? : number \| string<br>} | No | Translation effect during page transition, which is the value of the start point of entrance and the end point of exit. When this parameter is set together with **slide**, the latter takes effect by default.<br>- **x**: translation distance along the x-axis.<br>- **y**: translation distance along the y-axis.<br>- **z**: translation distance along the y-axis.|
| scale | {<br>x? : number,<br>y? : number,<br>z? : number,<br>centerX? : number \| string,<br>centerY? : number \| string<br>} | No | Scaling effect during page transition, which is the value of the start point of entrance and the end point of exit.<br>- **x**: scale ratio along the x-axis.<br>- **y**: scale ratio along the y-axis.<br>- **z**: scale ratio along the z-axis.<br>- **centerX** and **centerY**: scale center point.<br>- If the center point is 0, it refers to the upper left corner of the component.<br>|
| opacity | number | No | Opacity, which is the opacity value of the start point of entrance or the end point of exit.<br>Default value: **1**|
......@@ -63,11 +64,11 @@ struct PageTransitionExample1 {
build() {
Column() {
Navigator({ target: 'pages/page1', type: NavigationType.Push }) {
Image($r('app.media.bg1')).width("100%").height("100%")
Image($r('app.media.bg1')).width('100%').height('100%') // Store the image in the media folder.
}
}.scale({ x: this.scale1 }).opacity(this.opacity1)
}
// Customization method 1: Customize the transition process.
// Customization method 1: Customize the transition process.
pageTransition() {
PageTransitionEnter({ duration: 1200, curve: Curve.Linear })
.onEnter((type: RouteType, progress: number) => {
......@@ -93,12 +94,12 @@ struct AExample {
build() {
Column() {
Navigator({ target: 'pages/index' ,type: NavigationType.Push}) {
Image($r('app.media.bg2')).width("100%").height("100%")
Navigator({ target: 'pages/index', type: NavigationType.Push }) {
Image($r('app.media.bg2')).width('100%').height('100%') // Store the image in the media folder.
}
}.height("100%").width("100%").scale({ x: this.scale2 }).opacity(this.opacity2)
}.width('100%').height('100%').scale({ x: this.scale2 }).opacity(this.opacity2)
}
// Customization method 1: Customize the transition process.
// Customization method 1: Customize the transition process.
pageTransition() {
PageTransitionEnter({ duration: 1200, curve: Curve.Linear })
.onEnter((type: RouteType, progress: number) => {
......@@ -129,12 +130,12 @@ struct PageTransitionExample {
build() {
Column() {
Navigator({ target: 'pages/page1', type: NavigationType.Push }) {
Image($r('app.media.bg1')).width("100%").height("100%")
Image($r('app.media.bg1')).width('100%').height('100%') // Store the image in the media folder.
}
}.scale({ x: this.scale1 }).opacity(this.opacity1)
}
// Customization method 2: Use the default effects provided by the system, such as translation, scaling, and opacity.
// Customization method 2: Use the default effects provided by the system, such as translation, scaling, and opacity.
pageTransition() {
PageTransitionEnter({ duration: 1200 })
.slide(SlideEffect.Left)
......@@ -156,12 +157,12 @@ struct PageTransitionExample1 {
build() {
Column() {
Navigator({ target: 'pages/index', type: NavigationType.Push }) {
Image($r('app.media.bg2')).width ("100%").height("100%")
Image($r('app.media.bg2')).width('100%').height('100%') // Store the image in the media folder.
}
}.scale({ x: this.scale2 }).opacity(this.opacity2)
}
// Customization method 2: Use the default effects provided by the system, such as translation, scaling, and opacity.
// Customization method 2: Use the default effects provided by the system, such as translation, scaling, and opacity.
pageTransition() {
PageTransitionEnter({ duration: 1200 })
.slide(SlideEffect.Left)
......
......@@ -3,12 +3,12 @@
The framework provides four pixel units, with vp as the reference data unit.
| Name| Description |
| ---- | ------------------------------------------------------------ |
| Name | Description |
| ---- | ---------------------------------------- |
| px | Physical pixel unit of the screen. |
| vp | Pixel unit specific to the screen density. Pixels in this unit are converted into physical pixels of the screen based on the screen pixel density. This unit is used for values whose unit is not specified.|
| fp | Font pixel, which is similar to vp and varies according to the system font size.|
| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by **[designWidth](../../quick-start/package-structure.md)**). For example, if **designWidth** is set to **720** (default value), then 1lpx is equal to 2px for a screen with an actual width of 1440 physical pixels.|
| fp | Font pixel, which is similar to vp and varies according to the system font size. |
| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by **designWidth**). For example, if **designWidth** is set to **720** (default value), then 1lpx is equal to 2px for a screen with an actual width of 1440 physical pixels. |
## Pixel Unit Conversion
......
......@@ -16,14 +16,14 @@ Establishes two-way data binding between an attribute and this **LocalStorage**
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | --- | --------------------- |
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ----------- |
| propName | string | Yes | Name of the target attribute.|
**Return value**
| Type | Description |
| ----- | ------------------------------------------------------------ |
| ----- | ---------------------------------------- |
| @Link | Returns two-way binding to this attribute if there is data with a given key. This means that attribute changes made by a variable or component will be synchronized to the **AppStorage**, and attribute changes made through the **AppStorage** will be synchronized to the variable or component.|
```ts
......@@ -38,15 +38,15 @@ Works in a way similar to the **Link** API. If the current key is stored in the
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ------ | --- | -------------------- |
| propName | string | Yes | Target key. |
| defaultValue | T | Yes | Default value to set.|
| Name | Type | Mandatory | Description |
| ------------ | ------ | ---- | ----------- |
| propName | string | Yes | Target key.|
| defaultValue | T | Yes | Default value to set. |
**Return value**
| Type | Description |
| ----- | ------------------------------------------------------------ |
| ----- | ---------------------------------------- |
| @Link | Returns the value corresponding to the key if the current key is stored in the **AppStorage**; creates and returns a **Link** instance corresponding to the default value if the key has not been created.|
```ts
......@@ -61,15 +61,15 @@ Establishes one-way data binding with an attribute to update its status.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | --- | ------------------- |
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ----------- |
| propName | string | Yes | Target key.|
**Return value**
| Type | Description |
| ----- | ------------------------------------------------------------ |
| @Prop | Returns one-way binding to an attribute with a given key if the attribute exists. This means that attribute changes made through the **AppStorage** will be synchronized to the variable or component, but attribute changes made by the variable or component will be synchronized to the **AppStorage**. The variable returned by this method is an immutable one, which is applicable both to the variable and immutable state attributes. If the attribute with the specified key does not exist, **undefined** is returned.|
| ----- | ---------------------------------------- |
| @Prop | Returns one-way binding to an attribute with a given key if the attribute exists; returns **undefined** otherwise. One-way binding means that attribute changes made through the **AppStorage** will be synchronized to the variable or component, but attribute changes made by the variable or component will not be synchronized to the **AppStorage**. This API returns immutable variables and is applicable to mutable and immutable state variables alike.|
```ts
let simple = AppStorage.Prop('simpleProp')
......@@ -83,16 +83,16 @@ Works in a way similar to the **Prop** API. If the current key is stored in the
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ------ | --- | --------------------------- |
| propName | string | Yes | Key in the key-value pair to be saved.|
| Name | Type | Mandatory | Description |
| ------------ | ------ | ---- | --------------- |
| propName | string | Yes | Key of the target key-value pair.|
| defaultValue | S | Yes | Default value to set. |
**Return value**
| Type | Description |
| ----- | ------------------------------------------------------------ |
| @Prop | Returns the value corresponding to the key if the current key is stored in the **AppStorage**; creates and returns a **Prop** instance corresponding to the default value otherwise. |
| ----- | ---------------------------------------- |
| @Prop | Returns the value corresponding to the key if the current key is stored in the **AppStorage**; creates and returns a **Prop** instance corresponding to the default value otherwise.|
```ts
let simple = AppStorage.SetAndProp('simpleProp', 121)
......@@ -106,14 +106,14 @@ Checks whether the attribute corresponding to the specified key exists.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | --- | -------------- |
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ------- |
| propName | string | Yes | Key of the attribute.|
**Return value**
| Type | Description |
| ------- | -------------------------- |
| ------- | ------------- |
| boolean | Returns whether the attribute exists.|
```ts
......@@ -128,15 +128,15 @@ Obtains the value of the specified key.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------- |
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ----------- |
| propName | string | Yes | Key of the value to obtain.|
**Return value**
| Type | Description |
| ------------------ | -------------------------- |
| boolean or undefined| Returns whether the value of the attribute exists.|
| ----------------- | ------------- |
| T or undefined| Returns the attribute value if the attribute exists; returns **undefined** otherwise.|
```ts
let simple = AppStorage.Get('simpleProp')
......@@ -150,15 +150,15 @@ Replaces the value of a saved key.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | --- | ----------------- |
| propName | string | Yes | Key of the value to set. |
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ----------- |
| propName | string | Yes | Key to set. |
| newValue | T | Yes | Value to set.|
**Return value**
| Type | Description |
| ------- | ----------------------------------------------------- |
| ------- | ----------------------------------- |
| boolean | Returns **true** and the value if the key exists; returns **false** otherwise.|
```ts
......@@ -173,15 +173,15 @@ Creates or updates the value of the specified key.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | --- | ------------------------- |
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | --------------- |
| propName | string | Yes | Key to set. |
| newValue | T | Yes | Value to be updated or created.|
**Return value**
| Type | Description |
| ------- | ------------------------------------------------------------ |
| ------- | ---------------------------------------- |
| boolean | Updates the value of the attribute and returns **true** if an attribute that has the same name as the specified key exists; creates an attribute with the specified value as its default value and returns **false** otherwise. **undefined** and **null** are not allowed to return **true**.|
```ts
......@@ -196,14 +196,14 @@ Deletes the key-value pair that matches the specified key.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | --- | --------------------- |
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ------------ |
| propName | string | Yes | Key of the target key-value pair.|
**Return value**
| Type | Description |
| ------- | ------------------------------------------------------------ |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the key-value pair exists and is successfully deleted; returns **false** otherwise.|
```ts
......@@ -219,7 +219,7 @@ Searches for all keys.
**Return value**
| Type | Description |
| -------------- | ---------------------------- |
| -------------- | -------------- |
| array\<string> | Returns an array of strings containing all keys.|
```ts
......@@ -232,16 +232,34 @@ staticClear(): boolean
Deletes all attributes.
This API is deprecated since API version 9. You are advised to use [Clear](#clear) instead.
**Return value**
| Type | Description |
| ------- | ------------------------------------------------------------ |
| ------- | --------------------------------- |
| boolean | Returns **true** if all attributes are deleted; returns **false** if any of the attributes is being referenced by a state variable.|
```ts
let simple = AppStorage.staticClear()
```
### Clear<sup>9+</sup>
Clear(): boolean
Deletes all attributes.
**Return value**
| Type | Description |
| ------- | --------------------------------- |
| boolean | Returns **true** if all attributes are deleted; returns **false** if any of the attributes is being referenced by a state variable.|
```typescript
let simple = AppStorage.Clear()
```
### IsMutable
IsMutable(propName: string): boolean
......@@ -250,14 +268,14 @@ Checks whether an attribute exists and can be changed.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | :--- | --------------------- |
| Name | Type | Mandatory | Description |
| -------- | ------ | :--- | ------------ |
| propName | string | Yes | Key of the target attribute.|
**Return value**
| Type | Description |
| ------- | ------------------------------------ |
| ------- | ------------------ |
| boolean | Returns whether the attribute exists and can be changed.|
```ts
......@@ -268,12 +286,12 @@ let simple = AppStorage.IsMutable('simpleProp')
Size(): number
Checks the number of existing key-value pairs.
Obtains the number of existing key-value pairs.
**Return value**
| Type | Description |
| ------ | ------------------ |
| ------ | --------- |
| number | Returns the number of key-value pairs.|
```ts
......@@ -290,8 +308,8 @@ Creates and initializes a **LocalStorage** object.
**Parameters**
| Name | Type | Mandatory| Description |
| ---------------------- | ------ | ---- | ------------------------------------------------------------ |
| Name | Type | Mandatory | Description |
| ---------------------- | ------ | ---- | ---------------------------------------- |
| initializingProperties | Object | No | All object attributes and their values returned by **object.keys(obj)**.|
```ts
......@@ -309,7 +327,7 @@ This API can be used only in the stage model.
**Return value**
| Type | Description |
| ----------------------------- | ---------------------- |
| ----------------------------- | ----------------- |
| [LocalStorage](#localstorage) | **LocalStorage** object.|
```ts
......@@ -324,14 +342,14 @@ Checks whether the **LocalStorage** contains the specified attribute.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | --- | -------------- |
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ------- |
| propName | string | Yes | Key of the attribute.|
**Return value**
| Type | Description |
| ------- | -------------------------- |
| ------- | ------------- |
| boolean | Returns whether the attribute exists.|
```ts
......@@ -347,14 +365,14 @@ Obtains the value of the specified key.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | --- | ------------------- |
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ----------- |
| propName | string | Yes | Key of the value to obtain.|
**Return value**
| Type | Description |
| -------------- | ------------------------------------------------------- |
| -------------- | ---------------------------------------- |
| T \| undefined | Returns the value of the specified key if it exists; returns **undefined** otherwise.|
```ts
......@@ -370,16 +388,16 @@ Sets a new value for the specified key.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | --- | ----------------- |
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ----------- |
| propName | string | Yes | Key to set. |
| newValue | T | Yes | Value to set.|
**Return value**
| Type | Description |
| ------- | ----------------------------------------------------- |
| boolean | Returns **true** if the specified key exists and the value is set; returns **false** otherwise.|
| ------- | ----------------------------------- |
| boolean | Returns **true** and the value if the key exists; returns **false** otherwise.|
```ts
this.storage = new LocalStorage()
......@@ -394,15 +412,15 @@ Creates or updates the value of the specified key.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | :--- | ----------------------- |
| Name | Type | Mandatory | Description |
| -------- | ------ | :--- | -------------- |
| propName | string | Yes | Key of the value to create or update. |
| newValue | T | Yes | Value to be updated or created.|
**Return value**
| Type | Description |
| ------- | ------------------------------------------------------------ |
| ------- | ---------------------------------------- |
| boolean | Updates the value of the attribute and returns **true** if an attribute that has the same name as the specified key exists; creates an attribute with the specified value as its default value and returns false otherwise. **undefined** and **null** are not allowed.|
```ts
......@@ -418,14 +436,14 @@ Establishes two-way data binding between an attribute and this **LocalStorage**
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | --- | ---------------------- |
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ----------- |
| propName | string | Yes | Name of the target attribute.|
**Return value**
| Type| Description |
| ---- | ------------------------------------------------------------ |
| Type | Description |
| ---- | ---------------------------------------- |
| T | Returns two-way binding to this attribute if there is data with a given key. This means that attribute changes made by a variable or component will be synchronized to the **LocalStorage**, and attribute changes made through the **LocalStorage** will be synchronized to the variable or component. returns **undefined** if the attribute with the given key does not exist.|
```ts
......@@ -441,15 +459,15 @@ Works in a way similar to the **Link** API.
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ------ | --- | -------------------- |
| propName | string | Yes | Target key. |
| defaultValue | T | Yes | Default value to set.|
| Name | Type | Mandatory | Description |
| ------------ | ------ | ---- | ----------- |
| propName | string | Yes | Target key.|
| defaultValue | T | Yes | Default value to set. |
**Return value**
| Type | Description |
| ------------------------------------ | ------------------------------------------------------------ |
| ----- | ---------------------------------------- |
| @Link | Returns the value corresponding to the key if the current key is stored in the **LocalStorage**; creates and returns a **Link** instance corresponding to the default value if the key has not been created.|
```ts
......@@ -465,15 +483,15 @@ Establishes one-way data binding with an attribute to update its status.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | --- | ----------------------- |
| Name | Type | Mandatory | Description |
| -------- | ------ | ---- | ------------- |
| propName | string | Yes | Key of the attribute.|
**Return value**
| Type | Description |
| ------------------------------------ | ------------------------------------------------------------ |
| @Prop | Returns one-way binding to an attribute with a given key if the attribute exists; returns **undefined** otherwise. This means that attribute changes made through the **LocalStorage** will be synchronized to the variable or component, but attribute changes made by the variable or component will be synchronized to the **LocalStorage**. This API returns immutable variables and is applicable to mutable and immutable state variables. |
| ----- | ---------------------------------------- |
| @Prop | Returns one-way binding to an attribute with a given key if the attribute exists; returns **undefined** otherwise. One-way binding means that attribute changes made through the **LocalStorage** will be synchronized to the variable or component, but attribute changes made by the variable or component will not be synchronized to the **LocalStorage**. This API returns immutable variables and is applicable to mutable and immutable state variables alike. |
```ts
this.storage = new LocalStorage()
......@@ -488,15 +506,15 @@ Works in a way similar to the **Prop** API.
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ------ | --- | ------------------------- |
| Name | Type | Mandatory | Description |
| ------------ | ------ | ---- | -------------- |
| propName | string | Yes | Key of the target key-value pair.|
| defaultValue | T | Yes | Default value to set. |
**Return value**
| Type | Description |
| ------------------------------------ | ------------------------------------------------------------ |
| ----- | ---------------------------------------- |
| @Prop | Returns the value corresponding to the given key if the key is stored in the **LocalStorage**; creates and returns a **Prop** instance corresponding to the default value if the key has not been created.|
```ts
......@@ -512,15 +530,15 @@ Deletes the key-value pair that matches the specified key.
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | :--- | --------------------- |
| Name | Type | Mandatory | Description |
| -------- | ------ | :--- | ------------ |
| propName | string | Yes | Key of the target key-value pair.|
**Return value**
| Type | Description |
| ------- | ------------------------------------------------------------ |
| boolean | Returns **true** if the key-value pair exists and is successfully deleted; returns **false** if the key-value pair does not exist, fails to be deleted, or is being referenced by a state varaiable.|
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the key-value pair exists and is successfully deleted; returns **false** if the key-value pair does not exist, fails to be deleted, or is being referenced by a state variable.|
```ts
this.storage = new LocalStorage()
......@@ -536,7 +554,7 @@ Searches for all keys.
**Return value**
| Type | Description |
| -------------- | -------------------------------------- |
| -------------- | ------------------- |
| array\<string> | Returns an array of strings containing all keys that are not serializable.|
```ts
......@@ -553,7 +571,7 @@ Obtains the number of existing key-value pairs.
**Return value**
| Type | Description |
| ------ | ------------------ |
| ------ | --------- |
| number | Returns the number of key-value pairs.|
```ts
......@@ -570,7 +588,7 @@ Deletes all attributes.
**Return value**
| Type | Description |
| ------- | ------------------------------------------------------------ |
| ------- | --------------------------------- |
| boolean | Returns **true** if all attributes are deleted; returns **false** if any of the attributes is being referenced by a state variable.|
```ts
......@@ -588,8 +606,8 @@ Creates a **persistentstorage** object.
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ---------- | --- | -------------------------------- |
| Name | Type | Mandatory | Description |
| ---------- | ---------- | ---- | ---------------- |
| appStorage | AppStorage | Yes | Singleton object that saves all attributes and attribute values.|
| storage | Storage | Yes | **Storage** object. |
......@@ -605,8 +623,8 @@ Changes the attribute that matches the specified key to persistent data in the *
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ------ | --- | ----------------------- |
| Name | Type | Mandatory | Description |
| ------------ | ------ | ---- | -------------- |
| key | string | Yes | Key of the target attribute. |
| defaultValue | T | Yes | Value of the target attribute.|
......@@ -622,8 +640,8 @@ Cancels two-way binding. The value of this attribute will be deleted from the pe
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | --- | --------------------- |
| Name | Type | Mandatory | Description |
| ---- | ------ | ---- | ------------ |
| key | string | Yes | Key of the target attribute.|
```ts
......@@ -638,8 +656,8 @@ Changes the attributes that match the specified keys to persistent data in the *
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ---------------------------------- | -- | ------------------ |
| Name | Type | Mandatory | Description |
| ---- | ---------------------------------- | ---- | --------- |
| key | {key: string, defaultValue: any}[] | Yes | Keys of the target attributes.|
```ts
......@@ -655,7 +673,7 @@ Returns the flags of all persistent attributes.
**Return value**
| Type | Description |
| ------------- | -------------------------- |
| -------------- | ------------- |
| Array\<string> | Returns the flags of all persistent attributes.|
```ts
......@@ -686,26 +704,26 @@ Binds this system attribute to the **AppStorage**. You are advised to use this A
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | --- | --------------- |
| key | string | Yes | Key of the target attribute. For details, see **Built-in environment variables**. |
| value | S | Yes | Value of the target attribute.|
| Name | Type | Mandatory | Description | Description |
| ----- | ------ | ---- | ---------- | ------------------------- |
| key | string | Yes | Key of the target attribute. | For details, see **Built-in environment variables**.|
| value | S | Yes | Value of the target attribute.| Value of the target attribute. |
**Return value**
| Type | Description |
| ------- | ---------------------------------- |
| ------- | ---------------------- |
| boolean | Returns whether the attribute exists in the **AppStorage**.|
**Built-in environment variables**
| key | Type | Description |
| ------------ | ------------- | ------------------- |
| -------------------- | --------------- | ---------------------------------------- |
| accessibilityEnabled | string | Whether to enable accessibility. |
| colorMode | ColorMode | Color mode. The options are as follows:<br>- **ColorMode.LIGHT**: light mode.<br>- **ColorMode.DARK**: dark mode. |
| colorMode | ColorMode | Color mode. The options are as follows:<br>- **ColorMode.LIGHT**: light mode.<br>- **ColorMode.DARK**: dark mode.|
| fontScale | number | Font scale. |
| fontWeightScale | number | Font weight scale. |
| layoutDirection | LayoutDirection | Layout direction. The options are as follows:<br>- **LayoutDirection.LTR**: The direction is from left to right.<br>- **LayoutDirection.RTL**: The direction is from right to left. |
| layoutDirection | LayoutDirection | Layout direction. The options are as follows:<br>- **LayoutDirection.LTR**: The direction is from left to right.<br>- **LayoutDirection.RTL**: The direction is from right to left.|
| languageCode | string | Current system language. The value is in lowercase, for example, **zh**. |
```ts
......@@ -720,9 +738,9 @@ Associates this system item array with the **AppStorage**.
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ---------------------------------- | --- | ------------------ |
| key | {key: string, defaultValue: any}[] | Yes | Keys of the target attributes.|
| Name | Type | Mandatory | Description | Description |
| ---- | ---------------------------------- | ---- | --------- | --------- |
| key | {key: string, defaultValue: any}[] | Yes | Keys of the target attributes.| Keys of the target attributes.|
```ts
Environment.EnvProps([{key: 'accessibilityEnabled', defaultValue: 'default'},{key: 'accessibilityUnEnabled', defaultValue: 'undefault'}])
......@@ -737,7 +755,7 @@ Returns an array of associated system attributes.
**Return value**
| Type | Description |
| ------------- | ---------------------- |
| -------------- | ----------- |
| Array\<string> | Returns an array of associated system attributes.|
```ts
......
......@@ -20,46 +20,44 @@ Configure the component transition animations for when a component is inserted o
| -------- | -------- | -------- | -------- |
| type | [TransitionType](ts-appendix-enums.md#transitiontype) | No| Transition type, which includes component addition and deletion by default.<br>Default value: **TransitionType.All**<br>**NOTE**<br>If **type** is not specified, insertion and deletion use the same transition type.|
| opacity | number | No| Opacity of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>Default value: **1**|
| translate | {<br>x? : number,<br>y? : number,<br>z? : number<br>} | No| Translation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>-**x**: distance to translate along the x-axis.<br>-**y**: distance to translate along the y-axis.<br>-**z**: distance to translate along the z-axis.|
| scale | {<br>x? : number,<br>y? : number,<br>z? : number,<br>centerX? : number,<br>centerY? : number<br>} | No| Scaling of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: scale factor along the x-axis.<br>- **y**: scale factor along the y-axis.<br>- **z**: scale factor along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the scale center, respectively.<br>- If the center point is 0, it indicates the upper left corner of the component.<br>|
| rotate | {<br>x?: number,<br>y?: number,<br>z?: number,<br>angle?: Angle,<br>centerX?: Length,<br>centerY?: Length<br>} | No| Rotation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: rotation vector along the x-axis.<br>- **y**: rotation vector along the y-axis.<br>- **z**: rotation vector along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the rotation center, respectively.<br>- If the center point is (0, 0), it indicates the upper left corner of the component.|
| translate | {<br>x? : number \| string,<br>y? : number \| string,<br>z? : number \| string<br>} | No| Translation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>-**x**: distance to translate along the x-axis.<br>-**y**: distance to translate along the y-axis.<br>-**z**: distance to translate along the z-axis.|
| scale | {<br>x? : number,<br>y? : number,<br>z? : number,<br>centerX? : number \| string,<br>centerY? : number \| string<br>} | No| Scaling of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: scale factor along the x-axis.<br>- **y**: scale factor along the y-axis.<br>- **z**: scale factor along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the scale center, respectively. The default values are both **"50%"**.<br>- If the center point is 0, it indicates the upper left corner of the component.<br>|
| rotate | {<br>x?: number,<br>y?: number,<br>z?: number,<br>angle?: number \| string,<br>centerX?: number \| string,<br>centerY?: number \| string<br>} | No| Rotation of the component during transition, which is the value of the start point of insertion and the end point of deletion.<br>- **x**: rotation vector along the x-axis.<br>- **y**: rotation vector along the y-axis.<br>- **z**: rotation vector along the z-axis.<br>- **centerX** and **centerY**: x coordinate and y coordinate of the rotation center, respectively. The default values are both **"50%"**.<br>- If the center point is (0, 0), it indicates the upper left corner of the component.|
## Example
The following example shows how to use a button to control the appearance and disappearance of another button, and how to configure the required transition animations.
```ts
// xxx.ets
@Entry
@Component
struct TransitionExample {
@State btn: boolean = false
@State show: string = "show"
@State flag: boolean = true
@State show: string = 'show'
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center,}) {
Button(this.show).width(80).height(30).backgroundColor(0x317aff).margin({bottom:50})
Column() {
Button(this.show).width(80).height(30).margin(30)
.onClick(() => {
// Click the button to show or hide the image.
animateTo({ duration: 1000 }, () => {
this.btn = !this.btn
if(this.btn){
this.show = "hide"
}else{
this.show = "show"
if (this.flag) {
this.show = 'hide'
} else {
this.show = 'show'
}
this.flag = !this.flag
})
})
if (this.btn) {
// The insertion and deletion have different transition effects.
Button() {
Image($r('app.media.bg1')).width("80%").height(300)
}.transition({ type: TransitionType.Insert, scale : {x:0,y:1.0} })
.transition({ type: TransitionType.Delete, scale: { x: 1.0, y: 0.0 } })
if (this.flag) {
// Apply different transition effects to the appearance and disappearance of the image.
Image($r('app.media.testImg')).width(300).height(300)
.transition({ type: TransitionType.Insert, scale: { x: 0, y: 1.0 } })
.transition({ type: TransitionType.Delete, rotate: { angle: 180 } })
}
}.height(400).width("100%").padding({top:100})
}.width('100%')
}
}
```
![en-us_image_0000001211898498](figures/en-us_image_0000001211898498.gif)
![animateTo](figures/animateTo.gif)
......@@ -12,12 +12,12 @@ Shared element transition can be used for transition between pages, for example,
| Name | Parameters | Description |
| ---------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| sharedTransition | id: string,<br>{<br>duration?: number,<br>curve?: Curve \| string,<br>delay?: number,<br>motionPath?: <br>{<br>path: string,<br>form?: number,<br>to?: number,<br>rotatable?: boolean<br>},<br>zIndex?: number,<br>type?: [SharedTransitionEffectType](ts-appendix-enums.md#sharedtransitioneffecttype)<br>} | Transition of the shared element. If the same **id** value is configured for a component on the two pages, this component is considered as a shared element of the pages. If the **id** value is an empty string, no transition will be applied to the component.<br>- **id**: component ID.<br>- **duration**: Animation duration, in ms. The default duration is 1000 ms.<br>- **curve**: animation curve. The default curve is **Linear**. For details about the valid values, see [Curve](ts-animatorproperty.md).<br>- **delay**: Delay of animation playback, in ms. By default, the playback is not delayed.<br>- **motionPath**: motion path information.<br>- **path**: path.<br>- **from**: start value.<br>- **to**: end value.<br>- **rotatable**: whether to rotate.<br>- **zIndex**: z-axis.<br>- **type**: animation type.|
| sharedTransition | id: string,<br>{<br> duration?: number,<br> curve?: Curve \| string,<br> delay?: number,<br> motionPath?: <br>{<br> path: string,<br> form?: number,<br> to?: number,<br> rotatable?: boolean<br>},<br>zIndex?: number,<br>type?: [SharedTransitionEffectType](ts-appendix-enums.md#sharedtransitioneffecttype)<br>} | Transition of the shared element. If the same **id** value is configured for a component on the two pages, this component is considered as a shared element of the pages. If the **id** value is an empty string, no transition will be applied to the component.<br>- **id**: component ID.<br>- **duration**: animation duration, in ms. The default duration is 1000 ms.<br>- **curve**: animation curve. The default curve is **Linear**. For details about the valid values, see [Curve](ts-animatorproperty.md).<br>- **delay**: Delay of animation playback, in ms. By default, the playback is not delayed.<br>- **motionPath**: motion path information. For details, see [Motion Path Animation](ts-motion-path-animation.md).<br>- **path**: path.<br>- **from**: start value.<br>- **to**: end value.<br>- **rotatable**: whether to rotate.<br>- **zIndex**: z-axis.<br>- **type**: animation type.|
## Example
The example implements the custom transition of a shared image during redirection from one page to another, which is triggered by a click on the image.
The example implements the custom transition of a shared image during redirection from one page to another, which is triggered by a click on the image.
```ts
// xxx.ets
......@@ -27,20 +27,14 @@ struct SharedTransitionExample {
@State active: boolean = false
build() {
List() {
ListItem() {
Row() {
Navigator({ target: 'pages/common/Animation/transAnimation/PageB', type: NavigationType.Push }) {
Column() {
Navigator({ target: 'pages/PageB', type: NavigationType.Push }) {
Image($r('app.media.ic_health_heart')).width(50).height(50)
.sharedTransition('sharedImage1', { duration: 800, curve: Curve.Linear, delay: 100 })
}.padding({ left: 10 })
.sharedTransition('sharedImage', { duration: 800, curve: Curve.Linear, delay: 100 })
}.padding({ left: 20, top: 20 })
.onClick(() => {
this.active = true
})
Text('SharedTransition').width(80).height(80).textAlign(TextAlign.Center)
}
}
}
}
}
......@@ -50,14 +44,13 @@ struct SharedTransitionExample {
// PageB.ets
@Entry
@Component
struct BExample {
struct pageBExample {
build() {
Stack() {
Image($r('app.media.ic_health_heart')).width(150).height(150).sharedTransition('sharedImage1')
}.width('100%').height(400)
Image($r('app.media.ic_health_heart')).width(150).height(150).sharedTransition('sharedImage')
}.width('100%').height('100%')
}
}
```
![en-us_image_0000001211898494](figures/en-us_image_0000001211898494.gif)
![shared](figures/shared.gif)
......@@ -18,6 +18,10 @@ You can use `$r` or `$rawfile` to create a **Resource** object, but its attribut
**filename**: name of the file in the **resources/rawfile** directory of the project.
> **NOTE**
>
> When referencing resources of the **Resource** type, make sure the data type is the same as that of the attribute method. For example, if an attribute method supports the **string | Resource** types, the data type of the **Resource** type must be string.
## Length
The **Length** type is used to represent a size unit.
......@@ -138,11 +142,11 @@ The **LengthConstrain** type is used to describe the maximum and minimum lengths
The **Font** type is used to set the text style.
| Name | Type | Mandatory | Description |
| ------ | ---------------------------------------- | ---- | ---------------------------------------- |
| size | [Length](#length) | No | Font size. If the value is of the number type, the unit fp is used. |
| Name | Type | Mandatory| Description |
| ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| size | [Length](#length) | No | Font size. If the value is of the number type, the unit fp is used. The value cannot be a percentage.|
| weight | [FontWeight](ts-appendix-enums.md#fontweight) \| number \| string | No | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight.|
| family | string \| [Resource](#resource) | No | Font family of the text. Use commas (,) to separate multiple fonts. The priority of the fonts is the sequence in which they are placed. An example value is **'Arial, sans-serif'**.|
| family | string \| [Resource](#resource) | No | Font family of the text. Use commas (,) to separate multiple fonts. The priority of the fonts is the sequence in which they are placed. An example value is **'Arial, sans-serif'**. Currently, only the **'sans-serif'** font is supported.|
| style | [FontStyle](ts-appendix-enums.md#fontstyle) | No | Font style. |
## Area<sup>8+</sup>
......@@ -212,4 +216,4 @@ The **CustomBuilder** type is used to define custom UI descriptions in component
| Name | Type | Description |
| ------------- | ---------------------- | ---------------------------------------- |
| CustomBuilder | ()&nbsp;=&gt;&nbsp;any | Must be decorated by **@Builder**. For details, see [@Builder](../../quick-start/arkts-dynamic-ui-elememt-building.md#builder).|
| CustomBuilder | () =&gt; any | Must be decorated by **@Builder**. For details, see [@Builder](../../quick-start/arkts-dynamic-ui-elememt-building.md#builder).|
......@@ -85,7 +85,7 @@ struct Index {
build() {
Row() {
Column() {
Text('This is gradient color.').textAlign(TextAlign.Center)
Text('This is gradient color.').textAlign(TextAlign.Center).width(68)
.borderImage({
source: {
angle: 90,
......
......@@ -23,6 +23,8 @@ getInspectorByKey(id: string): string
Obtains all attributes of the component with the specified ID, excluding the information about child components.
This API is used only for test purposes.
**Parameters**
| Name | Type | Mandatory | Description |
......@@ -41,6 +43,8 @@ getInspectorTree(): string
Obtains the component tree and component attributes.
This API is used only for test purposes.
**Return value**
| Type | Description |
......@@ -53,6 +57,8 @@ sendEventByKey(id: string, action: number, params: string): boolean
Sends an event to the component with the specified ID.
This API is used only for test purposes.
**Parameters**
| Name | Type | Mandatory | Description |
......@@ -73,6 +79,8 @@ sendTouchEvent(event: TouchObject): boolean
Sends a touch event.
This API is used only for test purposes.
**Parameters**
| Name | Type | Mandatory | Description |
......@@ -91,6 +99,8 @@ sendKeyEvent(event: KeyEvent): boolean
Sends a key event.
This API is used only for test purposes.
**Parameters**
| Name | Type | Mandatory | Description |
......@@ -109,6 +119,8 @@ sendMouseEvent(event: MouseEvent): boolean
Sends a mouse event.
This API is used only for test purposes.
**Parameters**
| Name | Type | Mandatory | Description |
......
......@@ -10,10 +10,10 @@
| Name | Type | Description |
| ---------- | ---------------------------------------- | ---------------------------------------- |
| flexBasis | number \| string | Base size of a component in the main axis of the parent container.<br>Default value: **'auto'** (indicating that the base size of the component in the main axis is the original size of the component)|
| flexBasis | number \| string | Base size of the component in the main axis of the parent container.<br>Default value: **'auto'** (indicating that the base size of the component in the main axis is the original size of the component)<br>This attribute cannot be set in percentage.|
| flexGrow | number | Percentage of the parent container's remaining space that is allocated to the component.<br>Default value: **0** |
| flexShrink | number | Percentage of the parent container's shrink size that is allocated to the component.<br>When the parent container is **\<Row>** or **\<Column>**, the default value is **0**.<br> When the parent container is **\<Flex>**, the default value is **1**. |
| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | Alignment mode of the child components along the cross axis, which overwrites the default **alignItems** configuration in the parent container.<br>Default value: **ItemAlign.Auto**|
| alignSelf | [ItemAlign](ts-appendix-enums.md#itemalign) | Alignment mode of the child components along the cross axis of the parent container. The setting overwrites the **alignItems** setting of the parent container.<br>Default value: **ItemAlign.Auto**|
## Example
......@@ -30,82 +30,79 @@ struct FlexExample {
// The value of flexBasis() can be 'auto' or a number, which is equivalent to .width()/.height().
Flex() {
Text('flexBasis(100)')
.flexBasis('100')
.flexBasis(100) // The width is 100 vp.
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('flexBasis("auto")')
.flexBasis('auto')
Text(`flexBasis('auto')`)
.flexBasis('auto') // The width is 60% of the original width.
.width('60%')
.height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('flexGrow').fontSize(9).fontColor(0xCCCCCC).width('90%')
// Percentage of the remaining space
// flexGrow() specifies the percentage of the remaining space allocated to the component.
// flexGrow() indicates the percentage of the remaining space allocated to the component.
Flex() {
Text('flexGrow(2)')
.flexGrow(2)
.flexGrow(2) // The width allocated to the <Text> component is 2/3 of the remaining width of the parent container.
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('flexGrow(1)')
.flexGrow(1)
.flexGrow(1) // The width allocated to the <Text> component is 1/3 of the remaining width of the parent container.
.height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('flexShrink').fontSize(9).fontColor(0xCCCCCC).width('90%')
// flexShrink() specifies the percentage of the shrink size allocated to the component.
// The ratio of text1 is 0, and the default values of other parameters are 1. If the components cannot be completely displayed, the last two components are shrunk proportionally. The first component is not shrunk.
// flexShrink() indicates the percentage of the shrink size allocated to the component.
// The value is 0 for the first <Text> component and 1 for the other two <Text> components. This means that, if the components cannot be completely displayed in the parent container, the latter two are shrunk proportionally, while the former is not shrunk.
Flex({ direction: FlexDirection.Row }) {
Text('flexShrink(0)')
.flexShrink(0)
.width('50%')
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('no flexShrink')
Text('default flexShrink') // The default value is 1.
.width('40%')
.height(100)
.lineHeight(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
Text('flexShrink(2)')
.flexShrink(2)
Text('flexShrink(1)')
.flexShrink(1)
.width('40%')
.height(100)
.lineHeight(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
Text('alignSelf').fontSize(9).fontColor(0xCCCCCC).width('90%')
// alignSelf() overwrites the default alignItems configuration in the flex layout.
// The alignSelf setting overrides the alignItems setting of the parent container.
Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) {
Text('no alignSelf,height:80').width('33%').height(80)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
Text('alignSelf stretch')
.alignSelf(ItemAlign.Stretch)
Text('no alignSelf,height:70')
.width('33%')
.height(80)
.lineHeight(70)
.height(70)
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
Text('alignSelf End')
.alignSelf(ItemAlign.End)
.width('33%')
.height(70)
.backgroundColor(0xD2B48C)
.textAlign(TextAlign.Center)
Text('no alignSelf,height:100').width('34%').height(100)
.backgroundColor(0xF5DEB3).textAlign(TextAlign.Center)
Text('no alignSelf,height:100%')
.width('34%')
.height('100%')
.backgroundColor(0xF5DEB3)
.textAlign(TextAlign.Center)
}.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE)
}.width('100%').margin({ top: 5 })
}
}
```
![en-us_image_0000001212378394](figures/en-us_image_0000001212378394.png)
![flex](figures/flex.PNG)
......@@ -11,10 +11,10 @@ Focus control attributes set whether a component is focusable, how it participat
| Name | Type| Description |
| -------------------- | -------- | ---------------------------------------- |
| focusable | boolean | Whether the current component is focusable.<br>**NOTE**<br><br>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. |
| focusable | boolean | Whether the current component is focusable.<br>**NOTE**<br>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](ts-universal-focus-event.md). |
| tabIndex<sup>9+</sup> | number | How the current component participates in sequential keyboard navigation.<br>- **tabIndex** >= 0: The component is focusable in sequential keyboard navigation, with its order defined by the value. A component with a larger value gains focus later than one with a smaller value. If multiple components share the same **tabIndex** value, their focus order follows their position in the component tree.<br>- **tabIndex** < 0 (usually **tabIndex** = -1): The component is focusable, but cannot be reached through sequential keyboard navigation.<br>Default value: **0**|
| defaultFocus<sup>9+</sup> | boolean | Whether to set the current component as the default focus of the page. This attribute takes effect only when the page is new and accessed for the first time.<br>Default value: **false**|
| groupDefaultFocus<sup>9+</sup> | boolean | Whether to set the current component as the default focus of the parent container. This attribute takes effect only when the container is new and has focus for the first time.<br>Default value: **false**<br>**NOTE**<br>This attribute must be used together with **tabIndex**. When **tabIndex** is set for a container and **groupDefaultFocus** is set for a component in the container, the focus is automatically shifted to that component when the container obtains the focus for the first time.<br>|
| groupDefaultFocus<sup>9+</sup> | boolean | Whether to set the current component as the default focus of the parent container. This attribute takes effect only when the container is new and has focus for the first time.<br>Default value: **false**<br>**NOTE**<br>This attribute must be used together with **tabIndex**. When **tabIndex** is set for a container and **groupDefaultFocus** is set for a component in the container, the focus is automatically shifted to that component when the container obtains the focus for the first time. |
| focusOnTouch<sup>9+</sup> | boolean | Whether the current component is focusable on touch.<br>Default value: **false**<br>**NOTE**<br>The component can obtain focus only when it is touchable or clickable.|
## focusControl<sup>9+</sup>
......@@ -178,15 +178,15 @@ When you press the Tab button for the first time, the focus switches to the comp
![defaultFocus](figures/defaultFocus.png)
When you press Tab button for the second time, the focus switches to the container that matches **tabIndex(1)** and automatically moves to the component bound to **groupDefaultFocus**.
When you press the Tab button for the second time, the focus switches to the container that matches **tabIndex(1)** and automatically moves to the component bound to **groupDefaultFocus**.
![groupDefaultFocus1](figures/groupDefaultFocus1.png)
When you press Tab button for the third time, the focus switches to the container that matches **tabIndex(2)** and automatically moves to the component bound to **groupDefaultFocus**.
When you press the Tab button for the third time, the focus switches to the container that matches **tabIndex(2)** and automatically moves to the component bound to **groupDefaultFocus**.
![groupDefaultFocus2](figures/groupDefaultFocus2.png)
When you press Tab button for the fourth time, the focus switches to the container that matches **tabIndex(3)** and automatically moves to the component bound to **groupDefaultFocus**.
When you press the Tab button for the fourth time, the focus switches to the container that matches **tabIndex(3)** and automatically moves to the component bound to **groupDefaultFocus**.
![groupDefaultFocus3](figures/groupDefaultFocus3.png)
......@@ -198,7 +198,7 @@ Click the component bound to **focusOnTouch**. The component then obtains the fo
Sample code for **focusControl.requestFocus**:
Use the **focusContrl.requestFocus** API to enable a specified component to obtain the focus.
Use the **focusContrl.requestFocus** API to enable a specified component to obtain focus.
```ts
// requestFocus.ets
import prompt from '@ohos.prompt'
......@@ -251,7 +251,7 @@ struct RequestFocusExample {
Button("RequestFocus")
.width(200).height(70).fontColor(Color.White)
.onClick(() => {
var res = focusControl.requestFocus(this.selectId) // Enable the component selected by this.selectId to obtain the focus.
var res = focusControl.requestFocus(this.selectId) // Enable the component selected by this.selectId to obtain focus.
if (res) {
prompt.showToast({message: 'Request success'})
} else {
......@@ -268,14 +268,14 @@ Diagrams:
Press the Tab button to activate the focus state.
Below show how the UI behaves when you request focus for a component that does not exist.
Below shows how the UI behaves when you request focus for a component that does not exist.
![requestFocus1](figures/requestFocus1.png)
Below show how the UI behaves when you request focus for a component that is not focusable.
Below shows how the UI behaves when you request focus for a component that is not focusable.
![requestFocus2](figures/requestFocus2.png)
Below show how the UI behaves when you request focus for a focusable component.
Below shows how the UI behaves when you request focus for a focusable component.
![requestFocus3](figures/requestFocus3.png)
# 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.
......@@ -10,7 +11,7 @@
| 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**|
......@@ -23,8 +24,9 @@
@Entry
@Component
struct GridContainerExample1 {
build(){
build() {
Column() {
Text('useSizeType').fontSize(15).fontColor(0xCCCCCC).width('90%')
GridContainer() {
Row({}) {
Row() {
......@@ -36,6 +38,7 @@ struct GridContainerExample1 {
})
.height("100%")
.backgroundColor(0x66bbb2cb)
Row() {
Text('Center').fontSize(25)
}
......@@ -45,6 +48,7 @@ struct GridContainerExample1 {
})
.height("100%")
.backgroundColor(0x66b6c5d1)
Row() {
Text('Right').fontSize(25)
}
......@@ -56,9 +60,40 @@ struct GridContainerExample1 {
.backgroundColor(0x66bbb2cb)
}
.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() {
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)
}
}
}
}
```
......@@ -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)
......@@ -17,7 +17,7 @@ The location attributes set the alignment mode, layout direction, and position o
| position | [Position](ts-types.md#position8) | Offset of the component's upper left corner relative to the parent component's upper left corner. This offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.|
| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The upper left corner of the component is used as the reference point for offset. Generally, this attribute is used together with the **position** and **offset** attributes. When used independently, this attribute is similar to **offset**.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>} |
| offset | [Position](ts-types.md#position8) | Offset of the component relative to itself. This offset is expressed using relative values. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.<br>Default value:<br>{<br>x: 0,<br>y: 0<br>} |
| alignRules<sup>9+</sup> | {<br>left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };<br>bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };<br>center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }<br>} | Alignment rules relative to the container.<br>- **left**: left-aligned.<br>- **right**: right-aligned.<br>- **middle**: center-aligned.<br>- **top**: top-aligned.<br>- **bottom**: bottom-aligned.<br>- **center**: center-aligned.<br>**NOTE**<br>- **anchor**: ID of the component that functions as the anchor point.<br>- **align**: alignment mode relative to the anchor component.|
| alignRules<sup>9+</sup> | {<br>left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };<br>top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };<br>bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };<br>center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }<br>} | Alignment rules relative to the container. This attribute is valid only when the container is [\<RelativeContainer>](ts-container-relativecontainer.md).<br>- **left**: left-aligned.<br>- **right**: right-aligned.<br>- **middle**: center-aligned.<br>- **top**: top-aligned.<br>- **bottom**: bottom-aligned.<br>- **center**: center-aligned.<br>**NOTE**<br>- **anchor**: ID of the component that functions as the anchor point.<br>- **align**: alignment mode relative to the anchor component.|
## Example
......@@ -46,7 +46,7 @@ struct PositionExample1 {
.fontSize(16)
.backgroundColor(0xFFE4C4)
// To arrange the child components from left to right, set direction of the parent container to Direction.Auto or Direction.Ltr, or leave it to the default value.
// To arrange the child components from left to right, set direction of the parent container to Direction.Ltr.
Text('direction').fontSize(9).fontColor(0xCCCCCC).width('90%')
Row() {
Text('1').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3)
......@@ -55,19 +55,19 @@ struct PositionExample1 {
Text('4').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C)
}
.width('90%')
.direction(Direction.Auto)
.direction(Direction.Ltr)
// To arrange the child components from right to left, set direction of the parent container to Direction.Rtl.
Row() {
Text('1').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3)
Text('2').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C)
Text('3').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3)
Text('4').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C)
Text('1').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3).textAlign(TextAlign.End)
Text('2').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C).textAlign(TextAlign.End)
Text('3').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3).textAlign(TextAlign.End)
Text('4').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C).textAlign(TextAlign.End)
}
.width('90%')
.direction(Direction.Rtl)
}
}
.width('100%').margin({ top: 5 }).direction(Direction.Rtl)
.width('100%').margin({ top: 5 })
}
}
```
......
......@@ -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)
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(() => {
router.push({ uri: 'pages/details' })
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
......
......@@ -10,14 +10,14 @@ The **restoreId** attribute identifies a component in distributed migration scen
| Name| Type| Description|
| -------- | -------- | -------- |
| restoreId | number | ID of the component used for matching during distributed migration. This ID must be unique within an application.|
| restoreId | number | ID of the component used for device matching during distributed migration. This ID must be unique within an application.|
## Components with Distributed Migration Support
| Name| Initial Version| Migration Status|
| Name| Initial API Version| Migration Status|
| -------- | -------- | -------- |
| List | 8 | The sequence number of the item displayed on the top of the current device will be migrated to the remote device. After the migration, the item is completely displayed on the top of the remote device.|
| Grid | 9 | The sequence number of the item displayed on the top of the current device will be migrated to the remote device. After the migration, the item is completely displayed on the top of the remote device. The position of the scrollbar cannot be migrated.|
| List | 8 | The index of the list item displayed at the top of the list on the current device will be migrated to the remote device. After the migration, the list item that matches the index is displayed at the top of the list on the remote device.|
| Grid | 9 | The index of the grid item displayed at the top of the grid on the current device will be migrated to the remote device. After the migration, the grid item that matches the index is displayed at the top of the grid on the remote device. The position of the scrollbar cannot be migrated.|
| Scroll | 9 | The absolute distance with the top edge for scrolling will be migrated. Due to layout inconsistency resulting from differences in the display specifications between devices, the migration effect may be affected.|
| TextArea | 9 | The text content and the position of the caret will be migrated.|
| TextInput | 9 | The text content and the position of the caret will be migrated.|
......@@ -39,7 +39,6 @@ struct RestoreIdExample {
.width('100%')
.height(100)
.fontSize(16)
.fontColor(0xFFFFFF)
.textAlign(TextAlign.Center)
.borderRadius(10)
.backgroundColor(Color.Pink)
......
......@@ -12,8 +12,8 @@ Shape clipping changes the visible portion of a component through clipping or ma
| Name | Type | Description |
| -----| ------------------------------------------ | ------------------------------------ |
| clip | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) \| boolean | Specifies a clip mode. The value **Shape** indicates that the current component is cropped based on the specified shape. The value **boolean** specifies whether to clip the component based on the edge outline.<br>Default value: **false**|
| mask | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) | Adds a mask of the specified shape to the current component.|
| clip | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) \| boolean | Clip mode. If the value is a shape, the component is clipped based on the specified shape. If the value is of the Boolean type, it specifies whether to clip the component based on the edge outline of the parent container.<br>Default value: **false**|
| mask | [Circle](ts-drawing-components-circle.md) \| [Ellipse](ts-drawing-components-ellipse.md) \| [Path](ts-drawing-components-path.md) \| [Rect](ts-drawing-components-rect.md) | Mask of the specified shape to add to the component.|
## Example
......@@ -24,34 +24,33 @@ Shape clipping changes the visible portion of a component through clipping or ma
@Component
struct ClipAndMaskExample {
build() {
Column({ space: 5 }) {
Text('clip').fontSize(9).width('90%').fontColor(0xCCCCCC)
// Clip the image by using a circle with a diameter of 280px.
Image($r('app.media.example'))
.clip(new Circle({ width: 80, height: 80 }))
.width('500px').height('280px')
Column({ space: 15 }) {
Text('clip').fontSize(12).width('75%').fontColor('#DCDCDC')
Row() {
Image($r('app.media.example')).width('500px').height('280px')
Image($r('app.media.testImg')).width('500px').height('280px')
}
.clip(true)
.clip(true) // If clip is not set to true, the image is not confined by the rounded corners of the <Row> component and may extend beyond the <Row> component.
.borderRadius(20)
// Clip the image based on a circle with a diameter of 280 px.
Image($r('app.media.testImg'))
.clip(new Circle({ width: '280px', height: '280px' }))
.width('500px').height('280px')
Text('mask').fontSize(9).width('90%').fontColor(0xCCCCCC)
// Add a 500 px x 280 px mask to the image.
Image($r('app.media.example'))
Text('mask').fontSize(12).width('75%').fontColor('#DCDCDC')
// Add a 500 px x 280 px square mask to the image.
Image($r('app.media.testImg'))
.mask(new Rect({ width: '500px', height: '280px' }).fill(Color.Gray))
.width('500px').height('280px')
// Add a 280 px x 280 px circle mask to the image.
Image($r('app.media.example'))
// Add a 280 px x 280 px circular mask to the image.
Image($r('app.media.testImg'))
.mask(new Circle({ width: '280px', height: '280px' }).fill(Color.Gray))
.width('500px').height('281px')
.width('500px').height('280px')
}
.width('100%')
.margin({ top: 5 })
.margin({ top: 15 })
}
}
```
![en-us_image_0000001212218452](figures/en-us_image_0000001212218452.png)
![clipAndMask](figures/clipAndMask.PNG)
......@@ -17,7 +17,7 @@ The size attributes set the width, height, and margin of a component.
| size | {<br>width?: [Length](ts-types.md#length),<br>height?: [Length](ts-types.md#length)<br>} | Size of the component. |
| padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | Padding of the component.<br>When the parameter is of the **Length** type, the four paddings take effect.<br>Default value: **0**<br>When **padding** is set to a percentage, the width of the parent container is used as the basic value.|
| margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | Margin of the component.<br>When the parameter is of the **Length** type, the four margins take effect.<br>Default value: **0**<br>When **margin** is set to a percentage, the width of the parent container is used as the basic value.|
| constraintSize | {<br>minWidth?: [Length](ts-types.md#length),<br>maxWidth?: [Length](ts-types.md#length),<br>minHeight?: [Length](ts-types.md#length),<br>maxHeight?: [Length](ts-types.md#length)<br>} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**.<br>Default value:<br>{<br>minWidth: 0,<br>maxWidth: Infinity,<br>minHeight: 0,<br>maxHeight: Infinity<br>} |
| constraintSize | {<br>minWidth?: [Length](ts-types.md#length),<br>maxWidth?: [Length](ts-types.md#length),<br>minHeight?: [Length](ts-types.md#length),<br>maxHeight?: [Length](ts-types.md#length)<br>} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**. If the value of **minWidth** is greater than that of **maxWidth**, only the value of **minWidth** takes effect. The same rule applies to **minHeight** and **maxHeight**.<br>Default value:<br>{<br>minWidth: 0,<br>maxWidth: Infinity,<br>minHeight: 0,<br>maxHeight: Infinity<br>} |
| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.<br>**NOTE**<br>This attribute is valid only for the **\<Row>**, **\<Column>**, and **\<Flex>** layouts.|
......
......@@ -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)
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'
})
}.width('100%').margin({ top: 5 })
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)
......@@ -42,4 +42,4 @@ struct AreaExample {
}
```
![en-us_image_0000001257058403](figures/en-us_image_0000001257058403.gif)
![en-us_image_0000001189634870](figures/en-us_image_0000001189634870.gif)
\ No newline at end of file
......@@ -9,11 +9,11 @@ A drag event is triggered when a component is dragged.
## Events
| Name | Bubbling Supported| Description |
| ---------------------------------------- | ---- | ---------------------------------------- |
| onDragStart(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; [CustomBuilder](ts-types.md#custombuilder8) \| [DragItemInfo](#dragiteminfo) | No | Triggered when the component bound to the event is dragged for the first time.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>Return value: object being dragged, which is used for prompts displayed when the object is dragged.<br>A drag event can be triggered by a 150 ms long press. If the duration of a long-press gesture is set to less than or equal to 150 ms, the callback for the long-press gesture takes precedence. Otherwise, the callback for the drag event takes precedence.|
| ------------------------------------------------------------ | -------- | ------------------------------------------------------------ |
| onDragStart(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; [CustomBuilder](ts-types.md#custombuilder8) \| [DragItemInfo](#dragiteminfo)) | No | Triggered when the component bound to the event is dragged for the first time.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>Return value: object being dragged, which is used for prompts displayed when the object is dragged.<br>A drag event can be triggered by a 150 ms long press. If the duration of a long-press gesture is set to less than or equal to 150 ms, the callback for the long-press gesture takes precedence. Otherwise, the callback for the drag event takes precedence.|
| onDragEnter(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item enters a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when the **onDrop** event is listened to.|
| onDragMove(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item moves in a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when the **onDrop** event is listened to.|
| onDragLeave(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item leaves a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when the **onDrop** event is listened to.|
| onDragLeave(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item leaves a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.<br>This event is valid only when a listener for the **onDrop** event is enabled.|
| onDrop(event: (event?: [DragEvent](#dragevent), extraParams?: string) =&gt; void) | No | Triggered when the dragged item is dropped on a valid drop target.<br>- **event**: information about the drag event, including the coordinates of the item that is being dragged.<br>- **extraParams**: additional information about the drag event. For details, see **[extraParams](#extraparams)**.|
## DragItemInfo
......@@ -27,9 +27,9 @@ A drag event is triggered when a component is dragged.
## extraParams
Provides additional information required for dragging an item.
Provides additional information required for dragging an item.
**extraParams** is a string converted from a JSON object. You can obtain the following attributes using the JSON object converted from **Json.parse**.
**extraParams** is a string converted from a JSON object. You can obtain the following attributes using the JSON object converted from **Json.parse**.
| Name | Type | Description |
| ------------- | ------ | ---------------------------------------- |
......@@ -47,15 +47,27 @@ Provides additional information required for dragging an item.
```ts
// xxx.ets
@Extend(Text) function textStyle () {
.width('25%')
.height(35)
.fontSize(16)
.textAlign(TextAlign.Center)
.backgroundColor(0xAFEEEE)
}
@Entry
@Component
struct DragExample {
@State numbers: string[] = ['one', 'two', 'three', 'four', 'five', 'six']
@State text: string = ''
@State bool: boolean = false
@State bool: boolean = true
@State eventType: string = ''
@State appleVisible: Visibility = Visibility.Visible
@State orangeVisible: Visibility = Visibility.Visible
@State bananaVisible: Visibility = Visibility.Visible
private dragList: string[] = ['apple', 'orange', 'banana']
@State fruitVisible: Visibility[] = [Visibility.Visible, Visibility.Visible, Visibility.Visible]
@State index: number = 0
// Customize the content displayed during dragging.
@Builder pixelMapBuilder() {
......@@ -79,45 +91,28 @@ struct DragExample {
.textAlign(TextAlign.Start)
.margin(5)
Row({ space: 15 }) {
Text('apple')
.width('25%')
.height(35)
.fontSize(16)
.textAlign(TextAlign.Center)
.backgroundColor(0xAFEEEE)
.visibility(this.appleVisible)
ForEach(this.dragList, (item, index) => {
Text(item)
.textStyle()
.visibility(this.fruitVisible[index])
.onDragStart(() => {
this.bool = true
this.text = 'apple'
this.appleVisible = Visibility.None
this.text = item
this.fruitVisible[index] = Visibility.None
return this.pixelMapBuilder
})
Text('orange')
.width('25%')
.height(35)
.fontSize(16)
.textAlign(TextAlign.Center)
.backgroundColor(0xAFEEEE)
.visibility(this.orangeVisible)
.onDragStart(() => {
this.bool = true
this.text = 'orange'
this.orangeVisible = Visibility.None
return this.pixelMapBuilder
.onTouch((event: TouchEvent) => {
if (event.type === TouchType.Down) {
this.eventType = 'Down'
this.index = index
}
if (event.type === TouchType.Up) {
this.eventType = 'Up'
if (this.bool) {
this.fruitVisible[index] = Visibility.Visible
}
}
})
Text('banana')
.width('25%')
.height(35)
.fontSize(16)
.textAlign(TextAlign.Center)
.backgroundColor(0xAFEEEE)
.visibility(this.bananaVisible)
.onDragStart((event: DragEvent, extraParams: string) => {
console.log('Text onDragStart, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY())
this.bool = true
this.text = 'banana'
this.bananaVisible = Visibility.None
return this.pixelMapBuilder
})
}.padding({ top: 10, bottom: 10 }).margin(10)
......@@ -156,12 +151,13 @@ struct DragExample {
console.log('List onDragLeave, ' + extraParams + 'X:' + event.getX() + 'Y:' + event.getY())
})
.onDrop((event: DragEvent, extraParams: string) => {
var jsonString = JSON.parse(extraParams);
let jsonString = JSON.parse(extraParams);
if (this.bool) {
// Insert an element using the splice method.
this.numbers.splice(jsonString.insertIndex, 0, this.text)
this.bool = false
}
this.fruitVisible[this.index] = Visibility.None
})
}.width('100%').height('100%').padding({ top: 20 }).margin({ top: 20 })
}
......
......@@ -12,14 +12,14 @@ The show/hide event is triggered when a component is mounted or unmounted from t
| Name | Bubbling Supported| Description |
| ------------------------------------------------ | -------- | -------------------------- |
| onAppear(event: () =&gt; void) | No | Triggered when the component is displayed.|
| onDisappear(event: () =&gt; void) | No | Triggered when the component is hidden. |
| onDisAppear(event: () =&gt; void) | No | Triggered when the component is hidden.|
## Example
```ts
// xxx.ets
import prompt from '@ohos.prompt'
import promptAction from '@ohos.promptAction'
@Entry
@Component
......@@ -38,14 +38,14 @@ struct AppearExample {
Text(this.myText).fontSize(26).fontWeight(FontWeight.Bold)
.onAppear(() => {
this.changeAppear = 'Hide Text'
prompt.showToast({
promptAction.showToast({
message: 'The text is shown',
duration: 2000
})
})
.onDisAppear(() => {
this.changeAppear = 'Show Text'
prompt.showToast({
promptAction.showToast({
message: 'The text is hidden',
duration: 2000
})
......
# 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
......@@ -15,10 +18,6 @@ A focus event is triggered when the page focus moves between components. It can
| 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)
# Error Codes
- [Universal Error Codes](errorcode-universal.md)
- Ability Framework
- [Ability Error Codes](errorcode-ability.md)
- [Distributed Scheduler Error Codes](errorcode-DistributedSchedule.md)
- [Form Error Codes](errorcode-form.md)
- Bundle Management
- [Bundle Error Codes](errorcode-bundle.md)
- [zlib Error Codes](errorcode-zlib.md)
- Common Event and Notification
- [Event Error Codes](errorcode-CommonEventService.md)
- [DistributedNotificationService Error Codes](errorcode-DistributedNotificationService.md)
- UI Page
- [Animator Error Codes](errorcode-animator.md)
- [promptAction Error Codes](errorcode-promptAction.md)
- [Router Error Codes](errorcode-router.md)
- Graphics
- [colorSpaceManager Error Codes](errorcode-colorspace-manager.md)
- [Display Error Codes](errorcode-display.md)
- [Window Error Codes](errorcode-window.md)
- Media
- [Audio Error Codes](errorcode-audio.md)
- [Media Error Codes](errorcode-media.md)
- [AVSession Management Error Codes](errorcode-avsession.md)
- Resource Management
- [I18N Error Codes](errorcode-i18n.md)
- [Resource Manager Error Codes](errorcode-resource-manager.md)
- Resource Scheduling
- [backgroundTaskManager Error Codes](errorcode-backgroundTaskMgr.md)
- [reminderAgentManager Error Codes](errorcode-reminderAgentManager.md)
- [workScheduler Error Codes](errorcode-workScheduler.md)
- Security
- [Ability Access Control Error Codes](errorcode-access-token.md)
- [HUKS Error Codes](errorcode-huks.md)
- [User Authentication Error Codes](errorcode-useriam.md)
- Data Management
- [RDB Error Codes](errorcode-data-rdb.md)
- [DataShare Error Codes](errorcode-datashare.md)
- [Distributed Data Object Error Codes](errorcode-distributed-dataObject.md)
- [Distributed KV Store Error Codes](errorcode-distributedKVStore.md)
- [Preferences Error Codes](errorcode-preferences.md)
- File Management
- [File Management Error Codes](errorcode-filemanagement.md)
- Network Management
- [Upload and Download Error Codes](errorcode-request.md)
- Connectivity
- [NFC Error Codes](errorcode-nfc.md)
- [RPC Error Codes](errorcode-rpc.md)
- Basic Features
- [Accessibility Error Codes](errorcode-accessibility.md)
- [FaultLogger Error Codes](errorcode-faultlogger.md)
- [Application Event Logging Error Codes](errorcode-hiappevent.md)
- [HiSysEvent Error Codes](errorcode-hisysevent.md)
- [HiDebug Error Codes](errorcode-hiviewdfx-hidebug.md)
- [Input Method Framework Error Codes](errorcode-inputmethod-framework.md)
- [Pasteboard Error Codes](errorcode-pasteboard.md)
- [Webview Error Codes](errorcode-webview.md)
- Account Management
- [Account Error Codes](errorcode-account.md)
- [App Account Error Codes](errorcode-app-account.md)
- Device Management
- [Power Consumption Statistics Error Codes](errorcode-batteryStatistics.md)
- [Brightness Error Codes](errorcode-brightness.md)
- [Power Manager Error Codes](errorcode-power.md)
- [Running Lock Error Codes](errorcode-runninglock.md)
- [Thermal Manager Error Codes](errorcode-thermal.md)
- [Device Management Error Codes](errorcode-device-manager.md)
- [Location Subsystem Error Codes](errorcode-geoLocationManager.md)
- [Screen Hopping Error Codes](errorcode-multimodalinput.md)
- [Sensor Error Codes](errorcode-sensor.md)
- [Vibrator Error Codes](errorcode-vibrator.md)
- [System Parameter Error Codes](errorcode-system-parameterV9.md)
- [USB Error Codes](errorcode-usb.md)
- [Update Error Codes](errorcode-update.md)
- [DeviceUsageStatistics Error Codes](errorcode-DeviceUsageStatistics.md)
- Customization Management
- [Enterprise Device Management Error Codes](errorcode-enterpriseDeviceManager.md)
- Language Base Class Library
- [Utils Error Codes](errorcode-utils.md)
- Test
- [UiTest Error Codes](errorcode-uitest.md)
# Event Error Codes
## 1500001 Want Action Is Null
**Error Message**
Want action is null
**Description**
This error code is reported when the **Action** attribute in the **want** is null for the event to send.
**Possible Causes**
The **Action** attribute in the **want** is null for the event to send.
**Solution**
Make sure the **Action** attribute in the **want** is not null.
## 1500002 Failed to Send Common Events from a Sandbox Application
**Error Message**
sandbox application can not send common event
**Description**
This error code is reported when an attempt is made to send a common event from a sandbox application.
**Possible Causes**
Common events from a sandbox application are blocked.
**Solution**
Check whether the application used to send a common event is a sandbox application. If so, switch to another application.
## 1500003 Event Sending Frequency Is Too High
**Error Message**
common event send frequency too high
**Description**
This error code is reported when the application sends common events too frequently.
**Possible Causes**
The number of common events sent by the application in a given time frame has reached the maximum.
**Solution**
Do not send common events too frequently.
## 1500004 Failed to Send System Common Events
**Error Message**
not System services or System app
**Description**
This error code is reported when the application cannot send system common events.
**Possible Causes**
The application is not a system application or system service.
**Solution**
Make sure the application to send system common events is a system application or system service.
## 1500005 Subscriber Not Found
**Error Message**
subscriber can not found
**Description**
This error code is reported when the subscriber cannot be found.
**Possible Causes**
The subscriber is deleted.
**Solution**
Check whether the subscription has already been canceled. If the subscription has been canceled, the subscriber is deleted.
## 1500006 Invalid User ID
**Error Message**
usreId is invalid
**Description**
This error code is reported when the user ID is invalid.
**Possible Causes**
The user ID is different from the system user ID, or the application is not a system application or subsystem process.
**Solution**
Check whether the current user ID is the same as the system user ID. If they are different, check whether the application is a system application or subsystem process
## 1500007 Failed to Send a Request Through IPC
**Error Message**
message send error
**Description**
This error code is reported when the attempt to send a request through IPC fails.
**Possible Causes**
The connection object fails to be created.
**Solution**
Do not set up connections frequently. Try again later.
## 1500008 Failed to Read Data
**Error Message**
CEMS error
**Description**
This error code is reported when an error occurs on the server.
**Possible Causes**
A service exception occurs when the server processes data.
**Solution**
Try again later.
## 1500009 System Error
**Error Message**
system error
**Description**
This error code is reported when an exception occurs in the system during service processing, for example, when the current system time fails to be obtained.
**Possible Causes**
A system fault occurs.
**Solution**
Try again later.
# DistributedNotificationService Error Codes
## 1600001 Internal Error
**Error Message**
Internal Error.
**Description**
This error code is reported when an internal processing error occurs, such as a memory allocation or multi-thread processing error.
**Possible Causes**
1. Common kernel errors such as memory allocation and multi-thread processing errors occur.
**Solution**
1. Ensure sufficient system memory.
2. Restart the system.
## 1600002 Data Processing or Interaction Error Between the Application and Notification Subsystem
**Error Message**
IPC Error.
**Description**
This error code is reported when a serialization or deserialization error occurs and the interaction with the notification subsystem fails.
**Possible Causes**
1. A serialization and deserialization error occurs.
2. The interaction with the notification subsystem fails.
**Solution**
1. Make sure the input parameter value is within the valid range.
2. Make sure the notification subsystem is not being started.
## 1600003 Failed to Connect to the Service
**Error Message**
Failed to connect to service.
**Description**
This error code is reported when the notification subsystem is abnormal due to a service connection failure.
**Possible Causes**
The service is busy or the notification subsystem is not working correctly.
**Solution**
1. Try again later.
2. Make sure the notification subsystem is started.
## 1600004 Notification Is Disabled
**Error Message**
Notification is not enabled.
**Description**
This error code is reported when the notification function is disabled.
**Possible Causes**
The notification function is set to its default state (default) or manually disabled.
**Solution**
Enable the notification function.
## 1600005 Notification Slot Is Disabled
**Error Message**
Notification slot is not enabled.
**Description**
This error code is reported when the notification slot is disabled.
**Possible Causes**
The notification slot is disabled.
**Solution**
Make sure the application notification slot is enabled.
## 1600006 Unable to Remove the Notification
**Error Message**
Notification is not allowed to remove.
**Description**
This error code is reported when **isUnremoveable** is set to **true** and an attempt is made to remove all notifications or when **isRemoveAllowed** is set to **false** and an attempt is made to remove a specific notification.
**Possible Causes**
1. When **isUnremoveable** is set to **true**, notifications can only be removed on a one-by-one basis.
2. When **isRemoveAllowed** is set to **false**, no notification can be deleted.
**Solution**
1. Check whether **unremovable** is set to **true**.
2. Check whether **isRemoveAllowed** is set to **false**.
## 1600007 Notification Not Found
**Error Message**
The notification is not exist.
**Description**
This error code is reported when the target notification is not found.
**Possible Causes**
1. The notification has been deleted.
2. The notification has been canceled.
**Solution**
Make sure the notification exists.
## 1600008 User Not Found
**Error Message**
The user is not exist.
**Description**
This error code is reported when the target user is not found.
**Possible Causes**
1. The user ID is incorrect.
2. No user account has not been activated.
**Solution**
Make sure the user account with the specified ID has been activated.
## 1600009 Maximum Number of Notifications per Second Reached
**Error Message**
Over max number notifications per second.
**Description**
This error code is reported when the number of notifications sent per second has reached the maximum.
**Possible Causes**
More than 10 notifications are sent per second.
**Solution**
Reduce the number of notifications sent per second to 10 or less.
## 1600010 Distributed Processing Error
**Error Message**
Distributed operation failed.
**Description**
This error code is reported when a database processing error occurs or the database operations are too frequent.
**Possible Causes**
1. A database processing error occurs.
2. The database operations are too frequent.
**Solution**
1. Make sure the distributed data is running properly.
2. Reduce the database operation frequency.
## 1600011 Failed to read the Template Configuration File
**Error Message**
Read template config failed.
**Description**
This error code is reported when the template configuration file fails to be read.
**Possible Causes**
1. The template configuration file is lost.
2. The current template version is not supported.
**Solution**
1. Check for the **/system/etc/notification_template/external.json** file.
2. Update the version to 3.2 or later.
## 17700001 Bundle Name Not Found
**Error Message**
The specified bundle name was not found.
**Description**
This error code is reported when the specified bund name is not found.
**Possible Causes**
1. The bundle name is incorrect.
2. The application is not installed.
**Solution**
1. Verify the bundle name.
2. Make sure the application has been installed.
# Accessibility Error Codes
## 9300001 Invalid Bundle Name or Ability Name
**Error Message**
Invalid bundle name or ability name.
**Description**
This error code is reported when the entered bundle name or ability name is invalid.
**Possible Causes**
1. The bundle name does not exist.
2. The bundle does not contain the target ability.
**Solution**
1. Verify the bundle name.
2. Check whether the ability name corresponding to the bundle name is correct.
## 9300002 Target Ability Already Enabled
**Error Message**
Target ability already enabled.
**Description**
This error code is reported when the target ability is already enabled.
**Possible Causes**
The target ability is already enabled and cannot be enabled again.
**Solution**
1. Stop the target Ability.
2. Re-enable the target ability.
## 9300003 No Accessibility Permission to Perform the Operation
**Error Message**
Do not have accessibility right for this operation.
**Description**
This error code is reported when an application performs an accessibility operation for which the related permission has not been granted.
**Possible Causes**
The permission for performing the accessibility operation is not granted when the accessibility application is enabled.
**Solution**
1. Request from the user the permission for performing the accessibility operation, stating the reason for the request.
2. Have the accessibility application re-enabled and the required accessibility operation enabled.
## 9300004 Attribute Not Found
**Error Message**
This property does not exist.
**Description**
This error code is reported when the entered attribute of the accessibility element does not exist.
**Possible Causes**
The attribute does not exist in the accessibility element.
**Solution**
Make sure the accessibility element has the target attribute.
## 9300005 Operation Not Supported
**Error Message**
This action is not supported.
**Description**
This error code is reported when the application performs an operation that is not supported by the accessibility element.
**Possible Causes**
The accessibility element does not support the target operation.
**Solution**
Make sure the operation is included in the list of operations supported by the accessibility element.
# Animator Error Codes
## 100001 Internal Error
**Error Message**
Internal error.
**Description**
This error code is reported when an internal error that cannot be rectified by developers occurs. The internal error type is included in the error information.
**Possible Causes**
The operation for obtaining the rendering engine or parsing parameters fails.
**Solution**
N/A
......@@ -4,7 +4,7 @@
**Error Message**
invalid parameter.
Invalid parameter.
**Description**
......@@ -22,7 +22,7 @@ Pass the correct parameters in the API.
**Error Message**
allocate memory failed.
Memory allocation failure.
**Description**
......@@ -42,7 +42,7 @@ When the API is called, the memory fails to be allocated or a null pointer occur
**Error Message**
Operation not permit at current state.
Unsupported state.
**Description**
......@@ -61,7 +61,7 @@ The operation is not supported in the current state. For example, data is played
**Error Message**
unsupported operation.
Unsupported parameter value.
**Description**
......@@ -80,7 +80,7 @@ The value of the input parameter is not within the range supported.
**Error Message**
time out.
Processing timeout.
**Description**
......@@ -98,7 +98,7 @@ Control the time of the write operation, for example, adding delayed processing.
**Error Message**
stream number limited.
Too many audio streams.
**Description**
......@@ -116,7 +116,7 @@ Release audio streams that are no longer used.
**Error Message**
system error.
System error.
**Description**
......
......@@ -4,7 +4,7 @@
**Error Message**
Session service exception
Session service exception.
**Description**
......@@ -24,7 +24,7 @@ The session service is killed during session restart.
**Error Message**
The session does not exist
The session does not exist.
**Description**
......@@ -44,7 +44,7 @@ The session has been destroyed, and no session record exists on the server.
**Error Message**
The session controller does not exist
The session controller does not exist.
**Description**
......@@ -62,7 +62,7 @@ Query the session record and create the corresponding controller.
**Error Message**
The remote session connection failed
The remote session connection failed.
**Description**
......@@ -80,7 +80,7 @@ Stop sending control commands to the session. Subscribe to output device changes
**Error Message**
Invalid session command
Invalid session command.
**Description**
......@@ -98,7 +98,7 @@ Stop sending the command or event. Query the commands supported by the session,
**Error Message**
The session not active
The session is not activated.
**Description**
......@@ -116,7 +116,7 @@ Stop sending the command or event. Subscribe to the session activation status, a
**Error Message**
Command or event overload
Too many commands or events.
**Description**
......
# Power Consumption Statistics Error Codes
## 4600101 Service Connection Failure
**Error Message**
Operation failed. Cannot connect to service.
**Description**
This error code is reported for a service connection failure.
**Possible Causes**
1. The system service stops running.
2. The internal communication of system services is abnormal.
**Solution**
Check whether the system services are running properly.
1. Run the following command on the console to view the current system service list:
```bash
> hdc shell hidumper -ls
```
2. Check whether **BatteryStatisticsService** is included in the system service list.
# Brightness Error Codes
## 4700101 Service Connection Failure
**Error Message**
Operation failed. Cannot connect to service.
**Description**
This error code is reported for a service connection failure.
**Possible Causes**
1. The system service stops running.
2. The internal communication of system services is abnormal.
**Solution**
Check whether the system services are running properly.
1. Run the following command on the console to view the current system service list:
```bash
> hdc shell hidumper -ls
```
2. Check whether **DisplayPowerManagerService** is included in the system service list.
# containers Error Codes
## 10200012 Constructor Calling Failure
**Error Message**
The {className}'s constructor cannot be directly invoked.
**Description**
A constructor of the **containers** class is called directly to create an instance.
**Possible Causes**
The constructors of the **containers** class cannot be directly called. The keyword **new** must be used.
**Solution**
Use the keyword **new** to create an instance.
## 10200011 Passed this object Is Not an Instance of the containers Class
**Error Message**
The {methodName} method cannot be bound.
**Description**
**this object** passed in the API is not an instance of the **containers** class.
**Possible Causes**
The APIs of the **containers** class do not support **bind()**.
**Solution**
1. Check whether **bind()** is used to call the API.
2. Check whether an object that is not a container instance is assigned to the API.
## 10200001 Invalid Parameter Value
**Error Message**
The value of parameters are out of range.
**Description**
The value of a parameter passed in the API exceeds the valid range.
**Possible Causes**
The parameter value is out of range.
**Solution**
Use a value within the range.
## 10200010 Empty Container
**Error Message**
Container is empty.
**Description**
The container to be operated is empty.
**Possible Causes**
The container is empty.
**Solution**
Add elements to the container first.
# DataShare Error Codes
## 15700010 Failed to Create a DataShareHelper
**Error Message**
The dataShareHelper is not initialized successfully.
**Description**
The **DataShareHelper** class fails to be created.
**Possible Causes**
1. The **uri** specified in **createDataHelper** is incorrect.
2. The **context** specified in **createDataHelper** is incorrect. **DataShare** supports only the stage model.
**Solution**
1. Obtain the correct URI.
2. Check that the context of the stage model is used.
......@@ -26,7 +26,7 @@ The service is not started or fails to start.
**Solution**
Check whether the service is started normally and obtain the service again.
Make sure the service is started and obtain the service again.
## 11600103 Authentication Unavailable
......@@ -38,7 +38,7 @@ Authentication invalid.
The last authentication service is still in progress.
**Procedure**
**Solution**
Wait until the last authentication service is complete and call the authentication API again.
......
# Distributed Data Object Error Codes
## 15400001 Failed to Create the In-Memory Database
**Error Message**
Create table failed.
**Description**
The in-memory database fails to be created.
**Possible Causes**
An object with the same session ID already exists.
**Solution**
Check for the object has been added to the same session.
# Distributed KV Store Error Codes
## 15100001 Subscription Count Reaches the Limit
**Error Message**
Over max subscribe limits.
**Description**
The number of subscriptions has reached the limit for **on('dataChange')**.
**Possible Causes**
The number of subscriptions has reached the limit for **on('dataChange')**.
**Solution**
Unregister unnecessary subscriptions and try again.
## 15100002 Parameter Configuration Changes
**Error Message**
Open existed database with changed options.
**Description**
The **options** configuration changes when **getKVStore()** is called to obtain a KV store.
**Possible Causes**
The possible causes are as follows:
1. An existing **storeId** is used to create a KV store.
2. You want to change the **options** parameter of a KV store.
**Solution**
1. When creating a KV store, do not use a duplicate **storeId**.
2. Currently, the **options** parameter of a KV store cannot be changed. To apply the change, delete the KV store and create a KV store with the required **options** settings.
## 15100003 KV Store Corrupted
**Error Message**
Database corrupted.
**Description**
The target KV store is corrupted.
**Possible Causes**
The target KV store is corrupted.
**Solution**
1. Restore the KV store from a backup file.
2. If no backup file is available, delete the corrupted KV store and create a new one.
## 15100004 Failed to Find Data
**Error Message**
Not found.
**Description**
Related data is found when **deleteKVStore()**, **delete()**, **deleteBatch()**, or **get()** is called.
**Possible Causes**
The possible causes are as follows:
1. The KV store to delete does not exist or has been deleted.
2. The data queried does not exist or has been deleted.
3. The data to delete does not exist or has been deleted.
**Solution**
1. Before deleting a KV store, check that the KV store exists.
2. When querying data in a KV store, check whether the query keywords are correct.
3. When deleting data from a KV store, check that the keyword for the deletion is correct and the data to delete exists.
## 15100005 KV Store or Result Set Closed
**Error Message**
Database or result set already closed.
**Description**
The KV store or result set to operate is already closed.
**Possible Causes**
The KV store or result set is closed manually before the operation.
**Solution**
1. Obtain the KV store and try again.
2. Obtain the result set and try again.
# Enterprise Device Management Error Codes
## 9200001 Application Not a Device Administrator
**Error Message**
The application is not a administrator of the device.
**Description**
This error code is reported when the calling application is not an administrator of the device.
**Possible Causes**
The calling application has not been enabled as an administrator of the device.
**Solution**
Make sure the application is enabled as an administrator of the device.
## 9200002 Insufficient Permission for Systsm Administration
**Error Message**
The administrator application does not have permission to manage the device.
**Description**
This error code is reported when the API requires a permission level higher than that granted to the calling application.
**Possible Causes**
The application is a device administrator application, and the called API is restricted to a device super administrator application.
**Solution**
Make sure the enabled device administrator type is the same as that required by the called API.
## 9200003 Invalid Administrator Ability Component
**Error Message**
The administrator ability component is invalid.
**Description**
This error code is reported when the administrator ability component specified in the input parameters is invalid.
**Possible Causes**
The specified administrator ability component is invalid due to any of the following:
1. The administrator ability component does not exist when the application is enabled as a device administrator application.
2. The administrator ability component is not valid in an enterprise setting.
**Solution**
1. Make sure the name of the device administrator ability component is included in the application bundle when the application is enabled as a device administrator application.
2. Make sure the administrator ability component inherits the **EnterpriseAdminExtensionAbility** component defined by the enterprise device administrator framework.
## 9200004 Failed to Enable the Device Administrator Application
**Error Message**
Failed to activate the administrator application of the device.
**Description**
This error code is reported when the application fails to be enabled as a device administrator application.
**Possible Causes**
1. Multiple applications are enabled as super device administrators (SDAs).
2. The application has been enabled as a device administrator, and the device administrator type has changed.
3. Multiple device administrator ability components of the same application are enabled.
**Solution**
1. Make sure only one application is enabled as SDA.
2. Check whether the application has been enabled as a device administrator and whether the device administrator type changes when it is enabled again. If this is the case, disable the device administrator and enable it again.
3. Check whether any ability component in the application has been enabled as the device administrator. Only one ability component in an application can be enabled as the device administrator.
## 9200005 Failed to Disable the Device Administrator Application
**Error Message**
Failed to deactivate the administrator application of the device.
**Description**
This error code is reported when the application to disable has not been enabled as a device administrator application or the attempt to disable the device administrator application is made by a device administrator application.
**Possible Causes**
1. The application to disable has not been enabled as a device administrator application.
2. The attempt to disable the device administrator application is made by a device administrator application.
**Solution**
1. Check whether the target application has been enabled as a device administrator application.
2. Check whether the specified ability component in the target application has been enabled as a device administrator.
3. Check whether the attempt to disable the device administrator application is made by a device administrator application.
## 9200006 Invalid User ID
**Error Message**
The specified user ID is invalid.
**Description**
This error code is reported when the application calls an API to set the user policy but the specified user ID does not exist or the specified user ID is different from the caller user ID.
**Possible Causes**
1. The user ID used to set a user policy does not exist.
2. The specified user ID is different from the caller user ID, and the application is not a super device administrator (SDA) application.
**Solution**
1. Make sure the user ID specified in the called API is valid.
2. Check whether the caller user ID and the specified user ID are the same. In non-SDA mode, policies cannot be set across users.
## 9200007 System Service Error
**Error Message**
The system ability work abnormally.
**Description**
This error code is reported when the enterprise device management service is not working correctly.
**Possible Causes**
1. The enterprise device management service is not started properly.
2. The RPC object for enterprise device management cannot be obtained.
3. Other services on which the enterprise device management service depends are not started properly or the RPC object cannot be obtained for them.
4. A system exception occurs during the running of the enterprise device management service.
**Solution**
Try again later or restart the device.
## 9200008 Invalid System Event Subscription
**Error Message**
The specified system events enum is invalid.
**Description**
This error code is reported when the enterprise device management module does not support subscription to the specified event or the specified event is invalid.
**Possible Causes**
The enterprise device management module does not support subscription to the specified event or the specified event is invalid.
**Solution**
Make sure the event to subscribe to is a valid management event supported by the enterprise device management module.
# faultLogger Error Codes
# FaultLogger Error Codes
## 10600001 Service Faulty or Not Started
......
# File Management Error Codes
The error codes of the file management subsystem consist of the following:
- Basic file I/O error codes
- User data management error codes
- User file access error codes
- Spatial statistics error codes
## Basic File I/O Error Codes
### 13900001 Operation Not Permitted
**Error Message**
Operation not permitted
**Possible Causes**
The current operation on the file is not allowed.
**Solution**
Check the permission for the file.
### 13900002 File or Directory Not Exist
**Error Message**
No such file or directory
**Possible Causes**
The file or directory does not exist.
**Solution**
Check whether the file directory exists.
### 13900003 Process Not Exist
**Error Message**
No such process
**Possible Causes**
The process does not exist.
**Solution**
1. Check whether the process is killed unexpectedly.
2. Check whether the service related to the process has started.
### 13900004 System Call Interrupted
**Error Message**
Interrupted system call
**Possible Causes**
The system call is interrupted by another thread.
**Solution**
1. Check the multi-thread code logic.
2. Invoke the system call again.
### 13900005 I/O Error
**Error Message**
I/O error
**Possible Causes**
The I/O request is invalid.
**Solution**
Initiate the I/O request again.
### 13900006 Device or Address Not Exist
**Error Message**
No such device or address
**Possible Causes**
The device information or address is incorrect.
**Solution**
Check that the device information or address is correct.
### 13900007 Long Parameter List
**Error Message**
Arg list too long
**Possible Causes**
The parameter list is too long.
**Solution**
Reduce the number of parameters.
### 13900008 Invalid File Descriptor
**Error Message**
Bad file descriptor
**Possible Causes**
This file descriptor is closed.
**Solution**
Check whether the file descriptor is closed.
### 13900009 Child Process Not Exist
**Error Message**
No child processes
**Possible Causes**
The child process cannot be created.
**Solution**
Check the maximum number of processes in the system.
### 13900010 Resource Unavailable
**Error Message**
Try again
**Possible Causes**
The resources are blocked.
**Solution**
Request resources.
### 13900011 Memory Overflow
**Error Message**
Out of memory
**Possible Causes**
A memory overflow occurs.
**Solution**
1. Check the memory overhead.
2. Control the memory overhead.
### 13900012 Permission Denied
**Error Message**
Permission denied
**Possible Causes**
1. You do not have the permission to operate the file.
2. The file sandbox path is incorrect.
**Solution**
1. Check that you have the permission to operate the file.
2. Check that the file sandbox path is correct.
### 13900013 Incorrect Address
**Error Message**
Bad address
**Possible Causes**
The address is incorrect.
**Solution**
Check that the address is correct.
### 13900014 Device or Resource Not Available
**Error Message**
Device or resource busy
**Possible Causes**
The requested resource is unavailable.
**Solution**
Request the resource again.
### 13900015 File Already Exists
**Error Message**
File exists
**Possible Causes**
The file to be created already exists.
**Solution**
Check whether the file path is correct.
### 13900016 Invalid Cross-Device Link
**Error Message**
Cross-device link
**Possible Causes**
The link between devices is incorrect.
**Solution**
Check the devices and create the link correctly.
### 13900017 Device Not Exist
**Error Message**
No such device
**Possible Causes**
The device is not identified.
**Solution**
Check the connection to the target device.
### 13900018 Invalid Directory
**Error Message**
Not a directory
**Possible Causes**
The specified directory is invalid.
**Solution**
Check that the directory is correct.
### 13900019 The Specified Object Is a Directory
**Error Message**
Is a directory
**Possible Causes**
The specified object is a directory.
**Solution**
Check that the specified data is correct.
### 13900020 Invalid Parameter
**Error Message**
Invalid argument
**Possible Causes**
Invalid input parameter is detected.
**Solution**
Check that the input parameters are valid.
### 13900021 Too Many File Descriptors Opened
**Error Message**
File table overflow
**Possible Causes**
The number of file descriptors opened has reached the limit.
**Solution**
Close the file descriptors that are no longer required.
### 13900022 Too Many Files Opened
**Error Message**
Too many open files
**Possible Causes**
The number of files opened has reached the limit.
**Solution**
Close the files that are not required.
### 13900023 Text File Not Respond
**Error Message**
Text file busy
**Possible Causes**
The executable file of the program is in use.
**Solution**
Close the program that is being debugged.
### 13900024 File Oversized
**Error Message**
File too large
**Possible Causes**
The file size exceeds the limit.
**Solution**
Check whether the file size exceeds the limit.
### 13900025 Insufficient Space on the Device
**Error Message**
No space left on device
**Possible Causes**
The device storage space is insufficient.
**Solution**
Clear the space of the device.
### 13900026 Invalid Shift
**Error Message**
Illegal seek
**Possible Causes**
Seek is used in pipe or FIFO.
**Solution**
Check the use of seek.
### 13900027 Read-Only File System
**Error Message**
Read-only file system
**Possible Causes**
The file system allows read operations only.
**Solution**
Check whether the file is read-only.
### 13900028 Links Reach the Limit
**Error Message**
Too many links
**Possible Causes**
The number of links to the file has reached the limit.
**Solution**
Delete the links that are no longer required.
### 13900029 Resource Deadlock
**Error Message**
Resource deadlock would occur
**Possible Causes**
Resource deadlock occurs.
**Solution**
Terminate the deadlock process.
### 13900030 Long File Name
**Error Message**
Filename too Long
**Possible Causes**
The length of the path or file name exceeds the limit.
**Solution**
Modify the path or file name.
### 13900031 Function Not Implemented
**Error Message**
Function not implemented
**Possible Causes**
The function is not supported by the system.
**Solution**
Check the system version and update the system if required.
### 13900032 Directory Not Empty
**Error Message**
Directory not empty
**Possible Causes**
The specified directory is not empty.
**Solution**
1. Check the directory.
2. Ensure that the directory is empty.
### 13900033 Too Many Symbol Links
**Error Message**
Too many symbolic links
**Possible Causes**
There are too many symbolic links.
**Solution**
Delete unnecessary symbol links.
### 13900034 Operation Blocked
**Error Message**
Operation would block
**Possible Causes**
The operation is blocked.
**Solution**
Perform the operation again.
### 13900035 Invalid File Descriptor
**Error Message**
Invalid request desecriptor
**Possible Causes**
The requested file descriptor is invalid.
**Solution**
Check that the file descriptor is valid.
### 13900036 Target Is Not a Character Stream Device
**Error Message**
Device not a stream
**Possible Causes**
The device pointed to by the file descriptor is not a character stream device.
**Solution**
Check whether the file descriptor points to a stream device.
### 13900037 No Data Available
**Error Message**
No data available
**Possible Causes**
The required data is not available.
**Solution**
Request the data again.
### 13900038 Value Mismatches the Data Type
**Error Message**
Value too large for defined data type
**Possible Causes**
The specified value is out of the range defined for the data type.
**Solution**
Modify the data type.
### 13900039 File Descriptor Corrupted
**Error Message**
File descriptor in bad state
**Possible Causes**
The file descriptor is corrupted.
**Solution**
Check that the file descriptor is valid.
### 13900040 System Call Interrupted
**Error Message**
Interrupted systen call should be restarted
**Possible Causes**
The system call is interrupted.
**Solution**
Invoke the system call again.
### 13900041 Disk Quota Exceeded
**Error Message**
Quota exceeded
**Possible Causes**
The disk space is insufficient.
**Solution**
Clear disk space.
### 13900042 Unknown Error
**Error Message**
Unknown error
**Possible Causes**
The error is unidentified.
**Solution**
1. Call the API again.
2. Restart the service.
## User Data Management Error Codes
### 14000001 Invalid File Name
**Error Message**
Invalid display name
**Possible Causes**
The file name contains invalid characters.
**Solution**
Modify the file name.
### 14000002 Invalid URI
**Error Message**
Invalid uri
**Possible Causes**
The URI is invalid.
**Solution**
Use the obtained URI.
### 14000003 Invalid File Name Extension
**Error Message**
Invalid file extension
**Possible Causes**
The file name extension is incorrect.
**Solution**
Modify the file name extension.
### 14000004 File in Recycle Bin
**Error Message**
File has been put into trash bin
**Possible Causes**
The file is moved to the Recycle Bin.
**Solution**
Check whether the file is in the Recycle Bin.
## Spatial Statistics Error Codes
### 13600001 IPC Failed
**Error Message**
IPC error
**Possible Causes**
The called service does not exist.
**Solution**
Check whether the service is started.
### 13600002 File System Not Supported
**Error Message**
Not supported filesystem
**Possible Causes**
The file system is not supported.
**Solution**
Use a supported file system.
### 13600003 Mount Failed
**Error Message**
Failed to mount
**Possible Causes**
The **mount** command fails.
**Solution**
Remove the card and run the **mount** command again.
### 13600004 Unmount Failed
**Error Message**
Failed to unmount
**Possible Causes**
The device does not respond.
**Solution**
Check whether the file is being used. If yes, kill the thread that uses the file.
### 13600005 Incorrect Volume State
**Error Message**
Incorrect volume state
**Possible Causes**
The volume state is incorrect.
**Solution**
Check whether the current volume state is correct.
### 13600006 Failed to Create a Directory or Node
**Error Message**
Prepare directory or node error
**Possible Causes**
The directory or node to be created already exists.
**Solution**
Check whether the directory or node to be created already exists.
### 13600007 Failed to Delete a Directory or Node
**Error Message**
Delete directory or node error
**Possible Causes**
The specified directory or node has been deleted.
**Solution**
Check whether the specified directory or node exists.
### 13600008 Object Not Exist
**Error Message**
No such object
**Possible Causes**
1. The specified volume ID is incorrect.
2. The specified bundle name is incorrect.
**Solution**
1. Check whether the specified volume exists.
2. Check whether the specified bundle name exists.
### 13600009 Invalid User ID
**Error Message**
User id out of range
**Possible Causes**
The specified user ID is incorrect.
**Solution**
Check that the user ID is correct.
## User File Access Error Codes
### 14300001 IPC Failed
**Error Message**
IPC error
**Possible Causes**
1. The server service does not exist.
2. The extension mechanism is abnormal.
**Solution**
Check that the server service exists.
### 14300002 Incorrect URI Format
**Error Message**
Invalid uri
**Possible Causes**
The URI is invalid.
**Solution**
Check that the URI is in correct format.
### 14300003 Failed to Obtain the Server Ability Information
**Error Message**
Fail to get fileextension info
**Possible Causes**
The BMS interface is abnormal.
**Solution**
Check for basic system capability errors.
### 14300004 Incorrect Result Returned by js-server
**Error Message**
Get wrong result
**Possible Causes**
The data returned by the server is incorrect.
**Solution**
Check the data returned by the server.
### 14300005 Failed to Register Notify
**Error Message**
Fail to register notification
**Possible Causes**
1. The server service does not exist.
2. The extension mechanism is abnormal.
**Solution**
Check that the server service exists.
### 14300006 Failed to Unregister Notify
**Error Message**
Fail to remove notification
**Possible Causes**
1. The server service does not exist.
2. The extension mechanism is abnormal.
**Solution**
Check that the server service exists.
### 14300007 Failed to Initialize the Notify Agent
**Error Message**
Fail to init notification agent
**Possible Causes**
The specified Notify agent has not been registered.
**Solution**
Check whether the specified Notify agent is registered.
### 14300008 Failed to Notify the Agent
**Error Message**
Fail to notify agent
**Possible Causes**
1. The service does not exist.
2. The extension mechanism is abnormal.
**Solution**
Check whether the client is normal.
# Form Error Codes
## 16500001 Internal Error
**Error Message**
Internal Error.
**Description**
A common kernel error, for example, a malloc failure, occurs.
**Possible Causes**
The memory is insufficient.
**Solution**
Analyze the memory usage of the entire process, and check whether memory leakage occurs.
## 16500050 IPC Failure
**Error Message**
An IPC connection error happened.
**Description**
An error occurs when the system initiates inter-process communications (IPC) to complete the request.
**Possible Causes**
The parameter value passed in the API is too large, causing IPC data verification failure.
**Solution**
Pass appropriate parameter values.
## 16500060 Service Connection Failure
**Error Message**
A service connection error happened, please try again later.
**Description**
An error occurs when the system attempts to connect to a service to complete the request.
**Possible Causes**
The service is busy or abnormal.
**Solution**
Try again after the service is restarted.
## 16500100 Failed to Obtain Widget Configuration Information
**Error Message**
Failed to obtain configuration information.
**Description**
An error occurs when the system attempts to obtain widget configuration information to complete the request.
**Possible Causes**
The widget configuration information field is missing or invalid.
**Solution**
Use the correct configuration information.
## 16501000 Functional Error
**Error Message**
A functional error occurred.
**Description**
An internal error occurs when the system executes the request.
## 16501001 Widget ID Not Exist
**Error Message**
The ID of the form to be operated does not exist.
**Description**
The specified widget in the request is not found.
**Possible Causes**
The widget ID passed in the API does not exist or is invalid.
**Solution**
Use a valid widget ID.
## 16501002 Too Many Widgets
**Error Message**
The number of forms exceeds the upper bound.
**Description**
The application attempts to add more widgets when the number of widgets has reached the upper limit.
**Possible Causes**
The number of widgets has reached the upper limit.
**Solution**
Delete unnecessary widgets and then add the required widgets.
## 16501003 Widget Not Operatable
**Error Message**
The form can not be operated by the current application.
**Description**
The application cannot perform operations on a widget.
**Possible Causes**
The widget does not belong to the application.
**Solution**
1. Check the ownership of the widget ID.
2. Upgrade the application permission to **SystemApp**.
# Location Subsystem Error Codes
## 3301000 Location Service Unavailable
**Error Message**
Location service is unavailable.
**Description**
This error code is reported when the location service is unavailable and relevant APIs cannot be called.
**Possible Causes**
1. The location service fails to be started. As a result, the communication between the application and the location service fails, and the location service is unavailable.
2. The GNSS chip fails to be initialized, and thus the GNSS positioning function becomes invalid.
3. The network positioning service is abnormal, and thus the network positioning function becomes invalid.
**Solution**
Stop calling the API.
## 3301100 Location Service Unavailable Because of Switch Toggled Off
**Error Message**
The location switch is off.
**Description**
This error code is reported when the location service is unavailable because the service switch is toggled off.
**Possible Causes**
The location service switch is toggled off, which makes basic functions such as continuous positioning and immediate positioning unavailable.
**Solution**
Display a prompt asking for enabling the location service.
## 3301200 Failure to Obtain the Positioning Result
**Error Message**
Failed to obtain the geographical location.
**Description**
This error code is reported when the location service fails, and no positioning result is obtained.
**Possible Causes**
1. Positioning timed out because of weak GNSS signals.
2. Positioning timed out because the network positioning service is abnormal.
**Solution**
Initiate a positioning request again.
## 3301300 Reverse Geocoding Query Failure
**Error Message**
Reverse geocoding query failed.
**Description**
This error code is reported for a reverse geocoding query failure.
**Possible Causes**
Network connection is poor, which makes the request fail to be sent from the device or the result fail to be returned from the cloud to the device.
**Solution**
Try the reverse geocoding query again.
## 3301400 Geocoding Query Failure
**Error Message**
Geocoding query failed.
**Description**
This error code is reported for a geocoding query failure.
**Possible Causes**
Network connection is poor, which makes the request fail to be sent from the device or the result fail to be returned from the cloud to the device.
**Solution**
Try the geocoding query again.
## 3301500 Area Information Query Failure
**Error Message**
Failed to query the area information.
**Description**
This error code is reported for the failure to query the area information (including the country code).
**Possible Causes**
The correct area information is not found.
**Solution**
Stop calling the API for querying the country code.
## 3301600 Geofence Operation Failure
**Error Message**
Failed to operate the geofence.
**Description**
This error code is reported when an operation (like adding, deleting, pausing, and resuming) fails to be performed on the geofence.
**Possible Causes**
1. The GNSS chip does not support the geofence function.
2. The bottom-layer service logic is abnormal.
**Solution**
Stop calling the geofence operation API.
## 3301700 No Response to the Request
**Error Message**
No response to the request.
**Description**
This error code is reported when no response is received for an asynchronous request that requires a user to click a button for confirmation or requires a response from the GNSS chip or network server.
**Possible Causes**
1. The user does not click a button as required for confirmation.
2. The GNSS chip does not respond.
3. The network server does not respond.
**Solution**
Stop calling relevant APIs.
# Application Event Logging Error Codes
## 11100001 Application Event Logging Disabled
**Error Message**
Function is disabled.
**Description**
This error code is reported if the **write** API is called to perform application event logging but the system ignores related events because the logging function is disabled.
**Possible Causes**
The application event logging function is disabled.
**Solution**
Invoke the **configure** API to enable the application event logging function.
```js
hiAppEvent.configure({
disable: false
});
```
## 11101001 Invalid Event Domain Name
**Error Message**
Invalid event domain.
**Description**
This error code is reported if the **write** API is called to perform application event logging but the system ignores related events because the input event domain name is invalid.
**Possible Causes**
The specified event domain name does not comply with the following rules:
- The event domain name contains only digits, lowercase letters, and underscores (\_).
- The event domain name starts with a lowercase letter and does not end with an underscore (\_).
- The event domain name is not empty and contains a maximum of 32 characters.
**Solution**
Specify a valid event domain name.
## 11101002 Invalid Event Name
**Error Message**
Invalid event name.
**Description**
This error code is reported if the **write** API is called to perform application event logging but the system ignores related events because the input event name is invalid.
**Possible Causes**
The specified event name does not comply with the following rules:
- The event name contains only digits, lowercase letters, and underscores (\_).
- The event name starts with a lowercase letter and does not end with an underscore (\_).
- The event name is not empty and contains a maximum of 48 characters.
**Solution**
Specify a valid event name.
## 11101003 Invalid Number of Event Parameters
**Error Message**
Invalid number of event parameters.
**Description**
This error code is reported if the **write** API is called to perform application event logging but the system discards extra event parameters because the number of input event parameters exceeds the limit.
**Possible Causes**
The number of input event parameters exceeds 32.
**Solution**
Specify a valid number of event parameters.
## 11101004 Invalid Event Parameter String Length
**Error Message**
Invalid string length of the event parameter.
**Description**
This error code is reported if the **write** API is called to perform application event logging but the system ignores related event parameters because the value of the input event parameter is excessively long.
**Possible Causes**
The length of the input event parameter value exceeds 8 x 1024 characters.
**Solution**
Specify an event parameter value with a valid length.
## 11101005 Invalid Event Parameter Name
**Error Message**
Invalid event parameter name.
**Description**
This error code is reported if the **write** API is called to perform application event logging but the system ignores related event parameters because the input event parameter name is invalid.
**Possible Causes**
The specified event parameter name does not comply with the following rules:
- The event parameter name contains only digits, lowercase letters, and underscores (\_).
- The event parameter name starts with a lowercase letter and does not end with an underscore (\_).
- The event parameter name is not empty and contains a maximum of 16 characters.
**Solution**
Specify a valid event parameter name.
## 11101006 Invalid Array Length of Event Parameter Values
**Error Message**
Invalid array length of the event parameter.
**Description**
This error code is reported if the **write** API is called to perform application event logging but the system discards extra array elements because the array of the event parameter value is excessively long.
**Possible Causes**
The array length of the event parameter value exceeds 100.
**Solution**
Specify a valid array length for the event parameter value.
## 11102001 Invalid Watcher Name
**Error Message**
Invalid watcher name.
**Description**
This error code is reported if the **addWatcher** API is called to subscribe to application events but the system ignores the subscription because the specified watcher name is invalid.
**Possible Causes**
The specified watcher name does not comply with the following rules:
- The watcher name can contain only digits, lowercase letters, and underscores (\_).
- The watcher name starts with a lowercase letter and does not end with an underscore (\_).
- The watcher name is not empty and contains a maximum of 32 characters.
**Solution**
Specify a valid watcher name.
## 11102002 Invalid Filtering Event Domain Name
**Error Message**
Invalid filtering event domain.
**Description**
This error code is reported if the **addWatcher** API is called to subscribe to application events but the system ignores the subscription because the specified filtering event domain name is invalid.
**Possible Causes**
The specified filtering event domain name does not comply with the following rules:
- The event domain name contains only digits, lowercase letters, and underscores (\_).
- The event domain name starts with a lowercase letter and does not end with an underscore (\_).
- The event domain name is not empty and contains a maximum of 32 characters.
**Solution**
Specify a valid filtering event domain name.
## 11102003 Invalid Event Number
**Error Message**
Invalid row value.
**Description**
This error code is reported if the **addWatcher** API is called to subscribe to application events but the system ignores the subscription because an invalid event number is passed in the callback trigger condition.
**Possible Causes**
The event number passed in the input callback triggering condition is a negative number.
**Solution**
Specify a valid event number.
## 11102004 Invalid Event Size
**Error Message**
Invalid size value.
**Description**
This error code is reported if the **addWatcher** API is called to subscribe to application events but the system ignores the subscription because an invalid event size is passed in the callback trigger condition.
**Possible Causes**
The event size passed in the input callback triggering condition is a negative number.
**Solution**
Specify a valid event size.
## 11102005 Invalid Timeout Value
**Error Message**
Invalid timeout value.
**Description**
This error code is reported if the **addWatcher** API is called to subscribe to application events but the system ignores the subscription because an invalid timeout value is passed in the callback trigger condition.
**Possible Causes**
The timeout value passed in the input callback triggering condition is a negative number.
**Solution**
Specify a valid timeout value.
## 11103001 Invalid Maximum Storage Quota
**Error Message**
Invalid max storage quota value.
**Description**
This error code is reported if the **configure** API is called to subscribe to application events but the system ignores the setting because the specified maximum storage quota is invalid.
**Possible Causes**
The maximum storage quota does not meet the following rules:
- The quota value consists of only digits and a unit (including b|k|kb|m|mb|g|gb|t|tb, which are case-insensitive).
- The quota value must start with a digit. You can determine whether to pass the unit. If the unit is left empty, **b** (that is, byte) is used by default.
**Solution**
Specify a valid maximum storage quota.
## 11104001 Invalid Event Package Size
**Error Message**
Invalid size value.
**Description**
This error code is reported if the **setSize** API is called to set the threshold of the event package size but the system ignores the setting because the specified event package size is invalid.
**Possible Causes**
The specified event package size is a negative number.
**Solution**
Specify a valid event package size.
# HiSysEvent Error Codes
## 1120001 Invalid Event Domain
**Error Message**
Invalid event domain.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system ignores the logging operation because the input event domain name is invalid.
**Possible Causes**
1. The event domain name contains more than 16 characters.
2. The event domain name contains special characters.
3. The event domain name is empty.
**Solution**
Specify a valid event domain name.
## 1120002 Invalid Event Name
**Error Message**
Invalid event name.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system ignores the logging operation because the input event name is invalid.
**Possible Causes**
1. The event name contains more than 32 characters.
2. The event name contains special characters.
3. The event name is empty.
**Solution**
Check whether the event name is valid.
## 11200003 Environment Error
**Error Message**
Abnormal environment.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system ignores the logging operation because the environment is abnormal.
**Possible Causes**
1. The hiview service fails to be started.
2. The socket of the hiview service is abnormal.
**Solution**
Call the **write** API again to perform event logging.
## 11200004 Invalid Event Length
**Error Message**
Length of the event is over limit.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system ignores the logging operation because the total event length is invalid.
**Possible Causes**
The total event length exceeds 384 KB.
**Solution**
Check whether the total event length is greater than 384 KB.
## 11200051 Invalid Event Parameter
**Error Message**
Invalid event parameter.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system throws an exception because the input parameter name is invalid. However, the system will continue to complete the logging operation.
**Possible Causes**
1. The event parameter name contains more than 32 characters.
2. The event parameter name contains special characters.
3. The event parameter name is empty.
**Solution**
Check whether the event parameter name is valid.
## 11200052 Length of Event Parameter Values of the String Type Exceeding the Limit
**Error Message**
Size of the event parameter of the string type is over limit.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system throws an exception because the length of event parameter values of the string type is invalid. However, the system will continue to complete the logging operation.
**Possible Causes**
The length of parameter values of the string type exceeds 10 KB.
**Solution**
Check whether the length of parameter values of the string type exceeds 10 KB.
## 11200053 Number of Event Parameters Exceeding the Limit
**Error Message**
Count of event parameters is over limit.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system throws an exception because the number of event parameters is invalid. However, the system will continue to complete the logging operation.
**Possible Causes**
The number of event parameters exceeds 128.
**Solution**
Check whether the number of event parameters exceeds 128.
## 11200054 Length of Event Parameter Values of the Array Type Exceeding the Limit
**Error Message**
Count of event parameter of the array type is over limit.
**Description**
This error code is reported if the **write** API is called to perform system event logging but the system throws an exception because the length of event parameter values of the array type is invalid. However, the system will continue to complete the logging operation.
**Possible Causes**
The length of a parameter values of the array type exceeds 100.
**Solution**
Check whether the length of the parameter value of the array type exceeds 100.
## 11200101 Number of Event Watchers Exceeding the Limit
**Error Message**
Count of watchers is over limit.
**Description**
This error code is reported if the **addWatcher** API is called to add an event watcher but the system rejects the operation because the number of watchers has exceeded the limit.
**Possible Causes**
A total of 30 event watchers have been added.
**Solution**
Check whether the number of event watchers exceeds 30.
## 11200102 Number of Event Watcher Rules Exceeding the Limit
**Error Message**
Count of watch rules is over limit.
**Description**
This error code is reported if the **addWatcher** API is called to add an event watcher but the system rejects the operation because the number of watcher rules has exceeded the limit.
**Possible Causes**
A total of 20 event watcher rules have been added.
**Solution**
Check whether the number of event watcher rules exceeds 20.
## 11200201 Event Watcher Not Exist
**Error Message**
The watcher does not exist.
**Description**
This error code is reported if the **removeWatcher** API is called to remove an event watcher but the system rejects the operation because the watcher does not exist.
**Possible Causes**
1. The event watcher to be removed is empty.
2. The event watcher to be removed has not been successfully added.
**Solution**
Check whether the event watcher to the removed is empty or whether the event watcher has been successfully added.
## 11200301 Number of Query Rules Exceeding the Limit
**Error Message**
Count of query rules is over limit.
**Description**
This error code is reported if the **query** API is called to query system events but the system ignores the operation because the number of query rules has exceeded the limit.
**Possible Causes**
The number of query rules exceeds 10.
**Solution**
Check whether the number of query rules exceeds 10.
## 11200302 Invalid Query Rule
**Error Message**
Invalid query rule.
**Description**
This error code is reported if the **query** API is called to query system events but the system ignores the operation because the input query rule is invalid.
**Possible Causes**
1. The event domain name in the query rule contains more than 16 characters or the event name contains more than 32 characters.
2. The event domain name or event name in the query rule contains special characters.
3. The event domain name or event name in the query rule is empty.
**Solution**
Check whether the event domain name and event name configured in the query rule are valid.
## 11200303 Number of Concurrent Queries Exceeding the Limit
**Error Message**
Count of concurrent queries is over limit.
**Description**
This error code is reported if the **query** API is called to query system events but the system ignores the operation because the number of concurrent queries has exceeded the limit.
**Possible Causes**
The number of concurrent queries exceeds 4.
**Solution**
Check whether more than four queries are performed at the same time.
## 11200304 Query Frequency Exceeding the Limit
**Error Message**
Query frequency is over limit.
**Description**
This error code is reported if the **query** API is called to query system events but the system ignores the operation because the query frequency has exceeded the limit.
**Possible Causes**
More than one query is performed in one second.
**Solution**
Check whether more than one query is performed in one second.
# HiDebug Error Codes
## 11400101 Failed to Obtain the System Service
**Error Message**
ServiceId is invalid, systemAbility is not exist.
**Description**
No system service is found based on the specified service ID.
**Possible Causes**
The specified service ID is incorrect.
**Solution**
Specify a correct system service ID.
......@@ -4,20 +4,19 @@
**Error Message**
`${messageInfo}` is not supported.
The `${messageInfo}` is not supported.
**Possible Causes**
The API is supported, but certain features in the API, such as the algorithm, are not supported.
**Solution**
Modify the parameters and use the features supported.
Use the supported features as parameters.
## 12000002 Missing Key Algorithm Parameter
**Error Message**
Failed to obtain `${messageInfo}`. It is not set in ParamSet.
Failed to obtain the `${messageInfo}`. It is not set in ParamSet.
**Possible Causes**
......@@ -47,9 +46,12 @@ An invalid parameter is found.
**Error Message**
Failed to read the file.
A file error can be any of the following:
- Insufficient storage space.
- Invalid file size.
- Failed to `${messageInfo}`.
Failed to write the file.
**Possible Causes**
......@@ -57,20 +59,21 @@ The file operation failed.
**Solution**
1. Check whether the disk space is used up and whether the file system is abnormal.
1. Check whether sufficient disk space is available and whether the file system is normal.
2. Clear the disk space.
## 12000005 IPC Error
**Error Message**
IPC timed out.
An IPC error can be any of the following:
Failed to obtain messages from IPC.
- Failed to get messages from IPC.
- IPC `${messageInfo}`.
**Possible Causes**
IPC failed.
The Inter-Process Communication (IPC) failed.
**Solution**
......@@ -110,7 +113,7 @@ The possible causes include the following:
**Solution**
1. Locate the cause of the authentication failure based on the log.
2. If the authentication fails due to the access control attribute configured, the key cannot be used any more.
2. If the authentication fails due to the configuration of the access control attribute, the key cannot be used any more.
## 12000008 Failed to Access the Key Due to a Failure in Authentication Token Verification
......@@ -120,18 +123,18 @@ The authentication token verification failed.
**Possible Causes**
The authentication token verification failed due to an incorrect challenge value.
The challenge value is incorrect.
**Solution**
1. Check whether the challenge for userIAM authentication is correctly assembled.
2. If the challenge value is incorrect, modify the assembly mode, use the bytes generated by HUKS to assembly challenge value, and pass it to userIAM for authentication.
1. Check whether the challenge for user IAM authentication is correctly assembled.
2. If the challenge value is incorrect, modify the assembly mode, use the bytes generated by HUKS to assembly the challenge value, and pass it to user IAM for authentication.
## 12000009 Key Access Timed Out
**Error Message**
The Authentication token timed out.
This authentication token timed out.
**Possible Causes**
......@@ -139,7 +142,7 @@ The authentication failed because the authentication token timed out.
**Solution**
The difference between the current time and the authentication token generation time must be less than the timeout interval. Otherwise, the access will be rejected.
Initialize the key and perform the authentication again. Ensure that the difference between the current time and the authentication token generation time is less than the timeout interval.
## 12000010 Key Operation Sessions Reaches the Limit
......@@ -168,18 +171,18 @@ The key corresponding to the key alias does not exist.
**Solution**
1. Check whether the key alias is misspelled.
1. Check whether the key alias is correctly spelled.
2. Check whether the key corresponding to the key alias is successfully generated.
## 12000012 External Error
**Error Message**
External error `${messageInfo}`.
System external error.
**Possible Causes**
An external error, such as a hardware fault or file error occurs.
An external error, such as a hardware fault or file error, occurs.
**Solution**
......@@ -203,7 +206,9 @@ Enroll the credential or change the authentication type bound to the key.
**Error Message**
Memory is insufficient.
- Insufficient memory.
- Malloc failed.
**Possible Causes**
......@@ -217,7 +222,7 @@ Release memory or restart the device.
**Error Message**
Failed to call the `${messageInfo}` service to do `${messageInfo}`.
Failed to obtain the `${messageInfo}` information via UserIAM.
**Possible Causes**
......
# I18N Error Codes
# i18n Error Codes
## 890001 Incorrect Parameter Type
......
# Input Method Framework Error Codes
## 12800001 Package Manager Error
**Error Message**
Package manager error.
**Description**
This error code is reported when an API of the package manager, such as **getInputMethods** and **listCurrentInputMethodSubtype**, fails to be invoked to obtain information.
**Possible Causes**
The package manager is not working correctly.
**Solution**
None
## 12800002 Input Method Engine Error
**Error Message**
Input method engine error.
**Description**
This error code is reported when an input method API fails to be invoked.
**Possible Causes**
The input method process is suspended.
**Solution**
Check whether the input method process is running properly. For example, click the input text box in an appliccation and check whether the input keyboard is displayed.
## 12800003 Input Method Client Error
**Error Message**
Input method client error.
**Description**
This error code is reported when the API for showing or hiding the keyboard fails to be invoked by a third-party application.
**Possible Causes**
The input method is disconnected from the third-party application due to a service error with the application.
**Solution**
Bind the input method to the third-party application again: Close the background process of the third-party application, start the application again, and touch an input text box. If the keyboard is displayed properly, the issue is resolved.
## 12800004 Key Event Processing Error
**Error Message**
Key event processing error.
**Description**
This error code is reported when a key event error occurs.
**Possible Causes**
An exception occurs during key event distribution, consumption, or listening.
**Solution**
None
## 12800005 Configuration Persistence Error
**Error Message**
Configuration persisting error.
**Description**
This error code is reported when the configuration fails to be saved during input method switching.
**Possible Causes**
An exception occurs with the system parameter configuration module.
**Solution**
Run the **hdc shell param get persist.sys.default_ime** command to check the default input method parameters. If the parameters are displayed, the system parameter configuration module is working properly. In this case, restart the device and try again.
## 12800006 Input Method Controller Error
**Error Message**
Input method controller error.
**Description**
This error code is reported when the input method controller fails to be obtained.
**Possible Causes**
An error occurs during invoking of the **getCotroller** API.
**Solution**
None
## 12800007 Input Method Setter Error
**Error Message**
Input method settings extension error.
**Description**
This error code is reported when an **InputMethodSetting** instance fails to be obtained.
**Possible Causes**
An error occurs during invoking of the **getSetting** API.
**Solution**
None
## 12800008 Input Method Manager Service Error
**Error Message**
Input method manager service error.
**Description**
This error code is reported when an API of the [input method framework](../apis/js-apis-inputmethod.md) fails to be invoked.
**Possible Causes**
The input method manager service fails to be obtained.
**Solution**
Run the **ps -A|grep inputmethod** command to check for the process ID of the input method service. If the process ID is found, the service is working properly.
# Media Error Codes
## 5400101 Memory Allocation Failed
**Error Message**
No memory.
**Description**
Failed to allocate memory.
**Possible Causes**
1. The number of instances exceeds 16.
2. The new or malloc process fails, causing a null pointer.
**Solution**
Destroy this instance and re-create it. If the re-creation fails, stop related operations.
## 5400102 Unsupported Operation
**Error Message**
Operate not permit.
**Description**
This operation is not allowed.
**Possible Causes**
This operation is not allowed in the current state.
**Solution**
Switch the instance to the correct state and perform the operation.
## 5400103 I/O Error
**Error Message**
IO error.
**Description**
An I/O error occurs.
**Possible Causes**
The data interaction between the media and other modules (graphics, audio, network, HDI, and camera) is abnormal.
**Solution**
Ensure that the network is normal, destroy this instance, and re-create it. If the re-creation fails, stop related operations.
## 5400104 Operation Timeout
**Error Message**
Time out.
**Description**
The operation timed out.
**Possible Causes**
1. The network connection times out.
2. Accessing other modules times out.
**Solution**
1. Check whether the network is normal.
2. Destroy this instance and re-create it. If the re-creation fails, stop related operations.
## 5400105 Play Service Dead
**Error Message**
Service died.
**Description**
The playback service is dead.
**Possible Causes**
The playback service is dead.
**Solution**
Destroy this instance and re-create it. If the re-creation fails, stop related operations.
## 5400106 Format Not Supported
**Error Message**
Unsupport format.
**Description**
The format is not supported.
**Possible Causes**
The file format is not supported.
**Solution**
Use a supported format.
# NFC Error Codes
## 3100101
**Error Message**
NFC opening or closing state is abnormal in service.
**Description**
The NFC service fails to enable or disable NFC.
**Possible Causes**
Communication with the NFC service failed.
**Solution**
Enable or disable NFC again.
## 3100201
**Error Message**
Tag running state is abnormal in service.
**Description**
An error occurs when the NFC service executes the tag service logic.
**Possible Causes**
1. The tag parameters do not match the API to invoke.
2. The NFC is disabled.
3. The tag is disconnected before the tag operation.
4. The tag chip returns an error status or response timeout.
5. Binding with the NFC service has not been established.
**Solution**
1. Check whether the NFC parameters match the API to invoke.
2. Enable NFC for the device.
3. Connect to the tag and then perform the read and write operations.
4. Touch and read the card again.
5. Exit the app and read the card again.
# Pasteboard Error Codes
## 12900001 Index Out of Range
**Error Message**
The index is out of range.
**Description**
This error code is reported when the index passed in to the called API, such as **getRecord**, is out of range.
**Possible Causes**
The index passed in the API is beyond the record index range of the **PasteData** object. For example, the index passed in to **getRecord** exceeds the number of records.
**Solution**
Check the index range and call the API again with a valid index.
## 12900002 Maximum Number of Records Reached
**Error Message**
The number of record exceeds the maximum limit.
**Description**
This error code is reported when no new **PasteData** record can be added.
**Possible Causes**
The number of **PasteData** records has reached the maximum.
**Solution**
1. Check whether the number of **PasteData** records has reached the maximum.
2. If the number of **PasteData** records has reached the maximum, delete some records before adding new ones.
## 12900003 Another Copy or Paste Operation in Progress
**Error Message**
Another copy or paste is in progress.
**Description**
This error code is reported when a new copy or paste attempt is made before the previous one is completed.
**Possible Causes**
The copy and paste APIs are both asynchronous APIs. If the data to be copied or pasted is in large amount, the time required may be long. New copy or paste operations can be performed only after the previous operations have been completed.
**Solution**
1. Before copying or pasting data, check the status of the last copy or paste operation.
2. Perform subsequent operations only after the previous copy/paste operation is completed.
## 12900004 Copy Prohibited
**Error Message**
Replication is prohibited.
**Description**
This error code is reported when an attempt is made to copy data that cannot be copied.
**Possible Causes**
The target data cannot be copied, such as read-only data.
**Solution**
Make sure the target data allows the copy action.
\ No newline at end of file
# Power Manager Error Codes
## 4900101 Service Connection Failure
**Error Message**
Operation failed. Cannot connect to service.
**Description**
This error code is reported for a service connection failure.
**Possible Causes**
1. The system service stops running.
2. The internal communication of system services is abnormal.
**Solution**
Check whether the system services are running properly.
1. Run the following command on the console to view the current system service list:
```bash
> hdc shell hidumper -ls
```
2. Check whether **PowerManagerService** is included in the system service list.
## 4900102 System Shuting Down
**Error Message**
Operation failed. System is shutting down.
**Description**
This error code is reported when an operation failed during system shutting down.
**Possible Causes**
The system is shutting down.
**Solution**
Make sure that the operation is performed when the system is running properly.
......@@ -4,7 +4,7 @@
**Error Message**
Notification does not enable.
Notification is not enabled.
**Description**
......@@ -63,7 +63,7 @@ The reminder passed in **cancelReminder()** does not exist.
**Error Message**
The package name does not exist.
The bundle name does not exist.
**Description**
......
# RPC Error Codes
The APIs of the **rpc** module return exceptions since API version 9.
## 1900001 Failed to Call mmap
**Error Message**
Call mmap function failed.
**Description**
The mmap function failed.
**Possible Causes**
1. The mapping area is too large.
2. There is no sufficient memory for mapping.
**Solution**
1. Check whether the memory specified in **Ashmem::create()** is too large.
2. Check whether the system has sufficient memory for the mapping operation.
## 1900002 Failed to Call ioctl
**Error Message**
Call os ioctl function failed.
**Description**
Failed to call **ioctl** with the shared memory file descriptor.
**Possible Causes**
1. Invalid kernel parameters are set.
2. The specified type does not comply with the types specified when the shared memory is mapped.
**Solution**
1. Check whether the specified parameters are **PROT_EXEC**, **PROT_READ**, and **PROT_WRITE** of the **Ashmem** class.
2. Check whether the type specified is one of the types specified when the shared memory is mapped.
## 1900003 Failed to Write Data to the Shared Memory
**Error Message**
Write to ashmem failed.
**Description**
Failed to write data to the shared memory.
**Possible Causes**
1. The size of a single write or total size of continuous writes exceeds the size of the shared memory.
2. The PROT_WRITE mode is not enabled for the shared memory.
**Solution**
1. Check whether the data to be written to the shared memory exceeds the total size of the shared memory mapped.
2. Check that PROT_WRITE is enabled for the shared memory.
## 1900004 Failed to Read Data from the Shared Memory
**Error Message**
Read from ashmem failed.
**Description**
Failed to read data from the shared memory.
**Possible Causes**
1. The size of a single read or total size of continuous reads exceeds the size of the shared memory.
2. The PROT_READ mode is not enabled for the shared memory.
**Solution**
1. Check whether the data to be read exceeds the total size of the shared memory mapped.
2. Check that PROT_READ is enabled for the shared memory.
## 1900005 Operation Allowed Only for the Proxy Object
**Error Message**
Only proxy object permitted.
**Description**
This operation is allowed only on the proxy object.
**Possible Causes**
A method supported only by the **RemoteProxy** object is called for the **RemoteObject** object.
**Solution**
Check whether a method supported only by the **RemoteProxy** object is called for the **RemoteObject** object.
## 1900006 Operation Allowed Only for the Remote Object
**Error Message**
Only remote object permitted.
**Description**
This operation is allowed only on the remote object.
**Possible Causes**
A method supported only by the **RemoteObject** object is called for the **RemoteProxy** object.
**Solution**
Check whether a method supported only by the **RemoteObject** object is called for the **RemoteProxy** object.
## 1900007 Failed to Communicate with the Remote Object
**Error Message**
Communication failed.
**Description**
Failed to communicate with the remote object over IPC.
**Possible Causes**
1. The remote object has been destroyed.
2. The remote object is re-created, but the proxy object held by the local end has expired.
**Solution**
1. Check whether the remote object has been destroyed.
2. Check whether an observer for listening for the dead status of the remote object is registered, and whether the remote object is destructed and created again.
## 1900008 Invalid IPC Object
**Error Message**
Proxy or remote object is invalid.
**Description**
The proxy or remote object is invalid.
**Possible Causes**
1. The proxy object is invalid.
2. The remote object has been destroyed.
**Solution**
1. Check whether an exception occurs when the proxy object is obtained.
2. Check whether the remote object is destructed.
## 1900009 Failed to Write Data to MessageSequence
**Error Message**
Write data to message sequence failed.
**Description**
Failed to write data to **MessageSequence**.
**Possible Causes**
The default **MessageSequence** space is full.
**Solution**
Use the method provided by **MessageSequence** to check whether **MessageSequence** has sufficient space.
## 1900010 Failed to Read Data from MessageSequence
**Error Message**
Read data from message sequence failed.
**Description**
Failed to read data from **MessageSequence**.
**Possible Causes**
The data read sequence is different from the data write sequence.
**Solution**
Check that the data read sequence is the same as the data write sequence.
## 1900011 Memory Allocation Failed
**Error Message**
Sequence memory alloc failed.
**Description**
Failed to allocate memory during serialization.
**Possible Causes**
The data to write is too large.
**Solution**
Check whether the data to write is too large or whether parameters are set improperly.
## 1900012 JS Callback Failed
**Error Message**
Call JS callback function failed.
**Description**
Failed to invoke the JS callback.
**Possible Causes**
The JS function of the service returns a failure message.
**Solution**
Check whether the JS function is successfully executed.
## 1900013 Failed to Invoke dup
**Error Message**
Call os dup function failed.
**Description**
Failed to call dup.
**Possible Causes**
1. The file handle resources of the process are used up.
2. The specified **fd** is closed.
**Solution**
1. Check whether the input parameter** fd** is valid.
2. Check whether there are file handle resources of the process.
# Running Lock Error Codes
## 4900101 Service Connection Failure
**Error Message**
Operation failed. Cannot connect to service.
**Description**
This error code is reported for a service connection failure.
**Possible Causes**
1. The system service stops running.
2. The internal communication of system services is abnormal.
**Solution**
Check whether the system services are running properly.
1. Run the following command on the console to view the current system service list:
```bash
> hdc shell hidumper -ls
```
2. Check whether **PowerManagerService** is included in the system service list.
# Thermal Manager Error Codes
## 4800101 Service Connection Failure
**Error Message**
Operation failed. Cannot connect to service.
**Description**
This error code is reported for a service connection failure.
**Possible Causes**
1. The system service stops running.
2. The internal communication of system services is abnormal.
**Solution**
Check whether the system services are running properly.
1. Run the following command on the console to view the current system service list:
```bash
> hdc shell hidumper -ls
```
2. Check whether **ThermalService** is included in the system service list.
# UiTest Error Codes
## 17000001 Initialization Failure
**Error Message**
Initialize failed.
**Description**
This error code is reported when the framework fails to be initialized.
**Possible Causes**
The accessibility service cannot be accessed.
**Solution**
Run the **param set persist.ace.testmode.enabled 1** command and restart the device.
## 17000002 Unable to Call the API
**Error Message**
API does not allow calling concurrently.
**Description**
This error code is reported when the API fails to be called.
**Possible Causes**
The API was not called using **await**.
**Solution**
Check test cases and make sure asynchronous APIs are called using **await**.
## 17000003 Assertion Failure
**Error Message**
Component existence assertion failed.
**Description**
This error code is reported when the user assertion fails.
**Possible Causes**
The component that the user asserts to exist does not exist.
**Solution**
Check the existence of the component that is asserted to exist.
## 17000004 Target Component/Window Lost
**Error Message**
Component lost/UiWindow lost.
**Description**
This error code is reported when the target component or window is lost and cannot be operated.
**Possible Causes**
After the target component or window is obtained, the page changes. As a result, the target component or window is lost.
**Solution**
Check whether the loss is caused by page changes.
## 17000005 Operation Not Supported
**Error Message**
This operation is not supported.
**Description**
This error code is reported when the performed operation is not supported by the UI object.
**Possible Causes**
The component or window attribute does not support the performed operation.
**Solution**
Make sure the operation to perform is supported by the component or window attribute.
# Universal Error Codes
## 201 Permission Denied
**Error Message**
Permission verification failed, usually the result returned by VerifyAccessToken.
**Description**
This error code is reported when permission verification fails.
**Possible Causes**
The application calls an API without the required permission.
**Solution**
Check the permission required to call the API and make sure the application has the permission.
## 202 Permission Verification Failed for Calling a System API
**Error Message**
Permission verification failed, application which is not a system application uses system API.
**Description**
This error code is reported when a non-system application failed the permission verification.
**Possible Causes**
The API called by the application is a system API.
**Solution**
Check whether any system API is called. Delete it if any.
## 401 Parameter Check Failed
**Error Message**
BusinessError 401: Parameter error. The type of "${parameterName}" must be ${validType}[or ${validInput}].
**Description**
This error code is reported when a parameter error occurs.
**Possible Causes**
The mandatory parameter is not passed in, or the parameter type is invalid.
**Solution**
Make sure the mandatory parameter is passed in and the type of the passed parameter is invalid.
## 801 API Not Supported
**Error Message**
BusinessError 801: Capability not supported. function ${functionName } can not work correctly due to limited device capabilities.
**Description**
This error code is reported when the device supports the target SysCap but does not support a specific API.
**Possible Causes**
The device does not support the API.
**Solution**
Check whether the device supports the API.
# Update Error Codes
## 11500104 IPC Error
**Error Message**
BusinessError 11500104: IPC error.
**Description**
This error code is reported if an exception is thrown during an IPC call.
**Possible Causes**
An IPC API call failed.
**Solution**
1. Check whether the update system ability has started. If not, start it.
2. Check whether IPC data conversion is normal. If not, check the conversion process.
# USB Error Codes
## 14400001 USB Device Connection Denied
**Error Message**
Permission denied. Need call requestRight to get permission.
**Description**
This error code is reported if a certain API of the USB module is called but the required permission is not granted.
**Possible Causes**
The permission to access the USB device is not granted.
**Solution**
Call **requestRight** to request for the permission to access the USB device.
# User Authentication Error Codes
## 201 Permission Verification Failed
For details, see [Universal Error Codes](./errorcode-universal.md).
## 202 Invoker Is Not a System Application
For details, see [Universal Error Codes](./errorcode-universal.md).
## 401 Parameter Check Failed.
For details, see [Universal Error Codes](./errorcode-universal.md).
## 12500001 Authentication Failed
**Error Message**
Authentication failed.
**Possible Causes**
The credential does not match the credential enrolled.
**Solution**
Initiate authentication again.
## 12500002 General Operation Error
**Error Message**
General operation error.
**Possible Causes**
1. An error occurs when the NAPI layer parses parameters.
2. The process of the user authentication service is not started.
3. The proxy client fails to write data over IPC.
4. The stub server fails to parse data over IPC.
5. The driver service is not obtained.
**Solution**
Call the API again later or restart the device.
## 12500003 Authentication Canceled
**Error Message**
Authentication canceled.
**Possible Causes**
The authentication operation has been canceled.
**Solution**
Initiate the authentication again.
## 12500004 Authentication Timed Out
**Error Message**
Authentication timeout.
**Possible Causes**
The authentication is not complete within the specified time.
**Solution**
Initiate the authentication again.
## 12500005 Unsupported Authentication Type
**Error Message**
The authentication type is not supported.
**Possible Causes**
1. The input authentication type parameter is not supported. For example, if the authentication type passed in **getAvailableStatus** of the **userAuth** module is not **FACE** or **FINGERPRINT**, error code 12500005 is returned.
2. The device does not support the authentication type. For example, if fingerprint authentication is initiated on a device that has no fingerprint sensor, error code 12500005 is returned.
**Solution**
Check the authentication type parameter and call the API again.
## 12500006 Unsupported Authentication Trust Level
**Error Message**
The authentication trust level is not supported.
**Possible Causes**
1. The **authTrustLevel** value in **getAvailableStatus** or **getAuthInstance** of the **userAuth** module is not in the range [ATL1, ATL2, ATL3, ATL4].
2. The device does not support the authentication trust level. For example, if facial authentication for payment is initiated on a device that has only 2D cameras, error code 12500006 is returned.
**Solution**
Check that the **authTrustLevel** passed in is within the value range, and the device supports the specified authentication trust level.
## 12500007 Authentication Service Unavailable
**Error Message**
Authentication service is busy.
**Possible Causes**
Another authentication is initiated when the current authentication has not been finished yet.
**Solution**
Initiate authentication again later.
## 12500009 Authentication Locked
**Error Message**
Authentication is lockout.
**Possible Causes**
The number of authentication failures exceeds the limit.
**Solution**
Initiate authentication later.
## 12500010 Credential Not Enrolled
**Error Message**
The type of credential has not been enrolled.
**Possible Causes**
The **authType** parameter set in **getAvailableStatus** of the **userAuth** module is **FACE**, but no facial credential is enrolled in the device.
**start()** is called to initiate facial authentication, but no facial credential is enrolled in the device.
**Solution**
Check that the related type of credential has been enrolled in the device.
## 12700001 Failed to Enroll Faces
**Error Message**
The operation is failed.
**Possible Causes**
1. The facial authentication service is not started when **setSurfaceId()** of the **userAuth** module is called.
2. The proxy client fails to write data over IPC.
3. The stub server fails to parse data over IPC.
4. An error occurs when the facial authentication driver is invoked.
**Solution**
Call the API again later or restart the device.
# Utils Error Codes
## 10200001 Value Out of Range
**Error Message**
The value of ${param} is out of range.
**Description**
The value of a parameter passed in the API exceeds the valid range.
**Possible Causes**
The parameter value exceeds the value range.
**Solution**
Use a valid parameter value.
## 10200002 Parameter Parsing Error
**Error Message**
Invalid ${param} string.
**Description**
Failed to parse a string.
**Possible Causes**
A parameter of the string type passed in the API is a non-standard string. As a result, the string fails to be parsed.
**Solution**
Check the format of the string.
## 10200003 Failed to Initialize the Worker Instance
**Error Message**
Worker initialization failure.
**Description**
The **Worker** instance fails to be initialized when the API is called.
**Possible Causes**
1. The number of **Worker** instances to be created exceeds the upper limit.
2. The options for setting the **Worker** instance are incorrect.
**Solution**
1. Check whether the number of **Worker** instances exceeds 8. If yes, destroy idle **Worker** instances.
2. If **WorkerOptions** is set, check the parameter type and validity.
## 10200004 Worker Instance Is Not Running
**Error Message**
Worker instance is not running.
**Description**
The **Worker** instance is not running when the API is called.
**Possible Causes**
When the API is called, the **Worker** instance has been destroyed or is being destroyed.
**Solution**
Ensure that the **Worker** instance is running properly.
## 10200005 Worker Thread Does Not Support an API
**Error Message**
The invoked API is not supported in workers.
**Description**
An API that is not supported by the worker thread is called.
**Possible Causes**
The worker thread does not support the API.
**Solution**
Use a supported API.
## 10200006 Worker Transmission Information Serialization Exception
**Error Message**
Serializing an uncaught exception failed.
**Description**
An error occurs when serializing transmission information.
**Possible Causes**
The transmission information is not serializable.
**Solution**
Use transmission information that is a valid serialized object.
## 10200007 Abnormal Worker File Path
**Error Message**
The worker file path is invalid.
**Description**
The file path is invalid, and the **Worker** instance cannot be loaded.
**Possible Causes**
The worker file path is invalid. As a result, a valid **worker.abc** file cannot be generated during the build.
**Solution**
Ensure that the worker file path complies with the specifications for creating **Worker** instances. For details, see the example under [constructor<sup>9+</sup>](../apis/js-apis-worker.md#constructor9).
## 10200009 Buffer Size Error
**Error Message**
Buffer size must be a multiple of ${size}.
**Description**
The buffer size does not meet the requirement.
**Possible Causes**
The buffer size is not an integer multiple of **size**, which can be 16-bit, 32-bit, or 64-bit.
**Solution**
Use a buffer the size of which meets the requirements.
## 10200010 Empty Container
**Error Message**
The container is empty.
**Description**
The container to be operated is empty.
**Possible Causes**
No element is added to the container.
**Solution**
Add elements to the container first.
## 10200011 Passed this.object Is Not an Instance of the containers Class
**Error Message**
The {methodName} method cannot be bound.
**Description**
**this.object** passed in the API is not an instance of the **containers** class.
**Possible Causes**
The APIs of the **containers** class do not support **bind()**.
**Solution**
1. Check whether **bind()** is used to call the API.
2. Check whether an object that is not a container instance is assigned to the API.
## 10200012 Constructor Calling Failure
**Error Message**
The {className}'s constructor cannot be directly invoked.
**Description**
A constructor of the **containers** class is called directly to create an instance.
**Possible Causes**
The constructors of the **containers** class cannot be directly called. The keyword **new** must be used.
**Solution**
Use the keyword **new** to create an instance.
## 10200013 Read-Only Properly
**Error Message**
Cannot set property ${propertyName} of Buffer which has only a getter.
**Description**
The buffer ${propertyName} is read-only and cannot be set.
**Possible Causes**
The buffer is read-only.
**Solution**
Do not set the read-only attribute for the buffer.
# Webview Error Codes
## 17100001 WebviewController Not Associated with a Web Component
**Error Message**
Init error. The WebviewController must be associated with a Web compoent.
**Description**
This error code is reported when the **WebviewController** object is not associated with any **\<Web>** component.
**Solution**
Bind the **WebviewController** object to a **\<Web>** component.
## 17100002 Invalid URL
**Error Message**
Invalid url.
**Description**
This error code is reported when the URL format is incorrect.
**Solution**
Verify the URL format.
## 17100003 Incorrect Resource Path
**Error Message**
Invalid resource path or file type.
**Description**
This error code is reported when the path to the resource file is incorrect.
**Possible Causes**
The resource file does not exist or cannot be accessed.
**Solution**
Make sure the path to the resource file is correct.
## 17100004 Function Not Enabled
**Error Message**
Function not enable.
**Description**
This error code is reported when the related function is not enabled.
**Solution**
Make sure the related function is enabled.
## 17100005 Invalid Cookie Value
**Error Message**
Invalid cookie value.
**Description**
This error code is reported when the cookie value type is invalid.
**Possible Causes**
The cookie value type is not supported.
**Solution**
Verify the cookie value type.
## 17100006 Message Port Callback Cannot Be Registered
**Error Message**
Can not register message event using this port.
**Description**
This error code is reported when a callback fails to be registered for the message port.
**Possible Causes**
The port is closed.
**Solution**
Make sure the port is open.
## 17100007 Invalid Forward or Backward Operation
**Error Message**
Invalid back or forward operation.
**Description**
This error code is reported when the specified forward or backward cannot be performed.
**Possible Causes**
1. The browsing history is cleared.
2. There is no browsing operation corresponding to the forward or backward operation.
**Solution**
1. Check whether **clearHistory** has been performed.
2. Check whether the number of pages specified by the forward or backward operation is available.
## 17100008 javaScriptProxy Does Not Exist
**Error Message**
Cannot delete JavaScriptProxy.
**Description**
This error code is reported when the **javaScriptProxy** object to delete does not exist.
**Possible Causes**
The target **javaScriptProxy** object is not yet registered.
**Solution**
Make sure the **javaScriptProxy** object is registered.
## 17100009 Zoom Operation Failure
**Error Message**
Cannot zoom in or zoom out.
**Description**
This error code is reported when the page cannot be zoomed in or out.
**Possible Causes**
The zoom ratio has reached its maximum or minimum.
**Solution**
Check whether the zoom ratio has reached its maximum or minimum.
## 17100010 Failure to Send Messages Through a Port
**Error Message**
Cannot post message using this port.
**Description**
This error code is reported when the current port cannot be used to send messages.
**Possible Causes**
The local or remote port is closed.
**Solution**
1. Make sure the local port is open.
2. Make sure an **onMessageEvent** callback is registered for the remote port.
## 17100011 Invalid Origin
**Error Message**
Invalid origin.
**Description**
This error code is reported when the input parameter **origin** is invalid.
**Possible Causes**
1. The **origin** parameter is empty.
2. The **origin** value is invalid.
**Solution**
Make sure the **origin** value is valid.
## 17100012 No Web Storage Origin
**Error Message**
Invalid web storage origin.
**Description**
This error code is reported when no web storage origin is available.
**Possible Causes**
The related JS database API is not used.
**Solution**
1. Check whether the JS database API is used.
2. If the JS database API is used, find out the failure cause, for example, check whether **databaseAccess** is enabled.
......@@ -14,10 +14,10 @@ This error code is reported when the source file passed in the **compress** or *
When the **compress** API is called, the file to compress does not exist. When the **decompress** API is called, the file to decompress does not exist.
**Procedure**
**Solution**
1. Check whether the source file exists.
2. Check whether the path of the source file exists and whether the path is the correct sandbox path.
1. Make sure the source file exists.
2. Make sure the path of the source file exists and the path is the correct sandbox path.
## 900002 Invalid Destination File
......@@ -34,7 +34,7 @@ This error code is reported when the destination file passed in the **compress**
1. When the **compress** API is called, the passed destination file path is invalid, for example, a non-exist sandbox path.
2. When the **decompress** API is called, the destination folder does not exist.
**Procedure**
**Solution**
1. Check whether the destination file path is correct. If not, enter the correct sandbox path.
2. Check whether the destination folder exists. If not, create the folder.
......@@ -173,7 +173,7 @@ The following examples are not intended as copy-paste-ready. Further customizati
"clickOneDay": {
"action": "router",
"bundleName": "com.example.calendar",
"abilityName": "com.example.calendar.MainAbility",
"abilityName": "EntryAbility",
"params": {
"action": "click_month_view_event",
"day": "$event.day",
......
......@@ -55,5 +55,5 @@ You can set universal styles for components in the **style** attribute or **.css
| image-fill | &lt;color&gt; | - | Fill color for SVG images. The following components (and attributes) are supported: **button** (**icon** attribute) and **image** (**src** attribute).<br>The **fill** color value in the SVG image file is replaced with the value of **image-fill** during rendering, and is valid only for the fill attribute that is declared in the SVG image.|
| clip-path | [ &lt;geometry-box&gt; \|&lt;basic-shape&gt; ] \| none | - | Clip area of the component. Only the content within this area is displayed.<br>**\<geometry-box>**: applicable scope of the clip area's width and height. The default value is **border-box**. Available values are as follows:<br>- **margin-box**: The width and height includes the margin.<br>- **border-box**: The width and height includes the border.<br>- **padding-box**: The width and height includes the padding.<br>- **content-box**: The width and height does not include any margin, border, or padding.<br>**\<basic-shape>**: shape of the clip area. Available values include:<br>- **inset**, in the format of inset( &lt;percentage&gt;{1,4} [ round &lt;'border-radius'&gt; ]? )<br>- **circle**, in the format of circle( [ &lt;percentage&gt; ]? [ at &lt;percentage&gt; &lt;percentage&gt; ]? )<br>- **ellipse**, in the format of ellipse( [ &lt;percentage&gt;{2} ]? [ at &lt;percentage&gt; &lt;percentage&gt; ]? )<br>- **polygon**, in the format of polygon( [ &lt;percentage&gt; &lt;percentage&gt; ]\# )<br>- **path**, in the format of path( &lt;string&gt; )|
| mask-image | - &lt;linear-gradient&gt;<br>- string | - | Image used for the mask of the component:<br>Gradient color mask, for example, **linear-gradient(to left, black, white)**.<br>Solid color mask, for example, **linear-gradient(to right, grey , grey)**.<br>Mask filled by a local SVG image, for example, **url(common/mask.svg)**|
| mask-size | - string<br>- &lt;length&gt;&lt;length&gt;<br>- &lt;percentage&gt; &lt;percentage&gt; | auto | Display size of the mask image. The setting is valid only when **mask-image** is set to an image source.<br>The **string** values are as follows:<br>- **contain**: extends the image to the maximum size so that its height and width are fully applicable to the content area.<br>- **cover**: extends the image to a large enough size so that it completely covers the background area. Some parts of the image may not be displayed in the background area.<br>- **auto**: retains the original aspect ratio of the image.<br>The two **\<length>** values are as follows: The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.<br>The two **<percentage>** values indicate the image size in relative to the original image size. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.|
| mask-size | - string<br>- &lt;length&gt;&lt;length&gt;<br>- &lt;percentage&gt; &lt;percentage&gt; | auto | Display size of the mask image. The setting is valid only when **mask-image** is set to an image source.<br>The **string** values are as follows:<br>- **contain**: extends the image to the maximum size so that its height and width are fully applicable to the content area.<br>- **cover**: extends the image to a large enough size so that it completely covers the background area. Some parts of the image may not be displayed in the background area.<br>- **auto**: retains the original aspect ratio of the image.<br>The two **\<length>** values are as follows: The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default.<br>The two **\<percentage>** values indicate the image size in relative to the original image size. The first value indicates the width, and the second value indicates the height. If you only set one value, the other value is set to **auto** by default. |
| mask-position | - string string<br>- &lt;length&gt; &lt;length&gt;<br>- &lt;percentage&gt; &lt;percentage&gt; | 0px 0px | Display position of the mask image. The setting is valid only when **mask-image** is set to an image source. Using keywords: If only one keyword is specified, the other value is **center** by default. The two values define the horizontal position and vertical position, respectively.<br>The **string** values are as follows:<br>- **left**: leftmost in the horizontal direction.<br>- **right**: rightmost in the horizontal direction.<br>- **top**: top in the vertical direction.<br>- **bottom**: bottom in the vertical direction.<br>- **center**: center position.<br>Using **\<length>**: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is 0 0 in px (**0px 0px**). If only one value is specified, the other one is **50%**.<br>Using **\<percentage>**: The first value indicates the horizontal position, and the second value indicates the vertical position. For the upper left corner, the value is 0% 0%. For the lower right corner, the value is **100% 100%**. If only one value is specified, the other one is **50%**.<br>Using both **\<percentage>** and **\<length>**.|
......@@ -24,7 +24,7 @@ Custom components are existing components encapsulated based on service requirem
| Name| Type| Description|
| -------- | -------- | -------- |
| data | Object | Data model of the page. The name cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**).|
| props | Array/Object | Used for communication between components. This attribute can be transferred to components via **<tag xxxx='value'>**. A **props** name must be in lowercase and cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**). Currently, **props** does not support functions.|
| props | Array/Object | Used for communication between components. This attribute can be transferred to components via **\<tag xxxx='value'>**. A **props** name must be in lowercase and cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**). Currently, **props** does not support functions. |
## Adding a Custom Event
......
......@@ -59,6 +59,6 @@ Application resources can be accessed via an absolute or relative path. In this
## Configuration Files
If you are developing a widget in the FA model, configure the **config.json** file. For details, see [FA Widget Development](../../ability/fa-formability.md#configuring-the-widget-configuration-file).
If you are developing a widget in the FA model, configure the **config.json** file.
If you are developing a widget in the stage model, configure **ExtensionAbility** under **extensionAbilities** in the **module.json5** file. For details, see [Stage Widget Development](../../ability/stage-formextension.md#configuring-the-widget-configuration-file).
If you are developing a widget in the stage model, configure **ExtensionAbility** under **extensionAbilities** in the **module.json5** file.
......@@ -99,10 +99,10 @@ You can also implement redirection to the target application using a **want**, w
| Selector | Type | Default Value | Description |
| ------ | ------ | -------- | ---------------------------------------- |
| action | string | "router" | Event type.<br>- **"router"**: redirection event.<br>- **"message"**: message event.|
| want | [Want](../apis/js-apis-application-Want.md) | - | Information about the target application. For details, see the **want** format. |
| want | [Want](../apis/js-apis-app-ability-want.md) | - | Information about the target application. For details, see the **want** format. |
```json
```json
{
"data": {
"mainAbility": "xxx.xxx.xxx"
......@@ -112,7 +112,7 @@ You can also implement redirection to the target application using a **want**, w
"action": "router",
"want": {
"bundleName": "com.example.myapplication",
"abilityName": "com.example.entry.MainAbility"
"abilityName": "EntryAbility"
}
},
"routerEventName2": {
......@@ -124,9 +124,9 @@ You can also implement redirection to the target application using a **want**, w
}
}
}
```
```
In API version 8, the [featureAbility.getWant](../apis/js-apis-featureAbility.md) API in the **onCreate** method of the **app.js** or **app.ets** file must be called for the **want** parameter to receive related parameters.
In API version 8, the [featureAbility.getWant](../apis/js-apis-ability-featureAbility.md) API in the **onCreate** method of the **app.js** or **app.ets** file must be called for the **want** parameter to receive related parameters.
- Message event properties
......
# SysCap List
# SystemCapability List
SysCap, short for System Capability, refers to a standalone feature in the operating system.
SystemCapability (SysCap in short) refers to a standalone feature in the operating system.
Before using an API for development, you are advised to familiarize yourself with [SysCap](../quick-start/syscap.md), and then consult the following tables to see whether the SysCap set required for the API is supported by the target device type.
Before using an API for development, you are advised to familiarize yourself with [SysCap](syscap.md), and then consult the following tables to see whether the SysCap set required for the API is supported by the target device type.
## SystemCapability.ArkUI.ArkUI.Full
......
# SystemCapability
## Overview
### System Capabilities and APIs
SystemCapability (SysCap in short) refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each SysCap corresponds to a set of APIs, whose availability depends on the support of the target device. Such a set of APIs can be provided in DevEco Studio for association.
![image-20220326064841782](figures/image-20220326064841782.png)
For details about the SysCap sets in OpenHarmony, see [SysCap List](../reference/syscap-list.md).
### Supported SysCap Set, Associated SysCap Set, and Required SysCap Set
The supported SysCap set, associated SysCap set, and required SysCap set are collections of SysCaps.
The supported SysCap set covers the device capabilities, and the required SysCap set covers the application capabilities. If the SysCap set required by application A is a subset of the SysCap set supported by device N, application A can be distributed to device N for installation and running. Otherwise, application A cannot be distributed.
The associated SysCap set covers the system capabilities of associated APIs that DevEco Studio offers during application development.
![image-20220326064913834](figures/image-20220326064913834.png)
### Devices and Supported SysCap Sets
Each device provides a SysCap set that matches its hardware capability.
The SDK classifies devices into general devices and custom devices. The general devices' supported SysCap set is defined by OpenHarmony, and the custom devices' is defined by device vendors.
![image-20220326064955505](figures/image-20220326064955505.png)
### Mapping Between Devices and SDK Capabilities
The SDK provides a full set of APIs for DevEco Studio. DevEco Studio identifies the supported SysCap set based on the devices selected for the project, filters the APIs contained in the SysCap set, and provides the supported APIs for association (to autocomplete input).
![image-20220326065043006](figures/image-20220326065043006.png)
## How to Develop
### Obtaining the PCID
The Product Compatibility ID (PCID) contains the SysCap information supported by the current device. For the moment, you can obtain the PCID of a device from the device vendor. In the future, you'll be able to obtain the PCIDs of all devices from the authentication center, which is in development.
### Importing the PCID
DevEco Studio allows Product Compatibility ID (PCID) imports for projects. After the imported PCID file is decoded, the SysCap is output and written into the **syscap.json** file.
Right-click the project directory and choose **Import Product Compatibility ID** from the shortcut menu to upload the PCID file and import it to the **syscap.json** file.
![20220329-103626](figures/20220329-103626.gif)
### Configuring the Associated SysCap Set and Required SysCap Set
DevEco Studio automatically configures the associated SysCap set and required SysCap set based on the settings supported by the created project. You can modify these SysCap sets when necessary.
You can add APIs to the associated SysCap set in DevEco Studio by adding system capabilities. However, note that these APIs may not be supported on the device. Therefore, check whether these APIs are supported before using them.
Exercise caution when modifying the required SysCap set. Incorrect modifications may result in the application being unable to be distributed to the target device.
```json
// syscap.json
{
"devices": {
"general": [ // General devices. Each general device supports a SysCap set. Multiple general devices can be configured.
"default",
"car"
],
"custom": [ // Custom devices.
{
"Custom device": [
"SystemCapability.Communication.SoftBus.Core"
]
}
]
},
"development": { // The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated SysCap set.
"addedSysCaps": [
"SystemCapability.Location.Location.Lite"
]
},
"production": { // Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices.
"addedSysCaps": [], // Intersection of SysCap sets supported by devices configured in devices. It is the required SysCap set with addedSysCaps set and removedSysCaps set.
"removedSysCaps": [] // When the required SysCap set is a capability subset of a device, the application can be distributed to the device.
}
}
```
### Single-Device Application Development
By default, the associated SysCap set and required SysCap set of the application are the same as the supported SysCap set of the device. Exercise caution when modifying the required SysCap set.
![image-20220326065124911](figures/image-20220326065124911.png)
### Cross-Device Application Development
By default, the associated SysCap set of an application is the union of multiple devices' supported SysCap sets, while the required SysCap set is the intersection of the devices' supported SysCap sets.
![image-20220326065201867](figures/image-20220326065201867.png)
### Checking Whether an API Is Available
- Method 1: Use the **canIUse** API predefined in OpenHarmony.
```
if (canIUse("SystemCapability.ArkUI.ArkUI.Full")) {
console.log("This application supports SystemCapability.ArkUI.ArkUI.Full.");
} else {
console.log("This application does not support SystemCapability.ArkUI.ArkUI.Full".);
}
```
- Method 2: Import a module using the **import** API. If the current device does not support the module, the import result is **undefined**. Before using an API, you must make sure the API is available.
```
import geolocation from '@ohos.geolocation';
if (geolocation) {
geolocation.getCurrentLocation((location) => {
console.log(location.latitude, location.longitude);
});
} else {
console.log('This device does not support location information.');
}
```
You can also find out the SysCap to which an API belongs by referring to the API reference document.
### Checking the Differences Between Devices with a Specific SysCap
The performance of a SysCap may vary by device type. For example, a tablet is superior to a smart wearable device in terms of the camera capability.
```
import userAuth from '@ohos.userIAM.userAuth';
const authenticator = userAuth.getAuthenticator();
const result = authenticator.checkAbility('FACE_ONLY', 'S1');
if (result == authenticator.CheckAvailabilityResult.AUTH_NOT_SUPPORT) {
console.log('This device does not support facial recognition.');
}
// If an unsupported API is forcibly called, an error message is returned, but no syntax error occurs.
authenticator.execute('FACE_ONLY', 'S1', (err, result) => {
if (err) {
console.log(err.message);
return;
}
})
```
### How Do SysCap Differences Arise Between Devices
The device SysCaps in product solutions vary according to the component combination defined by the product solution vendor. The following figure shows the overall process.
![image-20220326072448840](figures/image-20220326072448840.png)
1. A set of OpenHarmony source code consists of optional and mandatory components. Different components represent different SysCaps.
2. In a normalized released SDK, APIs are mapped to SysCap sets.
3. Product solution vendors can assemble components based on hardware capabilities and product requirements.
4. The components configured for a product can be OpenHarmony components or proprietary components developed by a third party. Since there is mapping between components and SysCap, the SysCap set of the product can be obtained after all components are assembled.
5. The SysCap set is encoded to generate the PCID. You can import the PCID to DevEco Studio and decode it into SysCaps. During development, compatibility processing is performed to mitigate the SysCap differences of devices.
6. System parameters deployed on devices contain the SysCap set. The system provides native interfaces and application interfaces for components and applications to check whether a specific SysCap is available.
7. During application development, the SysCap set required by the application is encoded into the Required Product Compatibility ID (RPCID) and written into the application installation package. During application installation, the package manager decodes the RPCID to obtain the SysCap set required by the application and compares it with the SysCap set supported by the device. If the SysCap set required by the application is met, the application can be installed on the device.
8. When an application is running on a device, the **canIUse** API can be used to query whether the device is compatible with a specific SysCap.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册