提交 ff4e4cb9 编写于 作者: 王江颖 提交者: Gitee

Merge branch 'OpenHarmony-3.1-Release' of gitee.com:openharmony/docs into OpenHarmony-3.1-Release

Signed-off-by: N王江颖 <wangjiangying@huawei.com>
......@@ -7,16 +7,15 @@
- [OpenHarmony Release Notes](../release-notes/Readme.md)
- Quick Start
- Getting Started
- [Preparations](quick-start/start-overview.md)
- [Getting Started with eTS in the Traditional Coding Approach](quick-start/start-with-ets.md)
- [Getting Started with eTS in the Low-Code Approach](quick-start/start-with-ets-low-code.md)
- [Getting Started with JavaScript in the Traditional Coding Approach](quick-start/start-with-js.md)
- [Getting Started with JavaScript in the Low-Code Approach](quick-start/start-with-js-low-code.md)
- [Preparations](quick-start/start-overview.md)
- [Getting Started with eTS in the Traditional Coding Approach](quick-start/start-with-ets.md)
- [Getting Started with eTS in the Low-Code Approach](quick-start/start-with-ets-low-code.md)
- [Getting Started with JavaScript in the Traditional Coding Approach](quick-start/start-with-js.md)
- [Getting Started with JavaScript in the Low-Code Approach](quick-start/start-with-js-low-code.md)
- Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md)
- [Resource File Categories](quick-start/basic-resource-file-categories.md)
- [SysCap](quick-start/syscap.md)
- [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md)
- [SysCap](quick-start/syscap.md)
- Development
- [Ability Development](ability/Readme-EN.md)
- [UI Development](ui/Readme-EN.md)
......@@ -33,20 +32,16 @@
- [Device Usage Statistics](device-usage-statistics/Readme-EN.md)
- [DFX](dfx/Readme-EN.md)
- [Internationalization](internationalization/Readme-EN.md)
- [Native APIs](napi/Readme-EN.md)
- [Using Native APIs in Application Projects](napi/Readme-EN.md)
- Tools
- [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md)
- Hands-On Tutorials
- [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md)
- [Codelabs](https://gitee.com/openharmony/codelabs/blob/master)
- [Codelabs](https://gitee.com/openharmony/codelabs)
- API References
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- APIs
- [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs
- [Standard Libraries](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md)
- [JS and TS APIs](reference/apis/Readme-EN.md)
- Contribution
- [How to Contribute](../contribute/documentation-contribution.md)
......@@ -6,10 +6,7 @@
- [Getting Started with eTS in the Low-Code Approach](start-with-ets-low-code.md)
- [Getting Started with JavaScript in the Traditional Coding Approach](start-with-js.md)
- [Getting Started with JavaScript in the Low-Code Approach](start-with-js-low-code.md)
- Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](stage-structure.md)
- [Resource File Categories](basic-resource-file-categories.md)
- [SysCap](syscap.md)
......@@ -99,50 +99,6 @@ Example of the **module.json** file:
"resource": "$profile:config_file2"
}
],
"metadata": [
{
"name": "string",
"value": "string",
"resource": "$profile:config_file1"
},
{
"name": "string",
"value": "string",
"resource": "$profile:config_file2"
}
],
"abilities": [
{
"name": "MainAbility",
"srcEntrance" : "./login/MyMainAbility.ts",
"description": "$string:description_main_ability",
"icon": "$media:icon",
"label": "HiMusic",
"visible": true,
"skills": [
{
"actions": [
"action.system.home"
],
"entities": [
"entity.system.home"
],
"uris": [ ]
}
],
"backgroundModes": [
"dataTransfer",
"audioPlayback",
"audioRecording",
"location",
"bluetoothInteraction",
"multiDeviceConnection",
"wifiInteraction",
"voip",
"taskKeeping"
],
}
],
"abilities": [
{
"name": "MainAbility",
......
# JavaScript-based Web-like Development Paradigm
- Components
- Common
- [Universal Attributes](js-components-common-attributes.md)
- [Universal Styles](js-components-common-styles.md)
- [Universal Events](js-components-common-events.md)
- [Universal Methods](js-components-common-methods.md)
- [Animation Styles](js-components-common-animation.md)
- [Gradient Styles](js-components-common-gradient.md)
- [Transition Styles](js-components-common-transition.md)
- [Media Query](js-components-common-mediaquery.md)
- [Custom Font Styles](js-components-common-customizing-font.md)
- [Atomic Layout](js-components-common-atomic-layout.md)
- Universal Component Information
- [Universal Attributes](js-components-common-attributes.md)
- [Universal Styles](js-components-common-styles.md)
- [Universal Events](js-components-common-events.md)
- [Universal Methods](js-components-common-methods.md)
- [Animation Styles](js-components-common-animation.md)
- [Gradient Styles](js-components-common-gradient.md)
- [Transition Styles](js-components-common-transition.md)
- [Media Query](js-components-common-mediaquery.md)
- [Custom Font Styles](js-components-common-customizing-font.md)
- [Atomic Layout](js-components-common-atomic-layout.md)
- Container Components
- [badge](js-components-container-badge.md)
- [dialog](js-components-container-dialog.md)
- [div](js-components-container-div.md)
- [form](js-components-container-form.md)
- [list](js-components-container-list.md)
- [list-item](js-components-container-list-item.md)
- [list-item-group](js-components-container-list-item-group.md)
- [panel](js-components-container-panel.md)
- [popup](js-components-container-popup.md)
- [refresh](js-components-container-refresh.md)
- [stack](js-components-container-stack.md)
- [stepper](js-components-container-stepper.md)
- [stepper-item](js-components-container-stepper-item.md)
- [swiper](js-components-container-swiper.md)
- [tabs](js-components-container-tabs.md)
- [tab-bar](js-components-container-tab-bar.md)
- [tab-content](js-components-container-tab-content.md)
- Basic Components
- [button](js-components-basic-button.md)
- [chart](js-components-basic-chart.md)
- [divider](js-components-basic-divider.md)
- [image](js-components-basic-image.md)
- [image-animator](js-components-basic-image-animator.md)
- [input](js-components-basic-input.md)
- [label](js-components-basic-label.md)
- [marquee](js-components-basic-marquee.md)
- [menu](js-components-basic-menu.md)
- [option](js-components-basic-option.md)
- [picker](js-components-basic-picker.md)
- [picker-view](js-components-basic-picker-view.md)
- [piece](js-components-basic-piece.md)
- [progress](js-components-basic-progress.md)
- [qrcode](js-components-basic-qrcode.md)
- [rating](js-components-basic-rating.md)
- [richtext](js-components-basic-richtext.md)
- [search](js-components-basic-search.md)
- [select](js-components-basic-select.md)
- [slider](js-components-basic-slider.md)
- [span](js-components-basic-span.md)
- [switch](js-components-basic-switch.md)
- [text](js-components-basic-text.md)
- [textarea](js-components-basic-textarea.md)
- [toolbar](js-components-basic-toolbar.md)
- [toolbar-item](js-components-basic-toolbar-item.md)
- [toggle](js-components-basic-toggle.md)
- [web](js-components-basic-web.md)
- Media Components
- [video](js-components-media-video.md)
- Canvas Components
- [canvas](js-components-canvas-canvas.md)
- [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md)
- [Image](js-components-canvas-image.md)
- [CanvasGradient](js-components-canvas-canvasgradient.md)
- [ImageData](js-components-canvas-imagedata.md)
- [Path2D](js-components-canvas-path2d.md)
- [ImageBitmap](js-components-canvas-imagebitmap.md)
- [OffscreenCanvas](js-components-canvas-offscreencanvas.md)
- [OffscreenCanvasRenderingContext2D](js-offscreencanvasrenderingcontext2d.md)
- Grid Components
- [Basic Concepts](js-components-grid-basic-concepts.md)
- [grid-container](js-components-grid-container.md)
- [grid-row](js-components-grid-row.md)
- [grid-col](js-components-grid-col.md)
- SVG Components
- [Universal Attributes](js-components-svg-common-attributes.md)
- [svg](js-components-svg.md)
- [rect](js-components-svg-rect.md)
- [circle](js-components-svg-circle.md)
- [ellipse](js-components-svg-ellipse.md)
- [path](js-components-svg-path.md)
- [line](js-components-svg-line.md)
- [polyline](js-components-svg-polyline.md)
- [polygon](js-components-svg-polygon.md)
- [text](js-components-svg-text.md)
- [tspan](js-components-svg-tspan.md)
- [textPath](js-components-svg-textpath.md)
- [animate](js-components-svg-animate.md)
- [animateMotion](js-components-svg-animatemotion.md)
- [animateTransform](js-components-svg-animatetransform.md)
- Container Component
- [badge](js-components-container-badge.md)
- [dialog](js-components-container-dialog.md)
- [div](js-components-container-div.md)
- [form](js-components-container-form.md)
- [list](js-components-container-list.md)
- [list-item](js-components-container-list-item.md)
- [list-item-group](js-components-container-list-item-group.md)
- [panel](js-components-container-panel.md)
- [popup](js-components-container-popup.md)
- [refresh](js-components-container-refresh.md)
- [stack](js-components-container-stack.md)
- [stepper](js-components-container-stepper.md)
- [stepper-item](js-components-container-stepper-item.md)
- [swiper](js-components-container-swiper.md)
- [tabs](js-components-container-tabs.md)
- [tab-bar](js-components-container-tab-bar.md)
- [tab-content](js-components-container-tab-content.md)
- Basic Components
- [button](js-components-basic-button.md)
- [chart](js-components-basic-chart.md)
- [divider](js-components-basic-divider.md)
- [image](js-components-basic-image.md)
- [image-animator](js-components-basic-image-animator.md)
- [input](js-components-basic-input.md)
- [label](js-components-basic-label.md)
- [marquee](js-components-basic-marquee.md)
- [menu](js-components-basic-menu.md)
- [option](js-components-basic-option.md)
- [picker](js-components-basic-picker.md)
- [picker-view](js-components-basic-picker-view.md)
- [piece](js-components-basic-piece.md)
- [progress](js-components-basic-progress.md)
- [qrcode](js-components-basic-qrcode.md)
- [rating](js-components-basic-rating.md)
- [richtext](js-components-basic-richtext.md)
- [search](js-components-basic-search.md)
- [select](js-components-basic-select.md)
- [slider](js-components-basic-slider.md)
- [span](js-components-basic-span.md)
- [switch](js-components-basic-switch.md)
- [text](js-components-basic-text.md)
- [textarea](js-components-basic-textarea.md)
- [toolbar](js-components-basic-toolbar.md)
- [toolbar-item](js-components-basic-toolbar-item.md)
- [toggle](js-components-basic-toggle.md)
- [web](js-components-basic-web.md)
- Media Components
- [video](js-components-media-video.md)
- Canvas Components
- [canvas](js-components-canvas-canvas.md)
- [CanvasRenderingContext2D](js-components-canvas-canvasrenderingcontext2d.md)
- [Image](js-components-canvas-image.md)
- [CanvasGradient](js-components-canvas-canvasgradient.md)
- [ImageData](js-components-canvas-imagedata.md)
- [Path2D](js-components-canvas-path2d.md)
- [ImageBitmap](js-components-canvas-imagebitmap.md)
- [OffscreenCanvas](js-components-canvas-offscreencanvas.md)
- [OffscreenCanvasRenderingContext2D](js-offscreencanvasrenderingcontext2d.md)
- Grid
- [Basic Concepts](js-components-grid-basic-concepts.md)
- [grid-container](js-components-grid-container.md)
- [grid-row](js-components-grid-row.md)
- [grid-col](js-components-grid-col.md)
- SVG Components
- [Universal Attributes](js-components-svg-common-attributes.md)
- [svg](js-components-svg.md)
- [rect](js-components-svg-rect.md)
- [circle](js-components-svg-circle.md)
- [ellipse](js-components-svg-ellipse.md)
- [path](js-components-svg-path.md)
- [line](js-components-svg-line.md)
- [polyline](js-components-svg-polyline.md)
- [polygon](js-components-svg-polygon.md)
- [text](js-components-svg-text.md)
- [tspan](js-components-svg-tspan.md)
- [textPath](js-components-svg-textpath.md)
- [animate](js-components-svg-animate.md)
- [animateMotion](js-components-svg-animatemotion.md)
- [animateTransform](js-components-svg-animatetransform.md)
- Custom Components
- [Basic Usage](js-components-custom-basic-usage.md)
- [Custom Events](js-components-custom-events.md)
- [props](js-components-custom-props.md)
- [Event Parameter](js-components-custom-event-parameter.md)
- [slot](js-components-custom-slot.md)
- [Lifecycle Definition](js-components-custom-lifecycle.md)
- [Type Attributes](js-appendix-types.md)
- [Basic Usage](js-components-custom-basic-usage.md)
- [Custom Events](js-components-custom-events.md)
- [props](js-components-custom-props.md)
- [Event Parameter](js-components-custom-event-parameter.md)
- [slot](js-components-custom-slot.md)
- [Lifecycle Definition](js-components-custom-lifecycle.md)
- [Data Type Attributes](js-appendix-types.md)
# Transition Styles
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** Supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
> **NOTE**
>
> Supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version.
## Transition of Shared Elements
### Attributes
| Name | Type | Default Value | Description |
| ------- | ------ | ------------- | ------------------------------------------------------------ |
| shareid | string | - | Used for the transition of shared elements and takes effect only when it is configured.**list-item**, **image**, **text**, **button**, and **label** components are supported for the transition of shared elements. |
| 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. |
### Styles
| Name | Type | Default Value | Description |
| --------------------------------- | ------ | ------------- | ------------------------------------------------------------ |
| 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. |
| 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-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.|
### Important Notes
1. If the shared element transition style and custom page transition style are both configured, the latter is used.
2. The exchange effect of shared elements is similar to the transition shown below.
**Figure 1** Default transition effect of shared elements ![en-us_image_0000001238424309](figures/en-us_image_0000001238424309.png)
**Figure 1** Default transition effect of shared elements
![en-us_image_0000001238424309](figures/en-us_image_0000001238424309.png)
3. The animation of a shared element does not take effect for the border and background color of the element.
4. During the transition of a shared element, the page element is hidden. Therefore, the animation style and function set for the page element are invalid.
5. During the dynamic change of **shareid**<sup>5+</sup>, if the **shareid** value in component A is overwritten by that in component B, the shared element effect of component A becomes ineffective and will not be restored even if the **shareid** value is changed in component B.
1. The animation of a shared element does not take effect for the border and background color of the element.
2. During the transition of a shared element, the page element is hidden. Therefore, the animation style and function set for the page element are invalid.
3. During the dynamic change of **shareid**<sup>5+</sup>, if the **shareid** value in component A is overwritten by that in component B, the shared element effect of component A becomes ineffective and will not be restored even if the **shareid** value is changed in component B.
### Example
In the example below, where **PageA** jumps to **PageB**, the shared element is **image**, and the **shareid** is "shareImage".
```
```html
<!-- PageA -->
<!-- xxx.hml -->
<div>
<list>
<list-item type="description">
<image src="item.jpg" shareid="shareImage" onclick="jump" class="shared-transition-style"></image>
<text onclick="jump">Click on picture to Jump to ths details</text>
</list-item>
<list-item>
<text onclick="jump">Click on picture to Jump to the details</text>
</list-item>
</list>
</div>
```
```js
// xxx.js
import router from '@system.router';
export default {
jump() {
router.push({
uri: 'detailpage',
// The path must be the same as that in the config.json file.
uri: 'pages/detailpage',
});
},
}
```
```css
/* xxx.css */
.shared-transition-style {
shared-transition-effect: exchange;
......@@ -62,11 +81,17 @@ export default {
from { opacity: 0; }
to { opacity: 1; }
}
```
```html
<!-- PageB -->
<!-- xxx.hml -->
<div>
<image src="itemDetail.jpg" shareid="shareImage" onclick="jumpBack" class="shared-transition-style"></image>
</div>
```
```js
// xxx.js
import router from '@system.router';
export default {
......@@ -74,6 +99,9 @@ export default {
router.back();
},
}
```
```css
/* xxx.css */
.shared-transition-style {
shared-transition-effect: exchange;
......@@ -85,21 +113,26 @@ export default {
}
```
## Card Transition
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** Card transitions are not available when other transitions (including shared element transitions and custom transitions) are used.
## Widget Transition
> **NOTE**
>
> Widget transitions are not available when other transitions (including shared element transitions and custom transitions) are used.
### Styles
| Name | Type | Default Value | Description |
| ----------------- | ------ | ------------- | ------------------------------------------------------------ |
| transition-effect | string | - | Whether a component on the current page displays the transition effect during a card transition. Available values are as follows: - **unfold**: The component will move upwards by one card height if the component is located above the card tapped by the user, or move downwards by one card height if the component is located below the card. - **none**: No transition effect is displayed. |
| 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. |
### Example
The **source_page** has a title area on the top and a card list. Users can tap a card to switch to the **target_page**.
The **source_page** has a title area on the top and a widget list. Users can tap a widget to switch to the **target_page**.
```
```html
<!-- source_page -->
<!-- xxx.hml -->
<div class="container">
......@@ -112,6 +145,9 @@ The **source_page** has a title area on the top and a card list. Users can tap a
</list-item>
</list>
</div>
```
```js
// xxx.js
import router from '@system.router'
export default {
......@@ -128,6 +164,9 @@ export default {
router.push({ uri: uri, params : { ref : cardId } });
}
}
```
```css
/* xxx.css */
.container {
flex-direction: column;
......@@ -145,6 +184,9 @@ export default {
align-items: flex-end;
transition-effect: unfold;
}
```
```html
<!-- target_page -->
<!-- xxx.hml -->
<div class="container">
......@@ -152,6 +194,9 @@ export default {
<text style="font-size: 30px">this is detail</text>
</div>
</div>
```
```css
/* xxx.css */
.container {
flex-direction: column;
......@@ -168,16 +213,19 @@ export default {
![en-us_image_0000001193544358](figures/en-us_image_0000001193544358.gif)
## Page Transition Styles
## Page Transition
### Styles
| Name | Type | Default Value | Description |
| -------------------------- | ------ | ------------------------------------------------------ | ------------------------------------------------------------ |
| transition-enter | string | - | Works with **@keyframes** and supports transform and opacity animations. For details, see [Attributes available for the @keyframes rule](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](js-components-common-animation.md). |
| Name | Type | Default Value | Description |
| -------------------------- | ------ | ------------- | ---------------------------------------- |
| 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-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](js-components-common-animation.md). |
| 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).|
### Important Notes
......@@ -187,9 +235,11 @@ export default {
3. Notes on the **transition-enter** and **transition-exit** styles:
a. In the push scenario, the animation defined by **transition-enter** is used for entering the **Page2.js** in the page stack; the animation defined by **transition-exit** is used for entering the **Page1.js** in the page stack. ![en-us_image_0000001193704354](figures/en-us_image_0000001193704354.png)
a. In the push scenario, the animation defined by **transition-enter** is used for entering the **Page2.js** in the page stack; the animation defined by **transition-exit** is used for entering the **Page1.js** in the page stack.
![en-us_image_0000001193704354](figures/en-us_image_0000001193704354.png)
b. In the back scenario, the animation defined by **transition-enter** is used for exiting the **Page2.js** in the page stack, with the animation played in reverse sequence; the animation defined by **transition-exit** is used for exiting the **Page1.js** in the page stack, with the animation played in reverse sequence. ![en-us_image_0000001238184345](figures/en-us_image_0000001238184345.png)
b. In the back scenario, the animation defined by **transition-enter** is used for exiting the **Page2.js** in the page stack, with the animation played in reverse sequence; the animation defined by **transition-exit** is used for exiting the **Page1.js** in the page stack, with the animation played in reverse sequence.
![en-us_image_0000001238184345](figures/en-us_image_0000001238184345.png)
### Example
......@@ -197,7 +247,7 @@ export default {
1. Page1
```
```html
<!-- xxx.hml -->
<div class="container">
<text>index</text>
......@@ -205,12 +255,12 @@ export default {
</div>
```
```
<!-- xxx.js -->
```css
// xxx.js
import router from '@system.router';
export default {
data: {
},
jump() {
router.push({
......@@ -220,8 +270,8 @@ export default {
}
```
```
<!-- xxx.css -->
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
......@@ -238,13 +288,13 @@ export default {
transition-duration: 5s;
transition-timing-function: friction;
}
@keyframes go_page {
from {
opacity: 0;
transform: translate(0px) rotate(60deg) scale(1.0);
}
to {
opacity: 1;
transform: translate(100px) rotate(360deg) scale(1.0);
......@@ -255,7 +305,7 @@ export default {
opacity: 1;
transform: translate(200px) rotate(60deg) scale(2);
}
to {
opacity: 0;
transform: translate(200px) rotate(360deg) scale(2);
......@@ -263,9 +313,10 @@ export default {
}
```
2. Page2
```
```html
<!-- xxx.hml -->
<div class="container">
<text>transition</text>
......@@ -273,12 +324,12 @@ export default {
</div
```
```
<!-- xxx.js -->
```js
// xxx.js
import router from '@system.router';
export default {
data: {
},
jumpBack() {
router.back()
......@@ -286,8 +337,8 @@ export default {
}
```
```
<!-- xxx.css -->
```css
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
......@@ -295,7 +346,7 @@ export default {
width: 100%;
height: 100%;
}
.move_page {
width: 100px;
height: 100px;
......@@ -305,7 +356,7 @@ export default {
transition-duration: 5s;
transition-timing-function: ease;
}
@keyframes go_page {
from {
opacity: 0;
......@@ -316,7 +367,7 @@ export default {
transform:translate(100px) rotate(180deg) scale(2.0);
}
}
@keyframes exit_page {
from {
opacity: 1;
......@@ -329,4 +380,4 @@ export default {
}
```
![transition](figures/transition.gif)
\ No newline at end of file
![transition](figures/transition.gif)
# TypeScript-based Declarative Development Paradigm
- Components
- Universal Components
- Universal Events
- [Click Event](ts-universal-events-click.md)
- [Touch Event](ts-universal-events-touch.md)
- [Show/Hide Event](ts-universal-events-show-hide.md)
- [Drag/Drop Event](ts-universal-events-drag-drop.md)
- [Key Event](ts-universal-events-key.md)
- [Focus Event](ts-universal-focus-event.md)
- [Mouse Event](ts-universal-mouse-key.md)
- [Component Area Change Event](ts-universal-component-area-change-event.md)
- Universal Attributes
- [Size](ts-universal-attributes-size.md)
- [Location](ts-universal-attributes-location.md)
- [Layout Constraints](ts-universal-attributes-layout-constraints.md)
- [Flex Layout](ts-universal-attributes-flex-layout.md)
- [Border](ts-universal-attributes-border.md)
- [Background](ts-universal-attributes-background.md)
- [Opacity](ts-universal-attributes-opacity.md)
- [Visibility](ts-universal-attributes-visibility.md)
- [Enable/Disable](ts-universal-attributes-enable.md)
- [Overlay](ts-universal-attributes-overlay.md)
- [Z-order Control](ts-universal-attributes-z-order.md)
- [Transformation](ts-universal-attributes-transformation.md)
- [Image Effect Configuration](ts-universal-attributes-image-effect.md)
- [Shape Clipping](ts-universal-attributes-sharp-clipping.md)
- [Text Style](ts-universal-attributes-text-style.md)
- [Grid](ts-universal-attributes-grid.md)
- [Gradient Color](ts-universal-attributes-gradient-color.md)
- [Popup Control](ts-universal-attributes-popup.md)
- [Menu Control](ts-universal-attributes-menu.md)
- [Click Control](ts-universal-attributes-click.md)
- [Focus Control](ts-universal-attributes-focus.md)
- [Hover Effect](ts-universal-attributes-hover-effect.md)
- [Component ID](ts-universal-attributes-component-id.md)
- [Touch Target](ts-universal-attributes-touch-target.md)
- [Polymorphic Style](ts-universal-attributes-polymorphic-style.md)
- Gesture Processing
- [Gesture Binding Methods](ts-gesture-settings.md)
- Basic Gestures
- [TapGesture](ts-basic-gestures-tapgesture.md)
- [LongPressGesture](ts-basic-gestures-longpressgesture.md)
- [PanGesture](ts-basic-gestures-pangesture.md)
- [PinchGesture](ts-basic-gestures-pinchgesture.md)
- [RotationGesture](ts-basic-gestures-rotationgesture.md)
- [SwipeGesture](ts-basic-gestures-swipegesture.md)
- [Combined Gestures](ts-combined-gestures.md)
- Basic Components
- [Blank](ts-basic-components-blank.md)
- [Button](ts-basic-components-button.md)
- [Checkbox](ts-basic-components-checkbox.md)
- [CheckboxGroup](ts-basic-components-checkboxgroup.md)
- [DataPanel](ts-basic-components-datapanel.md)
- [DatePicker](ts-basic-components-datepicker.md)
- [Divider](ts-basic-components-divider.md)
- [Gauge](ts-basic-components-gauge.md)
- [Image](ts-basic-components-image.md)
- [ImageAnimator](ts-basic-components-imageanimator.md)
- [LoadingProgress](ts-basic-components-loadingprogress.md)
- [Marquee](ts-basic-components-marquee.md)
- [Navigation](ts-basic-components-navigation.md)
- [Progress](ts-basic-components-progress.md)
- [QRCode](ts-basic-components-qrcode.md)
- [Radio](ts-basic-components-radio.md)
- [Rating](ts-basic-components-rating.md)
- [RichText](ts-basic-components-richtext.md)
- [ScrollBar](ts-basic-components-scrollbar.md)
- [Search](ts-basic-components-search.md)
- [Select](ts-basic-components-select.md)
- [Slider](ts-basic-components-slider.md)
- [Span](ts-basic-components-span.md)
- [Stepper](ts-basic-components-stepper.md)
- [StepperItem](ts-basic-components-stepperitem.md)
- [Text](ts-basic-components-text.md)
- [TextArea](ts-basic-components-textarea.md)
- [TextClock](ts-basic-components-textclock.md)
- [TextInput](ts-basic-components-textinput.md)
- [TextPicker](ts-basic-components-textpicker.md)
- [TextTimer](ts-basic-components-texttimer.md)
- [TimePicker](ts-basic-components-timepicker.md)
- [Toggle](ts-basic-components-toggle.md)
- [Web](ts-basic-components-web.md)
- [Xcomponent](ts-basic-components-xcomponent.md)
- Container Components
- [AlphabetIndexer](ts-container-alphabet-indexer.md)
- [Badge](ts-container-badge.md)
- [Column](ts-container-column.md)
- [ColumnSplit](ts-container-columnsplit.md)
- [Counter](ts-container-counter.md)
- [Flex](ts-container-flex.md)
- [GridContainer](ts-container-gridcontainer.md)
- [Grid](ts-container-grid.md)
- [GridItem](ts-container-griditem.md)
- [List](ts-container-list.md)
- [ListItem](ts-container-listitem.md)
- [Navigator](ts-container-navigator.md)
- [Panel](ts-container-panel.md)
- [Refresh](ts-container-refresh.md)
- [Row](ts-container-row.md)
- [RowSplit](ts-container-rowsplit.md)
- [Scroll](ts-container-scroll.md)
- [SideBarContainer](ts-container-sidebarcontainer.md)
- [Stack](ts-container-stack.md)
- [Swiper](ts-container-swiper.md)
- [Tabs](ts-container-tabs.md)
- [TabContent](ts-container-tabcontent.md)
- Media Components
- [Video](ts-media-components-video.md)
- Drawing Components
- [Circle](ts-drawing-components-circle.md)
- [Ellipse](ts-drawing-components-ellipse.md)
- [Line](ts-drawing-components-line.md)
- [Polyline](ts-drawing-components-polyline.md)
- [Polygon](ts-drawing-components-polygon.md)
- [Path](ts-drawing-components-path.md)
- [Rect](ts-drawing-components-rect.md)
- [Shape](ts-drawing-components-shape.md)
- Canvas Components
- [Canvas](ts-components-canvas-canvas.md)
- [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md)
- [OffscreenCanvasRenderingConxt2D](ts-offscreencanvasrenderingcontext2d.md)
- [Lottie](ts-components-canvas-lottie.md)
- [Path2D](ts-components-canvas-path2d.md)
- [CanvasGradient](ts-components-canvas-canvasgradient.md)
- [ImageBitmap](ts-components-canvas-imagebitmap.md)
- [ImageData](ts-components-canvas-imagedata.md)
- Universal Component Information
- Universal Events
- [Click Event](ts-universal-events-click.md)
- [Touch Event](ts-universal-events-touch.md)
- [Show/Hide Event](ts-universal-events-show-hide.md)
- [Drag/Drop Event](ts-universal-events-drag-drop.md)
- [Key Event](ts-universal-events-key.md)
- [Focus Event](ts-universal-focus-event.md)
- [Mouse Event](ts-universal-mouse-key.md)
- [Component Area Change Event](ts-universal-component-area-change-event.md)
- [Visible Area Change Event](ts-universal-component-visible-area-change-event.md)
- Universal Attributes
- [Size](ts-universal-attributes-size.md)
- [Location](ts-universal-attributes-location.md)
- [Layout Constraints](ts-universal-attributes-layout-constraints.md)
- [Flex Layout](ts-universal-attributes-flex-layout.md)
- [Border](ts-universal-attributes-border.md)
- [Background](ts-universal-attributes-background.md)
- [Opacity](ts-universal-attributes-opacity.md)
- [Visibility](ts-universal-attributes-visibility.md)
- [Enable/Disable](ts-universal-attributes-enable.md)
- [Overlay](ts-universal-attributes-overlay.md)
- [Z-order Control](ts-universal-attributes-z-order.md)
- [Transformation](ts-universal-attributes-transformation.md)
- [Image Effect Configuration](ts-universal-attributes-image-effect.md)
- [Shape Clipping](ts-universal-attributes-sharp-clipping.md)
- [Text Style](ts-universal-attributes-text-style.md)
- [Grid](ts-universal-attributes-grid.md)
- [Gradient Color](ts-universal-attributes-gradient-color.md)
- [Popup Control](ts-universal-attributes-popup.md)
- [Menu Control](ts-universal-attributes-menu.md)
- [Click Control](ts-universal-attributes-click.md)
- [Focus Control](ts-universal-attributes-focus.md)
- [Hover Effect](ts-universal-attributes-hover-effect.md)
- [Component ID](ts-universal-attributes-component-id.md)
- [Touch Target](ts-universal-attributes-touch-target.md)
- [Polymorphic Style](ts-universal-attributes-polymorphic-style.md)
- Gesture Processing
- [Gesture Binding Methods](ts-gesture-settings.md)
- Basic Gestures
- [TapGesture](ts-basic-gestures-tapgesture.md)
- [LongPressGesture](ts-basic-gestures-longpressgesture.md)
- [PanGesture](ts-basic-gestures-pangesture.md)
- [PinchGesture](ts-basic-gestures-pinchgesture.md)
- [RotationGesture](ts-basic-gestures-rotationgesture.md)
- [SwipeGesture](ts-basic-gestures-swipegesture.md)
- [Combined Gestures](ts-combined-gestures.md)
- Basic Components
- [Blank](ts-basic-components-blank.md)
- [Button](ts-basic-components-button.md)
- [Checkbox](ts-basic-components-checkbox.md)
- [CheckboxGroup](ts-basic-components-checkboxgroup.md)
- [DataPanel](ts-basic-components-datapanel.md)
- [DatePicker](ts-basic-components-datepicker.md)
- [Divider](ts-basic-components-divider.md)
- [Gauge](ts-basic-components-gauge.md)
- [Image](ts-basic-components-image.md)
- [ImageAnimator](ts-basic-components-imageanimator.md)
- [LoadingProgress](ts-basic-components-loadingprogress.md)
- [Marquee](ts-basic-components-marquee.md)
- [Navigation](ts-basic-components-navigation.md)
- [Progress](ts-basic-components-progress.md)
- [QRCode](ts-basic-components-qrcode.md)
- [Radio](ts-basic-components-radio.md)
- [Rating](ts-basic-components-rating.md)
- [RichText](ts-basic-components-richtext.md)
- [ScrollBar](ts-basic-components-scrollbar.md)
- [Search](ts-basic-components-search.md)
- [Select](ts-basic-components-select.md)
- [Slider](ts-basic-components-slider.md)
- [Span](ts-basic-components-span.md)
- [Stepper](ts-basic-components-stepper.md)
- [StepperItem](ts-basic-components-stepperitem.md)
- [Text](ts-basic-components-text.md)
- [TextArea](ts-basic-components-textarea.md)
- [TextClock](ts-basic-components-textclock.md)
- [TextInput](ts-basic-components-textinput.md)
- [TextPicker](ts-basic-components-textpicker.md)
- [TextTimer](ts-basic-components-texttimer.md)
- [TimePicker](ts-basic-components-timepicker.md)
- [Toggle](ts-basic-components-toggle.md)
- [Web](ts-basic-components-web.md)
- [XComponent](ts-basic-components-xcomponent.md)
- Container Components
- [AlphabetIndexer](ts-container-alphabet-indexer.md)
- [Badge](ts-container-badge.md)
- [Column](ts-container-column.md)
- [ColumnSplit](ts-container-columnsplit.md)
- [Counter](ts-container-counter.md)
- [Flex](ts-container-flex.md)
- [GridContainer](ts-container-gridcontainer.md)
- [Grid](ts-container-grid.md)
- [GridItem](ts-container-griditem.md)
- [List](ts-container-list.md)
- [ListItem](ts-container-listitem.md)
- [Navigator](ts-container-navigator.md)
- [Panel](ts-container-panel.md)
- [Refresh](ts-container-refresh.md)
- [Row](ts-container-row.md)
- [RowSplit](ts-container-rowsplit.md)
- [Scroll](ts-container-scroll.md)
- [SideBarContainer](ts-container-sidebarcontainer.md)
- [Stack](ts-container-stack.md)
- [Swiper](ts-container-swiper.md)
- [Tabs](ts-container-tabs.md)
- [TabContent](ts-container-tabcontent.md)
- Media Components
- [Video](ts-media-components-video.md)
- Drawing Components
- [Circle](ts-drawing-components-circle.md)
- [Ellipse](ts-drawing-components-ellipse.md)
- [Line](ts-drawing-components-line.md)
- [Polyline](ts-drawing-components-polyline.md)
- [Polygon](ts-drawing-components-polygon.md)
- [Path](ts-drawing-components-path.md)
- [Rect](ts-drawing-components-rect.md)
- [Shape](ts-drawing-components-shape.md)
- Canvas Components
- [Canvas](ts-components-canvas-canvas.md)
- [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md)
- [OffscreenCanvasRenderingConxt2D](ts-offscreencanvasrenderingcontext2d.md)
- [Lottie](ts-components-canvas-lottie.md)
- [Path2D](ts-components-canvas-path2d.md)
- [CanvasGradient](ts-components-canvas-canvasgradient.md)
- [ImageBitmap](ts-components-canvas-imagebitmap.md)
- [ImageData](ts-components-canvas-imagedata.md)
- Animation
- [AnimatorProperty](ts-animatorproperty.md)
- [Explicit Animation](ts-explicit-animation.md)
......
# Image
The **\<Image>** component is used to render and display local and online images.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Image>** component is used to render and display images.
## Required Permissions
ohos.permission.INTERNET (to use Internet images)
To use online images, you need to add the **ohos.permission.INTERNET** permission to the corresponding abilities in the **config.json** (for the FA model) or **module.json5** file (for the stage model).
```
"abilities": [
{
...
"permissions": ["ohos.permission.INTERNET"],
...
}
]
```
## Child Components
......@@ -22,61 +31,67 @@ Not supported
Image(src: string | PixelMap | Resource)
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| src | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7)\| [Resource](../../ui/ts-types.md#resource-type) | Yes | - | Image address, which can be the address of an Internet or a local image.<br/>When using resources 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/>\- The value can also be a path starting with `dataability://`, which is used to access the image path provided by a Data ability. |
Obtains an image from the specified source for subsequent rendering and display.
**Parameters**
| Name| Type | Mandatory| Default Value| Description |
| ------ | ------------------------------------------------------------ | ---- | ------ | ------------------------------------------------------------ |
| src | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](../../ui/ts-types.md) | Yes | - | Image source. Both local and online images are supported.<br>When using resources 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/>\- The value can also be a path starting with `dataability://`, which is used to access the image path provided by a Data ability. |
## Attributes
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| alt | string \| [Resource](../../ui/ts-types.md#resource-type) | - | Placeholder image displayed during loading. Both local and Internal URIs are supported. |
| objectFit | ImageFit | Cover | Image scale type. |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat-enums) | ImageRepeat.NoRepeat | Whether the image is repeated.<br/>**NOTE**<br/>This attribute is not applicable to SVG images. |
| interpolation | ImageInterpolation | None | Interpolation effect of the image. This attribute is valid only when the image is zoomed in.<br/>**NOTE**<br/>- This attribute is not applicable to SVG images.<br/>- This attribute is not applicable to a **PixelMap** object. |
| renderMode | ImageRenderMode | Original | Rendering mode of the image.<br/>**NOTE**<br/>This attribute is not applicable to SVG images. |
| sourceSize | {<br/>width: number,<br/>height: number<br/>} | - | Decoding size of the image. The original image is decoded into an image of the specified size. If the value is of the number type, the unit px is used.<br/>**NOTE**<br/>This attribute is not applicable to a **PixelMap** object. |
| syncLoad<sup>8+</sup> | boolean | false | Whether to load images synchronously. By default, images are loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed. |
- ImageFit enums
| Name | Description |
| -------- | -------- |
| Cover | The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries. |
| Contain | The image is scaled with its aspect ratio retained for the content to be completely displayed within the display boundaries. |
| Fill | The video content is resized to fill the display area while retaining its aspect ratio. |
| None | The original size is retained. Generally, this enum is used together with the **objectRepeat** attribute. |
| ScaleDown | The image content is displayed with its aspect ratio retained. The size is smaller than or equal to the original size. |
- ImageInterpolation enums
| Name | Description |
| -------- | -------- |
| None | Interpolation image data is not used. |
| High | The interpolation image data is used at the high level. The use of the interpolation image data may affect the image rendering speed. |
| Medium | The interpolation image data is used at the medium level. |
| Low | The interpolation image data is used at the low level. |
- ImageRenderMode enums
| Name | Description |
| -------- | -------- |
| Original | The image is rendered based on the original image, including the color. |
| Template | The image is rendered as a template image, and its color is ignored. |
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
| Name | Type | Default Value | Description |
| --------------------- | ---------------------------------------- | ------------------------ | ---------------------------------------- |
| alt | string \| [Resource](../../ui/ts-types.md) | - | Placeholder image displayed during loading. Both local and Internet URIs are supported. |
| objectFit | ImageFit | Cover | Image scale type. |
| objectRepeat | [ImageRepeat](ts-appendix-enums.md#imagerepeat) | NoRepeat | Whether the image is repeated.<br>**NOTE**<br>This attribute is not applicable to SVG images. |
| interpolation | ImageInterpolation | None | Interpolation effect of the image. This attribute is valid only when the image is zoomed in.<br>**NOTE**<br>This attribute is not applicable to SVG images or **PixelMap** objects. |
| renderMode | ImageRenderMode | Original | Rendering mode of the image.<br>**NOTE**<br>This attribute is not applicable to SVG images. |
| sourceSize | {<br>width: number,<br>height: number<br>} | - | Decoding size of the image. The original image is decoded into an image of the specified size, in px.<br>**NOTE**<br>This attribute is not applicable to **PixelMap** objects. |
| syncLoad<sup>8+</sup> | boolean | false | Whether to load images synchronously. By default, images are loaded asynchronously. During synchronous loading, the UI thread is blocked and the placeholder diagram is not displayed. |
## ImageFit
| Name | Description |
| --------- | -------------------------------- |
| Cover | The image is scaled with its aspect ratio retained for both sides to be greater than or equal to the display boundaries. |
| Contain | The image is scaled with its aspect ratio retained for the content to be completely displayed within the display boundaries. |
| Fill | The image is scaled to fill the display area, and its aspect ratio is not retained. |
| None | The image is displayed in its original size. Generally, this enum is used together with the **objectRepeat** attribute.|
| ScaleDown | The image is displayed with its aspect ratio retained, in a size smaller than or equal to the original size. |
## ImageInterpolation
| Name | Description |
| ------ | ------------------------- |
| None | Interpolation image data is not used. |
| High | The interpolation image data is used at the high level, which may affect the image rendering speed.|
| Medium | The interpolation image data is used at the medium level. |
| Low | The interpolation image data is used at the low level. |
## ImageRenderMode
| Name | Description |
| -------- | --------------------- |
| Original | The image is rendered based on the original image, including the color. |
| Template | The image is rendered as a template image, and its color is ignored.|
## Events
| Name | Description |
| -------- | -------- |
| onComplete(callback: (event?: { width: number, height: number, componentWidth: number, componentHeight: number, loadingStatus: number }) =&gt; void) | Triggered when an image is successfully loaded. The loaded image is returned. |
| onError(callback: (event?: { componentWidth: number, componentHeight: number }) =&gt; void) | An exception occurs during image loading. |
| onFinish(callback: () =&gt; void) | If the source file to be loaded is an SVG image, this callback is invoked when the SVG animation playback is complete. If the animation is an infinite loop, this callback is not triggered. |
| 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.<br>|
| onError(callback: (event?: { componentWidth: number, componentHeight: number }) =&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.<br>|
| 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
## Example
```
```ts
// Image1
@Entry
@Component
......@@ -143,8 +158,7 @@ struct ImageExample1 {
![en-us_image_0000001211898484](figures/en-us_image_0000001211898484.gif)
```
```ts
// Image2
@Entry
@Component
......@@ -165,12 +179,12 @@ struct ImageExample2 {
.border({ width: 1 }).borderStyle(BorderStyle.Dashed)
.overlay('Template', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
}
Text('alt').fontSize(12).fontColor(0xcccccc).width('96%').height(30)
Image('')
.alt($r('app.media.Image_none'))
.width(100).height(100).border({ width: 1 }).borderStyle(BorderStyle.Dashed)
Text('sourceSize').fontSize(12).fontColor(0xcccccc).width('96%')
Row({ space: 50 }) {
Image($r('app.media.img_example'))
......@@ -190,7 +204,7 @@ struct ImageExample2 {
.border({ width: 1 }).borderStyle(BorderStyle.Dashed)
.overlay('w:200 h:200', { align: Alignment.Bottom, offset: { x: 0, y: 20 } })
}
Text('objectRepeat').fontSize(12).fontColor(0xcccccc).width('96%').height(30)
Row({ space: 5 }) {
Image($r('app.media.ic_health_heart'))
......@@ -213,14 +227,13 @@ struct ImageExample2 {
![en-us_image_0000001212058474](figures/en-us_image_0000001212058474.png)
```
```ts
// Image3
@Entry
@Component
struct ImageExample3 {
@State width: number = 0
@State height: number = 0
@State widthValue: number = 0
@State heightValue: number = 0
private on: Resource = $r('app.media.wifi_on')
private off: Resource = $r('app.media.wifi_off')
private on2off: Resource = $r('app.media.wifi_on2off')
......@@ -240,13 +253,13 @@ struct ImageExample3 {
.objectFit(ImageFit.Cover)
.height(180).width(180)
.onComplete((msg: { width: number,height: number }) => {
this.width = msg.width
this.height = msg.height
this.widthValue = msg.width
this.heightValue = msg.height
})
.onError(() => {
console.log('load image fail')
})
.overlay('\nwidth: ' + String(this.width) + ' height: ' + String(this.height), {
.overlay('\nwidth: ' + String(this.widthValue) + ' height: ' + String(this.heightValue), {
align: Alignment.Bottom,
offset: { x: 0, y: 20 }
})
......
# Text
> **NOTE**<br/>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Text>** component is used to display a piece of textual information.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
......@@ -19,12 +19,12 @@ This component can contain the [\<Span>](ts-basic-components-span.md) child comp
## APIs
Text(content?: string)
Text(content?: ResourceStr)
- Parameters
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| content | string | No| '' | Text content. This parameter does not take effect when the child component **\<Span>** is contained.|
| content | [ResourceStr](../../ui/ts-types.md) | No| '' | Text content. This parameter does not take effect when the child component **\<Span>** is contained.|
## Attributes
......@@ -32,53 +32,46 @@ Text(content?: string)
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| textAlign | TextAlign | TextAlign.Start | Text alignment mode of multiple lines of text.|
| textOverflow | {overflow: TextOverflow} | {overflow: TextOverflow.Clip} | Display mode when the text is too long.<br>**NOTE**<br>Text is truncated at the transition between words. To truncate text in the middle of a word, add **\u200B** between characters. |
| maxLines | number | Infinity | Maximum number of lines in the text.|
| lineHeight | Length | - | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.|
| decoration | {<br>type: TextDecorationType,<br>color?: Color<br>} | {<br>type: TextDecorationType.None,<br>color: Color.Black<br>} | Style and color of the text decorative line.|
| baselineOffset | Length | - | Offset of the text baseline.|
| textOverflow | {overflow: TextOverflow} | {overflow: TextOverflow.Clip} | Display mode when the text is too long.<br>**NOTE**<br/>Text is truncated at the transition between words. To truncate text in the middle of a word, add **\u200B** between characters.<br>This attribute must be used with `maxLines` to take effect. |
| maxLines | number | Infinity | Maximum number of lines in the text.<br>**NOTE**<br/><br>By default, text is automatically folded. If this parameter is specified, the text does not exceed the specified number of lines. If there is extra text, you can use `textOverflow` to specify the truncation mode.|
| lineHeight | string \| number \| [Resource](../../ui/ts-types.md) | - | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.|
| decoration | {<br/>type: TextDecorationType,<br/>color? [ResourceColor](../../ui/ts-types.md)<br/>} | {<br/>type: TextDecorationType.None,<br/>color£ºColor.Black<br/>} | Style and color of the text decorative line.|
| baselineOffset | [Length](../../ui/ts-types.md) | - | Offset of the text baseline.|
| textCase | TextCase | TextCase.Normal | Text case.|
| copyOption<sup>9+</sup> | boolean\|CopyOption | false | Whether copy and paste is allowed.|
- TextAlign enums
| Name| Description|
| -------- | -------- |
| Center | The text is center-aligned.|
| Start | The text is aligned with the direction in which the text is written.|
| End | The text is aligned with the opposite direction in which the text is written.|
- TextOverflow enums
| Name| Description|
| -------- | -------- |
| Clip | Extra text is truncated.|
| Ellipsis | An ellipsis (...) is used to represent clipped text.|
| None | No truncation or ellipsis is used for extra-long text.|
- TextDecorationType enums
| Name| Description|
| -------- | -------- |
| Underline | Line under the text.|
| LineThrough | Line through the text.|
| Overline | Line over the text.|
| None | No decorative lines.|
- TextCase enums
| Name | Description |
| --------- | -------------------- |
| Normal | The original case of the text is retained.|
| LowerCase | All letters in the text are in lowercase. |
| UpperCase | All letters in the text are in uppercase. |
- CopyOption<sup>9+</sup> enums
| Name| Description|
| -------- | -------- |
| InApp | Intra-application copy and paste is allowed.|
| LocalDevice | Intra-device copy and paste is allowed.|
| CrossDevice | Cross-device copy and paste is allowed.|
> **NOTE**<br/>
TextAlign enums
| Name| Description|
| -------- | -------- |
| Center | The text is center-aligned.|
| Start | The text is aligned with the direction in which the text is written.|
| End | The text is aligned with the opposite direction in which the text is written.|
## TextOverflow enums
| Name| Description|
| -------- | -------- |
| Clip | Extra text is truncated.|
| Ellipsis | An ellipsis (...) is used to represent clipped text.|
| None | No truncation or ellipsis is used for extra-long text.|
## TextDecorationType enums
| Name| Description|
| -------- | -------- |
| Underline | Line under the text.|
| LineThrough | Line through the text.|
| Overline | Line over the text.|
| None | No decorative lines.|
## TextCase enums
| Name | Description |
| --------- | -------------------- |
| Normal | The original case of the text is retained.|
| LowerCase | All letters in the text are in lowercase. |
| UpperCase | All letters in the text are in uppercase. |
> **NOTE**
>
> If the **\<Text>** component contains both the text and the **\<Span>** child component, only the content in **\<Span>** is displayed.
......
# PinchGesture
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> This gesture is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
......@@ -14,11 +15,12 @@ None
PinchGesture(options?: { fingers?: number, distance?: number })
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| fingers | number | No | 2 | Minimum number of fingers to trigger a pinch. The value ranges from 2 to 5. |
| distance | number | No | 3.0 | Minimum recognition distance, in vp. |
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| fingers | number | No | 2 | Minimum number of fingers to trigger a pinch. The value ranges from 2 to 5. |
| distance | number | No | 3.0 | Minimum recognition distance, in vp. |
## Events
......@@ -30,36 +32,36 @@ PinchGesture(options?: { fingers?: number, distance?: number })
| onActionEnd((event?: GestureEvent) =&gt; void) | Callback invoked when the finger used for a pinch gesture is lift. |
| onActionCancel(event: () =&gt; void) | Callback invoked when a tap cancellation event is received after a pinch gesture is recognized. |
- GestureEvent attributes related to the pinch gesture
| Name | Type | Description |
| -------- | -------- | -------- |
| scale | number | Scale ratio. This attribute is used for the pinch gesture. |
| pinchCenterX | number | X-coordinate of the center of the pinch gesture, in px. |
| pinchCenterY | number | Y-coordinate of the center of the pinch gesture, in px. |
## GestureEvent Attributes Related to the Pinch Gesture
| Name | Type | Description |
| -------- | -------- | -------- |
| scale | number | Scale ratio. This attribute is used for the pinch gesture. |
| pinchCenterX | number | X-coordinate of the center of the pinch gesture, in px. |
| pinchCenterY | number | Y-coordinate of the center of the pinch gesture, in px. |
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct PinchGestureExample {
@State scale: number = 1
@State scaleValue: number = 1
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Text('PinchGesture scale:' + this.scale)
}
.height(100).width(200).padding(20).border({ width: 1 }).margin(80)
.scale({ x: this.scale, y: this.scale, z: this.scale })
.scale({ x: this.scaleValue, y: this.scaleValue, z: this.scaleValue })
.gesture(
PinchGesture()
.onActionStart((event: GestureEvent) => {
console.info('Pinch start')
})
.onActionUpdate((event: GestureEvent) => {
this.scale = event.scale
this.scaleValue = event.scale
})
.onActionEnd(() => {
console.info('Pinch end')
......
# CanvasRenderingContext2D
> **NOTE**<br>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<RenderingContext>** component is used to draw rectangles, text, images, and other objects on a canvas.
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## APIs
......@@ -1771,17 +1769,17 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sWidth: number,
Draws an image.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ------- | ---------------------------------------- | --------- | ------------- | ---------------------------------------- |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7) | Yes | null | Image resource. For details, see ImageBitmap or PixelMap. |
| sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image. |
| sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image. |
| sWidth | number | No | 0 | Target width to crop the source image. |
| sHeight | number | No | 0 | Target height to crop the source image. |
| dx | number | Yes | 0 | X-coordinate of the upper left corner of the drawing area on the canvas. |
| dy | number | Yes | 0 | Y-coordinate of the upper left corner of the drawing area on the canvas. |
| dWidth | number | No | 0 | Width of the drawing area. |
| dHeight | number | No | 0 | Height of the drawing area. |
| Name | Type | Mandatory | Default Value | Description |
| ------- | ------------------------------------------------------------ | --------- | ------------- | ------------------------------------------------------------ |
| image | [ImageBitmap](ts-components-canvas-imagebitmap.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7) | Yes | null | Image resource. For details, see ImageBitmap or PixelMap. |
| sx | number | No | 0 | X-coordinate of the upper left corner of the rectangle used to crop the source image. |
| sy | number | No | 0 | Y-coordinate of the upper left corner of the rectangle used to crop the source image. |
| sWidth | number | No | 0 | Target width to crop the source image. |
| sHeight | number | No | 0 | Target height to crop the source image. |
| dx | number | Yes | 0 | X-coordinate of the upper left corner of the drawing area on the canvas. |
| dy | number | Yes | 0 | Y-coordinate of the upper left corner of the drawing area on the canvas. |
| dWidth | number | No | 0 | Width of the drawing area. If the width of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former. |
| dHeight | number | No | 0 | Height of the drawing area. If the height of the drawing area is different from that of the cropped image, the latter will be stretched or compressed to the former. |
- Example
......
# Combined Gestures
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> Combined gestures are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
......@@ -14,44 +15,46 @@ None
GestureGroup(mode: GestureMode, ...gesture: GestureType[])
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| mode | 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. |
**Parameters**
- 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. |
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| mode | 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
| 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
| Name | Description |
| Name | Description |
| -------- | -------- |
| onCancel(event: () =&gt; void) | Callback for the GestureMode.Sequence cancellation event. |
| onCancel(event: () =&gt; void) | Callback for the **GestureMode.Sequence** cancellation event. |
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct GestureGroupExample {
@State count: number = 0
@State offsetX: number = 0
@State offsetY: number = 0
@State borderStyle: BorderStyle = BorderStyle.Solid
@State borderStyles: BorderStyle = BorderStyle.Solid
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
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.borderStyle })
.height(100).width(200).padding(10).margin(80).border({ width: 1, style: this.borderStyles })
.gesture(
GestureGroup(GestureMode.Sequence,
LongPressGesture({ repeat: true })
......@@ -64,7 +67,7 @@ struct GestureGroupExample {
}),
PanGesture({})
.onActionStart(() => {
this.borderStyle = BorderStyle.Dashed
this.borderStyles = BorderStyle.Dashed
console.log('pan start')
})
.onActionUpdate((event: GestureEvent) => {
......
# Flex
The **\<Flex>** component allows for elastic layout of child components.
> **NOTE**<br/>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **\<Flex>** component allows for an elastic layout.
> **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 to comply with the **flexShrink** and **flexGrow** settings. 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
......@@ -24,39 +23,40 @@ Flex(options?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: F
Creates a standard **\<Flex>** component.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| direction | FlexDirection | No | FlexDirection.Row | Direction in which child components are arranged in the **\<Flex>** component, that is, the direction of the main axis. |
| wrap | FlexWrap | No | FlexWrap.NoWrap | Whether the **\<Flex>** component has a single line or multiple lines. |
| justifyContent | 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-enums) | No | ItemAlign.Stretch | Alignment mode of the child components in the **\<Flex>** component along the cross axis. |
| alignContent | 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**. |
- FlexDirection enums
| Name | Description |
| -------- | -------- |
| Row | The child components are arranged in the same direction as the main axis runs along the rows. |
| RowReverse | The child components are arranged opposite to the **Row** direction. |
| Column | The child components are arranged in the same direction as the main axis runs down the columns. |
| ColumnReverse | The child components are arranged opposite to the **Column** direction. |
- FlexWrap enums
| Name | Description |
| -------- | -------- |
| NoWrap | The child components in the **&lt;Flex&gt;** component are arranged in a single line, and they may overflow. |
| Wrap | The child components in the **&lt;Flex&gt;** component are arranged in multiple lines, and they may overflow. |
| WrapReverse | The child components in the **&lt;Flex&gt;** component are reversely arranged in multiple lines, and they may overflow. |
- FlexAlign enums
| Name | Description |
| -------- | -------- |
| Start | The child components are aligned with the start edge of the main axis. The first component is aligned with the main-start, and subsequent components are aligned with the previous one. |
| Center | The child components are aligned in the center of the main axis. The space between the first component and the main-start is the same as that between the last component and the main-end. |
| End | The child components are aligned with the end edge of the main axis. The last component is aligned with the main-end, and other components are aligned with the next one. |
| SpaceBetween | The child components are evenly distributed along the main axis. The first component is aligned with the main-start, the last component is aligned with the main-end, and the remaining components are distributed so that the space between any two adjacent components is the same. |
| SpaceAround | The child components are evenly distributed along the main axis, with a half-size space on either end. The space between any two adjacent components is the same. The space between the first component and main-start, and that between the last component and cross-main are both half the size of the space between two adjacent components. |
| SpaceEvenly | The child components are equally distributed along the main axis. The space between the first component and main-start, the space between the last component and main-end, and the space between two adjacent components are the same. |
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------------- | ---------------------------------------- | ---- | ----------------- | ---------------------------------------- |
| direction | FlexDirection | No | FlexDirection.Row | Direction in which child components are arranged in the **\<Flex>** component, that is, the direction of the main axis. |
| wrap | FlexWrap | No | FlexWrap.NoWrap | Whether the **\<Flex>** component has a single line or multiple lines. |
| justifyContent | 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-enums)| No | ItemAlign.Stretch | Alignment mode of the child components in the **\<Flex>** component along the cross axis. |
| alignContent | 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**.|
## FlexDirection
| Name | Description |
| ------------- | ---------------- |
| Row | The child components are arranged in the same direction as the main axis runs along the rows. |
| RowReverse | The child components are arranged opposite to the **Row** direction. |
| Column | The child components are arranged in the same direction as the main axis runs down the columns. |
| ColumnReverse | The child components are arranged opposite to the **Column** direction.|
## FlexWrap enums
| Name | Description |
| ----------- | ------------------------------------------------- |
| NoWrap | The child components in the **\<Flex>** component are arranged in a single line, and they cannot overflow. |
| Wrap | The child components in the **\<Flex>** component are arranged in multiple lines, and they may overflow. |
| WrapReverse | The child components in the **\<Flex>** component are reversely arranged in multiple lines, and they may overflow.|
## FlexAlign enums
| Name | Description |
| ------------ | ------------------------------------------------------------ |
| Start | The child components are aligned with the start edge of the main axis. The first component is aligned with the main-start, and subsequent components are aligned with the previous one.|
| Center | The child components are aligned in the center of the main axis. The space between the first component and the main-start is the same as that between the last component and the main-end.|
| End | The child components are aligned with the end edge of the main axis. The last component is aligned with the main-end, and other components are aligned with the next one.|
| SpaceBetween | The child components are evenly distributed along the main axis. The space between any two adjacent components is the same. The first component is aligned with the main-start, the last component is aligned with the main-end, and the remaining components are distributed so that the space between any two adjacent components is the same. |
| SpaceAround | The child components are evenly distributed along the main axis. The space between any two adjacent components is the same. The space between the first component and main-start, and that between the last component and cross-main are both half the size of the space between two adjacent components. |
| SpaceEvenly | The child components are equally distributed along the main axis. The space between the first component and main-start, the space between the last component and main-end, and the space between two adjacent components are the same.|
## Example
......@@ -124,7 +124,6 @@ struct FlexExample1 {
![en-us_image_0000001256978365](figures/en-us_image_0000001256978365.gif)
```
// Example 02
@Entry
......@@ -171,7 +170,6 @@ struct FlexExample2 {
![en-us_image_0000001211898500](figures/en-us_image_0000001211898500.png)
```
// Example 03
@Component
......@@ -221,7 +219,6 @@ struct FlexExample3 {
![en-us_image_0000001212218462](figures/en-us_image_0000001212218462.gif)
```
// Example 04
@Component
......@@ -273,7 +270,6 @@ struct FlexExample4 {
![en-us_image_0000001212378426](figures/en-us_image_0000001212378426.gif)
```
// Example 05
@Component
......
# Swiper
> **NOTE**<br>
>
> This component is supported since API version 7. 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 through swiping.
The **<Swiper\>** component provides a container that allows users to switch among child components through swiping.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
......@@ -37,7 +37,7 @@ Swiper(value:{controller?: SwiperController})
| autoPlay | boolean | false | Whether to enable automatic playback for child component switching. If this attribute is **true**, the indicator dots do not take effect. |
| interval | number | 3000 | Interval for automatic playback, in ms. |
| indicator | boolean | true | Whether to enable the navigation dots. |
| loop | boolean | true | Whether to enable loop playback. |
| loop | boolean | true | Whether to enable loop playback.<br>The value **true** means to enable loop playback. When **LazyForEach** is used, it is recommended that the number of the components to load exceed 5. |
| duration | number | 400 | Duration of the animation for switching child components, in ms. |
| vertical | boolean | false | Whether vertical swiping is used. |
| itemSpace | Length | 0 | Space between child components. |
......
# OffscreenCanvasRenderingContext2D
> **NOTE**<br>The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
Use **OffscreenCanvasRenderingContext2D** to draw rectangles, images, and text offscreen onto a canvas. Drawing offscreen onto a canvas is a process where content to draw onto the canvas is first drawn in the buffer, and then converted into a picture, and finally the picture is drawn on the canvas. This process increases the drawing efficiency.
Use **OffscreenCanvasRenderingContext2D** to draw rectangles, images, and text offscreen onto a canvas. Drawing offscreen onto a canvas is a process where content to draw onto the canvas is first drawn in the buffer, and then converted into a picture, and finally the picture is drawn on the canvas. This process increases the drawing efficiency.
> **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.
## APIs
......@@ -273,7 +275,7 @@ struct MiterLimit {
// xxx.ets
@Entry
@Component
struct Font {
struct Fonts {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings)
......
# Page Transition
Customize the page transition animations by configuring the page entrance and exit components in the global **pageTransition** method.
> **NOTE**
>
> This animation is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
Customize the page transition animations by configuring the page entrance and exit components in the global **pageTransition** method.
## APIs
| Name | Parameter | Description |
| -------- | -------- | -------- |
......@@ -20,15 +20,15 @@ Customize the page transition animations by configuring the page entrance and ex
| -------- | -------- | -------- | -------- | -------- |
| type | RouteType | - | No | If this parameter is not set, the reverse playback effect as pop switches to push is used. |
| duration | number | 1000 | No | Animation duration, in ms. |
| curve | Curve \| Curves | Linear | No | Animation curve. For details about the valid values, see [Curve](ts-animatorproperty.md). |
| curve | Curve \| Curves | Linear | No | Animation curve. For details about the valid values, see **Curve enums**. |
| delay | number | 0 | No | Animation delay, in ms. Delayed animation is disabled by default. |
- RouteType enums
| Name | Description |
| -------- | -------- |
| Pop | Jumps to the specified page. |
| Push | Jumps to the next page. |
| Pop | When page A jumps to page B, page A is Exit+Push, and page B is Enter+Push. |
| Push | When page B returns to page A, page A is Enter+Pop, and page B is Exit+Pop. |
## Attributes
......@@ -37,7 +37,7 @@ The **PageTransitionEnter** and **PageTransitionExit** components support the fo
| Name | Type | Default Value | Mandatory | Description |
| -------- | -------- | -------- | -------- | -------- |
| slide | SlideEffect | SlideEffect.Right | No | Slide effect during page transition. For details, see **SlideEffect enums**. |
| slide | SlideEffect | SlideEffect.Right | No | Slide effect during page transition. For details about the valid values, see **SlideEffect enums**. |
| translate | {<br/>x? : number,<br/>y? : number,<br/>z? : number<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. |
| scale | {<br/>x? : number,<br/>y? : number,<br/>z? : number,<br/>centerX? : number,<br/>centerY? : number<br/>} | - | No | Scaling effect during page transition, which is the value of the start point of entrance and the end point of exit. |
| opacity | number | 1 | No | Opacity, which is the opacity value of the start point of entrance or the end point of exit. |
......@@ -57,8 +57,8 @@ The PageTransitionEnter and PageTransitionExit components support the following
| Event | Description |
| -------- | -------- |
| onEnter(type: RouteType, progress: number) =&gt; void | The callback input parameter is the normalized progress of the current entrance animation. The value range is 0–1. |
| onExit(type: RouteType, progress: number) =&gt; void | The callback input parameter is the normalized progress of the current exit animation. The value range is 0–1. |
| onEnter(type: RouteType, progress: number) =&gt; void | Callback invoked when page entrance occurs. The input parameter is the normalized progress of the current entrance animation. The value range is 0–1. |
| onExit(type: RouteType, progress: number) =&gt; void | Callback invoked when page exit occurs. The input parameter is the normalized progress of the current exit animation. The value range is 0–1. |
## Example
......@@ -136,7 +136,6 @@ struct AExample {
Customization method 2: The entrance animation of the current page is configured to slide in from the left, and the exit animation is configured to zoom out with opacity change.
```
// index.ets
@Entry
......@@ -168,7 +167,6 @@ struct PageTransitionExample {
}
```
```
// page1.ets
@Entry
......
# Component Area Change Event
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
......@@ -12,20 +13,21 @@ None
## Events
| Name | Bubble Supported | Description |
| Name | Bubble Supported | Description |
| -------- | -------- | -------- |
| onAreaChange(event: (oldValue: Area, newValue: Area) =&gt; void) | No | Triggered when the component area changes. For details about the **Area** type, see **Area** attributes. |
| onAreaChange(event: (oldValue: Area, newValue: Area) =&gt; void) | No | Triggered when the component area changes. For details about the **Area** type, see **Area** attributes. |
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct AreaExample {
@State value: string = 'Text'
@State size: string = ''
@State size1: string = ''
build() {
Column() {
......@@ -36,7 +38,7 @@ struct AreaExample {
})
.onAreaChange((oldValue: Area, newValue: Area) => {
console.info(`Ace: on area change, oldValue is ${JSON.stringify(oldValue)} value is ${JSON.stringify(newValue)}`)
this.size = JSON.stringify(newValue)
this.size1 = JSON.stringify(newValue)
})
Text('new area is: \n' + this.size).margin({ right: 30, left: 30 })
}
......
......@@ -80,10 +80,9 @@
- [Directory Structure](ts-framework-directory.md)
- [Rules for Accessing Application Code Files](ts-framework-file-access-rules.md)
- ["js" Tag](ts-framework-js-tag.md)
- Resource Access
- [Accessing Application Resources](ts-application-resource-access.md)
- [Accessing System Resources](ts-system-resource-access.md)
- [Media Resource Types](ts-media-resource-type.md)
- Resource Management
- [Resource File Categories](ui-ts-basic-resource-file-categories.md)
- [Accessing Resources](ts-resource-access.md)
- [Pixel Units](ts-pixel-units.md)
- [Types](ts-types.md)
- Declarative Syntax
......
# CSS
Cascading Style Sheets (CSS) is a language used to describe the HML page structure. All HML components have default styles. You can customize styles for these components using CSS to design various pages.
Cascading Style Sheets (CSS) is a language used to describe the HML page structure. All HML components have default styles. You can customize styles for these components using CSS to design various pages. For details, see [Universal Styles](../reference/arkui-js/js-components-common-styles.md).
## Size Unit
1. Logical px set by &lt;length&gt;:
1. The default logical screen width is 720 px (for details, see the "window" section in [config.json](js-framework-js-tag.md)). Your page will be scaled to fit the actual width of the screen. For example, on a screen with the actual width of 1440 physical px, 100 px is displayed on 200 physical px, with all sizes doubled from 720 px to 1440 px.
2. If you set autoDesignWidth to true (for details, see the "window" section in [config.json](js-framework-js-tag.md)), the logical px are scaled based on the screen density. For example, if the screen density is 3x, 100 px will be rendered on 300 physical px. This approach is recommended when your application needs to adapt to multiple devices.
- Logical px set by \<length>:
- The default logical screen width is 720 px (for details, see the "window" section in [config.json](js-framework-js-tag.md)). Your page will be scaled to fit the actual width of the screen. For example, on a screen with the actual width of 1440 physical px, 100 px is displayed on 200 physical px, with all sizes doubled from 720 px to 1440 px.
- If you set autoDesignWidth to true (for details, see the "window" section in [config.json](js-framework-js-tag.md)), the logical px are scaled based on the screen density. For example, if the screen density is 3x, 100 px will be rendered on 300 physical px. This approach is recommended when your application needs to adapt to multiple devices.
2. Percentage set by &lt;percentage&gt;: The component size is represented by its percentage of the parent component size. For example, if the width &lt;percentage&gt; of a component is set to 50%, the width of the component is half of its parent component's width.
- Percentage set by &lt;percentage&gt;: The component size is represented by its percentage of the parent component size. For example, if the width &lt;percentage&gt; of a component is set to 50%, the width of the component is half of its parent component's width.
## Style Import
......@@ -23,7 +23,7 @@ The .css file with the same name as the .hml file in each page directory describ
1. Internal style: The style and class attributes can be used to specify the component style. Example:
```
```html
<!-- index.hml -->
<div class="container">
<text style="color: red">Hello World</text>
......@@ -31,7 +31,7 @@ The .css file with the same name as the .hml file in each page directory describ
```
```
```css
/* index.css */
.container {
justify-content: center;
......@@ -40,7 +40,7 @@ The .css file with the same name as the .hml file in each page directory describ
2. External style files: You need to import the files. For example, create a style.css file in the common directory and import the file at the beginning of index.css.
```
```css
/* style.css */
.title {
font-size: 50px;
......@@ -48,7 +48,7 @@ The .css file with the same name as the .hml file in each page directory describ
```
```
```css
/* index.css */
@import '../../common/style.css';
.container {
......@@ -67,12 +67,12 @@ A CSS selector is used to select elements for which styles need to be added to.
| \#id | \#titleId | Selects all components whose id is titleId. |
| tag | text | Selects all &lt;text&gt; components. |
| , | .title, .content | Selects all components whose class is title or content. |
| \#id .class tag | \#containerId .content text | Selects all grandchild &lt;text&gt; components whose grandparent components are identified as containerId and whose parent components are of the content class. To select child components, use > to replace the space between \#id and .class, for example, \#containerId>.content. |
| \#id .class tag | \#containerId .content text | Selects all grandchild **\<text>** components whose grandparent components are identified as containerId and whose parent components are of the content class. To select child components, use > to replace the space between **\#id** and **.class**, for example, **\#containerId>.content**. |
The following is an example:
```
```html
<!-- Page layoutxxx.hml -->
<div id="containerId" class="container">
<text id="titleId" class="title">Title</text>
......@@ -83,9 +83,9 @@ The following is an example:
```
```
```css
/* Page style xxx.css */
/* Set the style for all <div> components. */
/\* Set the style for all <div> components. \*/
div {
flex-direction: column;
}
......@@ -101,15 +101,13 @@ div {
.title, .content {
padding: 5px;
}
/* Set the style for all texts of components whose class is container.
*/
/\* Set the style for all texts of components whose class is container.\*/
.container text {
color: #007dff;
color: \#007dff;
}
/* Set the style for direct descendant texts of components whose class is container.
*/
.container > text {
color: #fa2a2d;
/\* Set the style for direct descendant texts of components whose class is container.\*/
.container &gt; text {
color: \#fa2a2d;
}
```
......@@ -130,46 +128,45 @@ When multiple selectors point to the same element, their priorities are as follo
A CSS pseudo-class is a keyword added to a selector that specifies a special state of the selected element(s). For example, :disabled can be used to select the element whose disabled attribute is true.
In addition to a single pseudo-class, a combination of pseudo-classes is supported. For example, :focus:checked selects the element whose focus and checked attributes are both set to true. The following table lists the supported single pseudo-class in descending order of priority.
In addition to a single pseudo-class, a combination of pseudo-classes is supported. For example, **:focus:checked** selects the element whose focus and checked attributes are both set to true. The following table lists the supported single pseudo-class in descending order of priority.
| Pseudo-class | Available Components | Description |
| Pseudo-class | Available Components | Description |
| -------- | -------- | -------- |
| :disabled | Components that support the disabled attribute | Selects the element whose disabled attribute is changed to true (unavailable for animation attributes). |
| :focus | Components that support the focusable attribute | Selects the element that takes focus (unavailable for animation attributes). |
| :active | Components that support the click event<br/> | Selects the element activated by a user. For example, a pressed button or a selected tab-bar (unavailable for animation attributes). |
| :waiting | button | Selects the element whose waiting attribute is true (unavailable for animation attributes). |
| :disabled | Components that support the disabled attribute | Selects the element whose disabled attribute is changed to true (unavailable for animation attributes). |
| :active | Components that support the click event | Selects the element activated by a user. For example, a pressed button or a selected tab-bar (unavailable for animation attributes). |
| :waiting | button | Selects the element whose waiting attribute is true (unavailable for animation attributes). |
| :checked | input[type="checkbox", type="radio"], and switch | Selects the element whose checked attribute is true (unavailable for animation attributes). |
| :hover<sup>6+</sup> | Components that support the mouseover event | Selects the element that the cursor is on. |
The following is an example for you to use the :active pseudo-class to control the style when a user presses the button.
The following is an example for you to use the **:active** pseudo-class to control the style when a user presses the button.
```
```html
<!-- index.hml -->
<div class="container">
<input type="button" class="button" value="Button"></input>
</div>
```
```
```css
/* index.css */
.button:active {
background-color: #888888;/* After the button is activated, the background color is changed to #888888. */
}
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**:
> Pseudo-classes are not supported for the \<popup> component and its child components, including, \<dialog>, \<menu>, \<option>, and \<picker>.
> **NOTE**
>
> Pseudo-classes are not supported for the **\<popup>** component and its child components, including **\<popup>**, **\<dialog>**, **\<menu>**, **\<option>**, and **\<picker>**.
## Precompiled Styles
Precompilation is a program that uses specific syntax to generate CSS files. It provides variables and calculation, helping you define component styles more conveniently. Currently, Less, Sass, and Scss are supported. To use precompiled styles, change the suffix of the original .css file. For example, change index.css to index.less, index.sass, or index.scss.
Precompilation is a program that uses specific syntax to generate CSS files. It provides variables and calculation, helping you define component styles more conveniently. Currently, Less, Sass, and Scss are supported. To use precompiled styles, change the suffix of the original .css file. For example, change **index.css** to **index.less**, **index.sass**, or **index.scss**.
- The following index.less file is changed from index.css.
```
```less
/* index.less */
/* Define a variable. */
@colorBackground: #000000;
......@@ -178,18 +175,18 @@ Precompilation is a program that uses specific syntax to generate CSS files. It
}
```
- Reference a precompiled style file. For example, if the style.scss file is located in the common directory, change the original index.css file to index.scss and import style.scss.
- Reference a precompiled style file. For example, if the **style.scss** file is located in the common directory, change the original index.css file to **index.scss** and import **style.scss**.
```
```scss
/* style.scss */
/* Define a variable. */
$colorBackground: #000000;
```
Reference the precompiled style file in index.scss:
Reference the precompiled style file in **index.scss**:
```
```scss
/* index.scss */
/* Import style.scss. */
@import '../../common/style.scss';
......@@ -199,7 +196,8 @@ Precompilation is a program that uses specific syntax to generate CSS files. It
```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**:
> **NOTE**
>
> Place precompiled style files in the common directory.
## CSS Style Inheritance<sup>6+</sup>
......
# @Component
A struct decorated by @Component has the componentization capability and can serve as an independent component. This type of component is also called a custom component, and its UI structure is described in the build method. Custom components have the following features:
A struct decorated by **@Component** has the componentization capability and can serve as an independent component. This type of component is also called a custom component, and its UI structure is described in the **build** method. Custom components have the following features:
- Composability: Custom components can be used with preset or other components, as well as common attributes and methods.
- Reusable: Custom components can be reused by other components and used as different instances in different parent components or containers.
- Lifecycle: Custom components provide callbacks for service logic processing throughout the lifecycle.
- Data-driven update: The UI of custom components can be automatically updated based on the data of state variables.
For details about componentization, see [About @Component](ts-custom-component-initialization.md).
> **NOTE**
> **NOTE**
>
> - The **build** method must be defined for a custom component.
>
> - Custom constructors are prohibited for custom components.
> - The **build** method must be defined for a custom component.
>- Custom constructors are prohibited for custom components.
The following code illustrates how to create a custom component named **MyComponent**:
```
```ts
@Component
struct MyComponent {
build() {
......@@ -38,12 +35,13 @@ struct MyComponent {
```
The **build** method of **MyComponent** is executed during initial rendering. When the component status changes, the build method will be executed again.
The **build** method of **MyComponent** is executed during initial rendering. When the component status changes, the **build** method will be executed again.
The following code illustrates how to use **MyComponent**:
```
```ts
@Component
struct ParentComponent {
build() {
......@@ -56,9 +54,11 @@ struct ParentComponent {
}
```
**MyComponent** can be applied multiple times and reused in different components, as shown in the code below:
```
```ts
@Component
struct ParentComponent {
build() {
......
......@@ -3,7 +3,7 @@
The **@Styles** decorator adds new attribute functions to basic components, such as **\<Text>**, **\<Column>**, and **\<Button>**. Currently, **@Styles** supports only universal attributes. You can use the **@Styles** decorator to quickly define and reuse the custom styles of a component.
**@Styles** can be defined inside or outside a component. When it is defined outside a component, the keyword function must be included.
**@Styles** can be defined inside or outside a component. When it is defined outside a component, the keyword **function** must be added before the API name.
......@@ -40,8 +40,6 @@ struct FancyUse {
In **StateStyles**, styles defined outside the component can be directly called. However, the keyword **this** must be used to call styles defined in the component.
```
@Styles function globalFancy() {
.width(100)
......
# Media Resource Types
- Image resource types
| Format| File Name Extension|
| -------- | -------- |
| JPEG | .jpg |
| PNG | .png |
| GIF | .gif |
| SVG | .svg |
| WEBP | .webp |
| BMP | .bmp |
- Audio and video resource types
| Format| File Name Extension|
| -------- | -------- |
| H.263 | .3gp <br>.mp4 |
| H.264 AVC <br> Baseline Profile (BP) | .3gp <br>.mp4 |
| MPEG-4 SP | .3gp |
| VP8 | .webm <br> .mkv |
# Accessing Application Resources
## Resource Definition
## Accessing Application Resources
Application resources are defined in the project's **resources** directory, which is organized as follows:
To reference an application resource in a project, use the `"$r('app.type.name')"` format. **app** indicates the resource defined in the **resources** directory of the application. **type** indicates the resource type (or the location where the resource is stored). The value can be **color**, **float**, **string**, **plural**, or **media**. **name** indicates the resource name, which you set when defining the resource.
- Level-1: **base** sub-directory, qualifiers sub-directories, and **rawfile** sub-directory
- The **base** sub-directory is a default directory. If no qualifiers sub-directories in the **resources** directory of the application match the device status, the resource file in the **base** sub-directory will be automatically referenced.
- You need to create qualifiers sub-directories on your own. The name of a qualifiers sub-directory consists of one or more qualifiers that represent the application scenarios or device characteristics, covering the mobile country code (MCC), mobile network code (MNC), language, script, country or region, screen orientation, device type, color mode, and screen density. The qualifiers are separated using underscores (_) or hyphens (-).
- When the resources in the **rawfile** sub-directory are referenced, resource files will not be matched based on the device status. You can directly store resource files in the **rawfile** sub-directory.
When referencing resources in the **rawfile** sub-directory, use the `"$rawfile('filename')"` format. Currently, **$rawfile** allows only the **\<Image>** component to reference image resources. **filename** indicates the relative path of a file in the **rawfile** directory, and the file name must contain the file name extension. Note that the relative path cannot start with a slash (/).
- Level-2: resource sub-directories
- Resource sub-directories store basic elements such as character strings, colors, and floating point numbers, and resource files such as media files.
- Supported files and resource types are listed in the table below.
| File Name| Resource Type|
| -------- | -------- |
| color.json | Color resource.|
| float.json | Resources such as spacing, rounded corners, and fonts.|
| string.json | String resource.|
| plural.json | String resource.|
| media directory| Image resource.|
> **NOTE**
> Resource descriptors accept only strings, such as `'app.type.name'`, and cannot be combined.
In the **.ets** file, you can use the resources defined in the **resources** directory.
## Referencing Resources
```ts
Text($r('app.string.string_hello'))
.fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_hello'))
}
To reference an application resource in a project, use the `"$r('app.type.name')"` format. **app** indicates the resource defined in the **resources** directory of the application. **type** indicates the resource type (or the location where the resource is stored). The value can be **color**, **float**, **string**, **plural**, or **media**. **name** indicates the resource name, which you set when defining the resource.
Text($r('app.string.string_world'))
.fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world'))
}
When referencing resources in the **rawfile** sub-directory, use the `"$rawfile('filename')"` format. Currently, **$rawfile** allows only the **\<Image>** component to reference image resources. **filename** indicates the relative path of a file in the **rawfile** directory, and the file name must contain the file name extension. Note that the relative path cannot start with a slash (/).
Text($r('app.string.message_arrive', "five of the clock")) // Reference string resources. The second parameter of $r is used to replace %s.
.fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_hello'))
}
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> Resource descriptors accept only strings, such as `'app.type.name'`, and cannot be combined.
Text($r('app.plural.eat_apple', 5, 5)) // Reference plural resources. The first parameter indicates the plural resource, and the second parameter indicates the number of plural resources. The third parameter indicates the substitute of %d.
.fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world'))
}
Image($r('app.media.my_background_image')) // Reference media resources.
Image($rawfile('test.png')) // Reference an image in the rawfile directory.
Image($rawfile('newDir/newTest.png')) // Reference an image in the rawfile directory.
```
## Example
Some custom resources in the **base** sub-directory are as follows:
## Accessing System Resources
System resources include colors, rounded corners, fonts, spacing, character strings, and images. By using system resources, you can develop different applications with the same visual style.
To reference a system resource, use the "$r('sys.type.resource_id')" format. Wherein: sys indicates a system resource; type indicates the resource type, which can be color, float, string, or media; resource_id indicates the resource ID, which is determined when the system resource is provided. For details about available system resource IDs.
```ts
Text('Hello')
.fontColor($r('sys.color.ohos_id_color_emphasize'))
.fontSize($r('sys.float.ohos_id_text_size_headline1'))
.fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
.backgroundColor($r('sys.color.ohos_id_color_palette_aux1'))
Image($r('sys.media.ohos_app_icon'))
.border({color: $r('sys.color.ohos_id_color_palette_aux1'), radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2})
.margin({top: $r('sys.float.ohos_id_elements_margin_horizontal_m'), bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l')})
.height(200)
.width(300)
```
resources
├─ base
│ ├─ element
│ │ ├─ color.json
│ │ ├─ string.json
│ │ └─ float.json
│ └─ media
│ └─ my_background_image.png
└─ rawfile
├─ test.png
└─ newDir
└─ newTest.png
```
## Resource File Examples
The content of the **color.json** file is as follows:
```
```json
{
"color": [
{
......@@ -73,7 +84,7 @@ The content of the **color.json** file is as follows:
The content of the **float.json** file is as follows:
```
```json
{
"float":[
{
......@@ -91,7 +102,7 @@ The content of the **float.json** file is as follows:
The content of the **string.json** file is as follows:
```
```json
{
"string":[
{
......@@ -113,7 +124,7 @@ The content of the **string.json** file is as follows:
The content of the **plural.json** file is as follows:
```
```json
{
"plural":[
{
......@@ -132,40 +143,3 @@ The content of the **plural.json** file is as follows:
]
}
```
In the **.ets** file, you can use the resources defined in the **resources** directory.
```
Text($r('app.string.string_hello'))
.fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_hello'))
}
Text($r('app.string.string_world'))
.fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world'))
}
Text($r('app.string.message_arrive', "five of the clock")) // Reference string resources. The second parameter of $r is used to replace %s.
.fontColor($r('app.color.color_hello'))
.fontSize($r('app.float.font_hello'))
}
Text($r('app.plural.eat_apple', 5, 5)) // Reference plural resources. The first parameter indicates the plural resource, and the second parameter indicates the number of plural resources. The third parameter indicates the substitute of %d.
.fontColor($r('app.color.color_world'))
.fontSize($r('app.float.font_world'))
}
Image($r('app.media.my_background_image')) // Reference media resources.
Image($rawfile('test.png')) // Reference an image in the rawfile directory.
Image($rawfile('newDir/newTest.png')) // Reference an image in the rawfile directory.
```
## Samples
The following sample is provided to help you better understand how to access application resources:
- [`ResourceManager`: eTS Resource Management (API 7)](https://gitee.com/openharmony/app_samples/tree/master/common/ResourceManager)
# Accessing System Resources
System resources include colors, rounded corners, fonts, spacing, character strings, and images. By using system resources, you can develop different applications with the same visual style.
To reference a system resource, use the "$r('sys.type.resource_id')" format. Wherein: sys indicates a system resource; type indicates the resource type, which can be color, float, string, or media; resource_id indicates the resource ID, which is determined when the system resource is provided. For details about available system resource IDs.
```
Text('Hello')
.fontColor($r('sys.color.ohos_id_color_emphasize'))
.fontSize($r('sys.float.ohos_id_text_size_headline1'))
.fontFamily($r('sys.string.ohos_id_text_font_family_medium'))
.backgroundColor($r('sys.color.ohos_id_color_palette_aux1'))
Image($r('sys.media.ohos_app_icon'))
.border({color: $r('sys.color.ohos_id_color_palette_aux1'), radius: $r('sys.float.ohos_id_corner_radius_button'), width: 2})
.margin({top: $r('sys.float.ohos_id_elements_margin_horizontal_m'), bottom: $r('sys.float.ohos_id_elements_margin_horizontal_l')})
.height(200)
.width(300)
```
# Resource File Categories
## resources Directory
All the application resource files, such as strings, images, and audio files, are stored in the **resources** directory, allowing you to easily access, use, and maintain them. The **resources** directory consists of two types of sub-directories: the **base** sub-directory and qualifiers sub-directories, and the **rawfile** sub-directory. For details, see Categories of the **resources** directory.
Example of the **resources** directory:
```
resources
|---base // Default sub-directory
| |---element
| | |---string.json
| |---media
| | |---icon.png
|---en_GB-vertical-car-mdpi // Example of a qualifiers sub-directory, which needs to be created on your own
| |---element
| | |---string.json
| |---media
| | |---icon.png
|---rawfile // Default sub-directory
```
**Table 1** Categories of the **resources** directory
| Category | base and Qualifiers Sub-directories | rawfile Sub-directory |
| ----------- | ---------------------------------------- | ---------------------------------------- |
| Structure | Sub-directories are structured in two levels. The directory name must comply with specified naming conventions so that its target resource file in the correct directory can be matched based on the device status.<br> The **base** sub-directory and qualifiers sub-directories are the first level of sub-directories under **resources**.<br>- The **base** sub-directory is generated by default. If no qualifiers sub-directories in the **resources** directory of the application match the device status, the resource file in the **base** sub-directory will be automatically referenced.<br>- You need to create qualifiers sub-directories on your own. Each directory name consists of one or more qualifiers that represent the application scenarios or device characteristics. For details, see [Qualifiers Sub-directories](#qualifiers-sub-directories).<br>Resource group sub-directories are located at the second level of sub-directories to store basic elements such as strings, colors, and boolean values, as well as resource files such as media, animations, and layouts. For details, see [Resource Group Sub-directories](#resource-group-sub-directories). | You can create multiple levels of sub-directories with custom directory names. They can be used to store various resource files.<br>However, resource files in the **rawfile** sub-directory will not be matched based on the device status. |
| Compilation | Resource files in the sub-directories are compiled into binary files, and each resource file is assigned an ID. | Resource files in the sub-directory are directly packed into the application without being compiled, and no IDs will be assigned to the resource files. |
| Reference | Resource files in the sub-directories are referenced based on the resource type and resource name. | Resource files in the sub-directories are referenced based on the specified file path and file name. |
## Qualifiers Sub-directories
The name of a qualifiers sub-directory consists of one or more qualifiers that represent the application scenarios or device characteristics, covering the mobile country code (MCC), mobile network code (MNC), language, script, country or region, screen orientation, device type, color mode, and screen density. The qualifiers are separated using underscores (_) or hyphens (-). When creating a qualifiers sub-directory, you need to understand the directory naming conventions and the rules for matching qualifiers sub-directories and the device status.
**Naming Conventions for Qualifiers Sub-directories**
- Qualifiers are ordered in the following sequence: *MCC*MNC-language_script_country/region-screen orientation-device type-color mode-screen density_. You can select one or multiple qualifiers to name your sub-directory based on your application scenarios and device characteristics.
- Separation between qualifiers: The language, script, and country/region qualifiers are separated using underscores (\_); the MNC and MCC qualifiers are also separated using underscores (\_); other qualifiers are separated using hyphens (-). For example, **zh_Hant_CN** and **zh_CN-car-ldpi**.
- Value range of qualifiers: The value of each qualifier must meet the requirements. Otherwise, the resource files in the sub-directory cannot be matched.
**Table 2** Requirements for qualifier values
| Qualifier Type | Description and Value Range |
| ------------------ | ---------------------------------------- |
| MCC&amp;MNC | Indicates the MCC and MNC, which are obtained from the network where the device is registered. The MCC can be either followed by the MNC with an underscore (*) in between or be used independently. For example, **mcc460** represents China, and **mcc460*mnc00** represents China Mobile.<br>For details about the value range, refer to **ITU-T E.212** (the international identification plan for public networks and subscriptions). |
| Language | Indicates the language used by the device. The value consists of two or three lowercase letters, for example, **zh** indicates Chinese, **en** indicates English, and **mai** indicates Maithili.<br>For details about the value range, refer to **ISO 639** (codes for the representation of names of languages). |
| Script | Indicates the script type used by the device. The value starts with one uppercase letter followed by three lowercase letters, for example, **Hans** indicates simplified Chinese and **Hant** indicates traditional Chinese.<br>For details about the value range, refer to **ISO 15924** (codes for the representation of names of scripts). |
| Country/Region | Indicates the country or region where a user is located. The value consists of two or three uppercase letters or three digits, for example, **CN** indicates China and **GB** indicates the United Kingdom.<br>For details about the value range, refer to **ISO 3166-1** (codes for the representation of names of countries and their subdivisions). |
| Screen orientation | Indicates the screen orientation of the device. The value can be:<br>- **vertical**: portrait orientation<br>- **horizontal**: landscape orientation |
| Device type | Indicates the device type. The value can be:<br>- **car**: head units<br>- **tv**: smart TVs<br>- **wearable**: wearables |
| Color mode | Indicates the color mode of the device. The value can be:<br>- **dark**: dark mode<br>- **light**: light mode |
| Screen density | Indicates the screen density of the device, in dpi. The value can be:<br>- **sdpi**: screen density with small-scale dots per inch (SDPI). This value is applicable for devices with a DPI range of (0, 120].<br>- **mdpi**: screen density with medium-scale dots per inch (MDPI). This value is applicable for devices with a DPI range of (120, 160].<br>- **ldpi**: screen density with large-scale dots per inch (LDPI). This value is applicable for devices with a DPI range of (160, 240].<br>- **xldpi**: screen density with extra-large-scale dots per inch (XLDPI). This value is applicable for devices with a DPI range of (240, 320].<br>- **xxldpi**: screen density with extra-extra-large-scale dots per inch (XXLDPI). This value is applicable for devices with a DPI range of (320, 480].<br>- **xxxldpi**: screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI). This value is applicable for devices with a DPI range of (480, 640]. |
**Rules for Matching Qualifiers Sub-directories and Device Resources**
- Qualifiers are matched with the device resources in the following priorities: MCC&amp;MNC &gt; locale (options: language, language_script, language_country/region, and language_script_country/region) &gt; screen orientation &gt; device type &gt; color mode &gt; screen density
- If the qualifiers sub-directories contain the **MCC, MNC, language, script, screen orientation, device type, and color mode** qualifiers, their values must be consistent with the current device status so that the sub-directories can be used for matching the device resources. For example, the qualifiers sub-directory **zh_CN-car-ldpi** cannot be used for matching the resource files labeled **en_US**.
## Resource Group Sub-directories
You can create resource group sub-directories (including element, media, animation, layout, graphic, and profile) in the **base** and qualifiers sub-directories to store resource files of specific types. For details, see Resource group sub-directories.
**Table 3** Resource group sub-directories
| Resource Group Sub-directory | Description | Resource File |
| ---------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| element | Element resources. Each type of data is represented by a JSON file. The options are as follows:<br>- **boolean**: boolean data<br>- **color**: color data<br>- **float**: floating-point data<br>- **intarray**: array of integer<br>- **integer**: integer data<br>- **pattern**: pattern data<br>- **plural**: plural form data<br>- **strarray**: array of strings<br>- **string**: string data | It is recommended that files in the **element** sub-directory be named the same as the following files, each of which can contain only data of the same type:<br>- boolean.json<br>- color.json<br>- float.json<br>- intarray.json<br>- integer.json<br>- pattern.json<br>- plural.json<br>- strarray.json<br>- string.json |
| media | Media resources, including non-text files such as images, audios, and videos. | The file name can be customized, for example, **icon.png**. |
| profile | Other types of files, which are stored in their raw formats. | The file name can be customized. |
### Media Resource Types
Table 4 Image resource types
| Format| File Name Extension|
| -------- | -------- |
| JPEG | .jpg |
| PNG | .png |
| GIF | .gif |
| SVG | .svg |
| WEBP | .webp |
| BMP | .bmp |
Table 5 Audio and video resource types
| Format| File Name Extension|
| -------- | -------- |
| H.263 | .3gp <br>.mp4 |
| H.264 AVC <br> Baseline Profile (BP) | .3gp <br>.mp4 |
| MPEG-4 SP | .3gp |
| VP8 | .webm <br> .mkv |
## Creating a Resource File
You can create a sub-directory and its files under the **resources** directory based on the above descriptions of the qualifiers sub-directories and resource group sub-directories.
DevEco Studio provides a wizard for you to create resource directories and resource files.
- Creating a Resource Directory and Resource File
Right-click the **resources** directory and choose **New > Resource File**.
If no qualifier is selected, the file is created in a resource type sub-directory under **base**. If one or more qualifiers are selected, the system automatically generates a sub-directory and creates the file in this sub-directory.
The created sub-directory is automatically named in the format of **Qualifiers.Resource type**. For example, if you create a sub-directory by setting **Orientation** to **Vertical** and **Resource type** to **Graphic**, the system automatically generates a sub-directory named **vertical.graphic**.
![create-resource-file-1](figures/create-resource-file-1.png)
- Creating a Resource Directory
Right-click the **resources** directory and choose **New > Resource Directory**. This operation creates a sub-directory only.
Select a resource group type and set qualifiers. Then the system automatically generates the sub-directory name. The sub-directory is automatically named in the format of **Qualifiers.Resource group**. For example, if you create a sub-directory by setting **Orientation** to **Vertical** and **Resource type** to **Graphic**, the system automatically generates a sub-directory named **vertical.graphic**.
![create-resource-file-2](figures/create-resource-file-2.png)
- Creating a Resource File
Right-click a sub-directory under **resources** and choose **New > XXX Resource File**. This operation creates a resource file under this sub-directory.
For example, you can create an element resource file in the **element** sub-directory.
![create-resource-file-3](figures/create-resource-file-3.png)
......@@ -7,7 +7,8 @@ In this section, we will develop an infographic food details page, by building c
## Building the Stack Layout
1. Create a food name.
Delete the code of the build method in the project template, create a &lt;Stack&gt; component, and place the **\<Text>** component in the braces of the **\<Stack>** component so that the &lt;Text&gt; component becomes a child component of the &lt;Stack&gt; component. A **\<Stack>** component consists of one or more child components. The latter child component overwrites the former one.
Delete the code of the **build** method in the project template, create a **\<Stack>** component, and place the **\<Text>** component in the braces of the **\<Stack>** component. When the **\<Stack>** component contains multiple child components, the latter child component overwrites the former one.
```
@Entry
......@@ -23,10 +24,11 @@ In this section, we will develop an infographic food details page, by building c
}
```
![en-us_image_0000001222967780](figures/en-us_image_0000001222967780.png)
![en-us_image_0000001222967780](figures/en-us_image_0000001222967780.png)
2. Display food pictures.
Create an **\<Image>** component and specify a URL for it. The **\<Image>** and **\<Text>** components are mandatory. To display the **\<Text>** component above the **\<Image>** component, you need to declare the **\<Image>** component first. Image resources are stored in the **rawfile** folder in **resources**. When referencing the resources in the **rawfile** folder, use the `"$rawfile('filename')"` format, where filename indicates the relative path of the file in the **rawfile** folder. Currently, `$rawfile` only allows the **\<Image>** component to reference image resources.
Create an **\<Image>** component and specify a URL for it. The **\<Image>** and **\<Text>** components are mandatory. To display the **\<Text>** component above the **\<Image>** component, you need to declare the **\<Image>** component first. Image resources are stored in the **rawfile** folder in **resources**. When referencing the resources in the **rawfile** folder, use the `"$rawfile('filename')"` format, where **filename** indicates the relative path of the file in the **rawfile** folder. Currently, `$rawfile` only allows the **\<Image>** component to reference image resources.
```
@Entry
......@@ -46,9 +48,10 @@ In this section, we will develop an infographic food details page, by building c
![en-us_image_0000001267887861](figures/en-us_image_0000001267887861.png)
3. Access images through resources.
In addition to specifying the image path, you can also use the media resource symbol $r to reference resources based on the resource qualifier rules in the resources folder. Right-click the resources folder, choose **New** &gt; **Resource Directory**, and set **Resource Type** to **Media (image resource)**. Place Tomato.png in the media folder.
You can then can reference the application resource in the ` "$r('app.type.name')"` format, that is, `$r('app.media.Tomato')`.
In addition to specifying the image path, you can also use the media resource symbol `$r` to reference resources in the **resources** folder based on the resource qualifier rules. Right-click the **resources** folder, choose **New** &gt; **Resource Directory**, and set **Resource Type** to **Media (image resource)**.
Place **Tomato.png** in the **media** folder. You can then can reference the application resource in the `$r('app.type.name')` format, that is, `$r('app.media.Tomato')`.
```
......@@ -68,10 +71,11 @@ In this section, we will develop an infographic food details page, by building c
}
```
4. Set the width and height of the image, and set the objectFit attribute of the image to ImageFit.Contain, which means to keep the aspect ratio of the image to ensure that the image is completely displayed within the boundary.If the image fills the entire screen, the possible causes are as follows:
4. Set the width and height of the image, and set the **objectFit** attribute of the image to **ImageFit.Contain**, which means to keep the aspect ratio of the image to ensure that the image is completely displayed within the boundary. If the image fills the entire screen, the possible causes are as follows:
1. The width and height of the image are not set.
2. The default attribute of **objectFit** of the image is **ImageFit.Cover**, that is, the image is zoomed in or zoomed out to fill the entire display boundary with the aspect ratio locked.
```
@Entry
@Component
......@@ -91,7 +95,7 @@ In this section, we will develop an infographic food details page, by building c
![en-us_image_0000001223127732](figures/en-us_image_0000001223127732.png)
5. Set the food image and name layout. Set the alignment mode of the stack to bottom alignment. By default, the stack is center aligned. Set **alignContent** to **Alignment.BottomStart**. Similar to **FontWeight**, **Alignment** is a built-in enumeration type provided by the framework.
5. Set the food image and name layout. Set **alignContent** to **Alignment.BottomStart**. Similar to **FontWeight**, **Alignment** is a built-in enumeration type provided by the framework.
```
@Entry
......@@ -112,9 +116,9 @@ In this section, we will develop an infographic food details page, by building c
![en-us_image_0000001267647873](figures/en-us_image_0000001267647873.png)
6. You can change the background color of the food image by setting the background color of the stack. You can set the background color in either of the following ways:
1. By using the built-in enumeration value of Color provided by the framework. For example, **backgroundColor(Color.Red)** indicates that the background color is set to red.
2. By using the parameter of the string type. The supported color formats are rgb, rgba, and HEX. For example, you can set the background color to blue by setting **backgroundColor(??\#0000FF??)** and set the background color to white by setting **backgroundColor(??rgb(255, 255, 255)??)**.
6. You can change the background color of the food image by setting the background color of the **\<Stack>** component in either of the following ways:
1. Using the built-in **Color** enums provided by the framework. For example, **backgroundColor(Color.Red)** indicates that the background color is set to red.
2. Using the string-type parameter. The supported color formats are rgb, rgba, and HEX. For example, you can set the background color to blue by setting **backgroundColor(??\#0000FF??)** and set the background color to white by setting **backgroundColor(??rgb(255, 255, 255)??)**.
```
......@@ -163,7 +167,7 @@ In this section, we will develop an infographic food details page, by building c
![en-us_image_0000001222967776](figures/en-us_image_0000001222967776.png)
8. Adjust the structure between components and semanticize component names. Create the FoodDetail page entry component, create a column in **FoodDetail**, and set the alignment to **alignItems(HorizontalAlign.Center)**. Change the name of the **MyComponent** component to **FoodImageDisplay**, which is a child component of the **FoodDetail** component.
8. Adjust the structure between components and semanticize component names. Create the **FoodDetail** page entry component, create a column in **FoodDetail**, and set the alignment to **alignItems(HorizontalAlign.Center)**. Change the name of the **MyComponent** component to **FoodImageDisplay**, which is a child component of the **FoodDetail** component.
A column is a container component whose child components are vertically arranged. It is a linear layout in essence. Therefore, only the alignment in the cross axis direction can be set.
......@@ -202,7 +206,7 @@ In this section, we will develop an infographic food details page, by building c
You can use the Flex layout to build a food composition table. In this way you do not need to worry about the width and height calculation. The size of different cells can be flexibly set based on the proportion.
1. Create a **ContentTable** component as a child component of the FoodDetail component.
1. Create a **ContentTable** component as a child component of the **FoodDetail** component.
```
@Component
......@@ -239,13 +243,13 @@ You can use the Flex layout to build a food composition table. In this way you d
}
```
2. Create a Flex component to display two food composition categories in the tomato: Calories and Nutrition.
2. Create a Flex component to display two food composition categories in the tomato: **Calories** and **Nutrition**.
Calories contains information about calories. Nutrition contains information about protein, fat, carbohydrates, and vitamin C.
**Calories** contains information about calories. **Nutrition** contains information about protein, fat, carbohydrates, and vitamin C.
Create the Calories class. Create a Flex component and set its height to 280, and the top, right, and left margins to 30. The Flex component contains three Text child components, which represent the category name (Calories), content name (Calories), and contain value (17 kcal), respectively. By default, child components in the Flex component are arranged horizontally.
Create the **Calories** class. Create a Flex component and set its height to 280, and the top, right, and left margins to 30. The Flex component contains three **\<Text>** child components, which represent the category name (**Calories**), content name (**Calories**), and contain value (**17 kcal**), respectively. By default, child components in the Flex component are arranged horizontally.
In the following example, code of FoodImageDisplay is omitted, and only code of ContentTable is provided.
In the following example, code of **FoodImageDisplay** is omitted, and only code of **ContentTable** is provided.
```
......@@ -281,14 +285,14 @@ Create the Calories class. Create a Flex component and set its height to 280, an
![en-us_image_0000001267767869](figures/en-us_image_0000001267767869.png)
3. Adjust the layout and set the proportion (layoutWeight) of each part. Set the proportion of the category name to **1**, and the total proportion of content name and content value to **2**. The content name and content value are in a same Flex, and the content name occupies all remaining space flexGrow(1).
3. Adjust the layout and set the proportion (**layoutWeight**) of each part. Set the proportion of the category name to **1**, and the total proportion of content name and content value to **2**. The content name and content value are in a same Flex, and the content name occupies all remaining space **flexGrow(1)**.
```
@Component
struct FoodImageDisplay {
build() {
Stack({ alignContent: Alignment.BottomStart }) {
Image($m('Tomato.png'))
Image($r('app.media.Tomato'))
.objectFit(ImageFit.Contain)
.height(357)
Text('Tomato')
......@@ -337,7 +341,7 @@ Create the Calories class. Create a Flex component and set its height to 280, an
![en-us_image_0000001267607901](figures/en-us_image_0000001267607901.png)
4. Create the **Nutrient** class in a similar process. Nutrition consists of four parts: Protein, Fat, Carbohydrates, and VitaminC. The names of the last three parts are omitted in the table and represented by spaces.
4. Create the **Nutrient** class in a similar process. **Nutrition** consists of four parts: **Protein**, **Fat**, **Carbohydrates**, and **VitaminC**. The names of the last three parts are omitted in the table and represented by spaces.
Set **FlexDirection.Column**, **FlexAlign.SpaceBetween**, and **ItemAlign.Start**.
......@@ -442,7 +446,7 @@ Create the Calories class. Create a Flex component and set its height to 280, an
Currently, all food groups are declared, resulting in code duplication and redundancy. You can use @Builder to build a custom method and abstract the same UI structure declaration. The @Builder decorated method and the build method for the @Component decorated component are used to declare some UI rendering structures and comply with the same eTS syntax. You can define one or more methods decorated by @Builder, but a component decorated by @Component can have only one build method.
Declare the IngredientItem method decorated by @Builder in ContentTable to declare the UI descriptions for the category name, content name, and content value.
Declare the **IngredientItem** method decorated by @Builder in **ContentTable** to declare the UI descriptions for the category name, content name, and content value.
```
......@@ -455,9 +459,6 @@ Create the Calories class. Create a Flex component and set its height to 280, an
.fontWeight(FontWeight.Bold)
.layoutWeight(1)
Flex({ alignItems: ItemAlign.Center }) {
Circle({width: 6, height: 6})
.margin({right: 12})
.fill(colorValue)
Text(name)
.fontSize(17.4)
.flexGrow(1)
......@@ -470,7 +471,7 @@ Create the Calories class. Create a Flex component and set its height to 280, an
}
```
When the ` IngredientItem` API is called in the build method of ContentTable, ` this ` needs to be used to invoke the method in the scope of the component to distinguish the global method call.
When the `IngredientItem` API is called in the **build** method of **ContentTable**, `this` needs to be used to invoke the method in the scope of the component to distinguish the global method call.
```
......@@ -491,7 +492,7 @@ When the ` IngredientItem` API is called in the build method of ContentTable,
}
```
The overall code of the ContentTable component is as follows:
The overall code of the **ContentTable** component is as follows:
```
......
......@@ -35,9 +35,9 @@ Ability框架在API 8及更早版本使用FA模型。FA模型中Ability分为Pag
![fa-threading-model](figures/fa-threading-model.png)
## 相关实例
针对Ability开发,有以下相关实例可供参考:
- [`DistributeCalc`:分布式计算器(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/Preset/DistributeCalc)
- [`DistributeGraffiti`:分布式涂鸦(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DistributedGraffiti)
- [`DistributedCalc`:分布式计算器(JS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/DistributeCalc)
- [`DistributedCalc`:分布式计算器(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/DistributeCalc)
- [`DistributeGraffiti`:分布式涂鸦(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/DistributedGraffiti)
- [分布式调度启动远程FA(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteStartFA)
- [分布式新闻客户端(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/NewsDemo)
- [分布式手写板(eTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts)
......
......@@ -288,4 +288,4 @@ Data提供方可以自定义数据的增、删、改、查,以及文件打开
针对DataAbility开发,有以下相关实例可供参考:
- [`DataAbility`:DataAbility的创建与访问(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DataAbility)
- [`DataAbility`:DataAbility的创建与访问(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/DataAbility)
......@@ -350,5 +350,5 @@ onUpdate(formId) {
## 相关实例
针对FA模型卡片提供方的开发,有以下相关实例可供参考:
- [`FormAbility`:FA模型卡片(JS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility)
- [`FormLauncher`:卡片使用方(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormLauncher)
\ No newline at end of file
- [`FormAbility`:FA模型卡片(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/FormAbility)
- [`FormLauncher`:卡片使用方(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/FormLauncher)
\ No newline at end of file
......@@ -261,4 +261,4 @@ export default {
```
## 相关实例
针对PageAbility开发,有以下相关实例可供参考:
- [`DMS`:分布式Demo(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
\ No newline at end of file
- [`DMS`:分布式Demo(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/DMS)
\ No newline at end of file
......@@ -404,5 +404,5 @@ export default {
## 相关实例
针对ServiceAbility开发,有以下相关实例可供参考:
- [`ServiceAbility`:ServiceAbility的创建与使用(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceAbility)
- [`DMS`:分布式Demo(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
- [`ServiceAbility`:ServiceAbility的创建与使用(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/ServiceAbility)
- [`DMS`:分布式Demo(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/DMS)
......@@ -318,7 +318,3 @@ struct Index {
}
}
```
## 相关实例
针对Stage模型Ability开发,有以下相关示例可供参考:
- [`StageCallAbility`:StageCallAbility的创建与使用(eTS)(API9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility)
......@@ -248,6 +248,3 @@ try {
}
```
## 相关实例
针对Stage模型本地Call功能开发,有以下相关实例可供参考:
- [`StageCallAbility`:StageCallAbility的创建与使用(eTS)(API9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility)
......@@ -357,8 +357,3 @@ onUpdate(formId) {
最终可以得到,如下卡片:
![fa-form-example](figures/fa-form-example.png)
## 相关实例
针对Stage模型卡片提供方的开发,有以下相关实例可供参考:
- [`FormExtAbility`:Stage模型卡片(eTS JS)(API9)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormExtAbility)
\ No newline at end of file
......@@ -75,8 +75,3 @@ ExtensionAbility,是Stage模型中新增的扩展组件的基类,一般用
"srcEntrance": "./ets/ServiceExtAbility/ServiceExtAbility.ts"
}]
```
## 相关实例
针对ServiceExtensionAbility开发,有以下相关实例可供参考:
- [`ServiceExtAbility`:StageExtAbility的创建与使用(eTS)(API9)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceExtAbility)
......@@ -71,7 +71,3 @@ httpRequest.request(
}
);
```
## 相关实例
针对HTTP数据请求,有以下相关实例可供参考:
- [`Http`:数据请求(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Http)
\ No newline at end of file
......@@ -125,4 +125,4 @@ UDP与TCP流程大体类似,下面以TCP为例:
## 相关实例
针对Socket连接开发,有以下相关实例可供参考:
- [`Socket`:Socket 连接(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Socket)
- [`Socket`:Socket 连接(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket)
......@@ -172,12 +172,5 @@
```js
local_object.setSessionId("");
```
## 开发实例
针对分布式数据对象,有以下开发实例可供参考:
- [备忘录应用](https://gitee.com/openharmony/distributeddatamgr_objectstore/tree/master/samples/distributedNotepad)
在备忘录应用中,当某一个设备上的备忘录事件发生变更时,通过分布式数据对象将事件变更同步在可信组网内的其他设备上,比如新增备忘录事件、编辑事件标题和内容、清空事件列表等。
......@@ -30,11 +30,13 @@
以单版本分布式数据库为例,说明开发步骤。
1. 导入模块。
```js
import distributedData from '@ohos.data.distributedData';
```
2. 根据配置构造分布式数据库管理类实例。
1. 根据应用上下文创建`kvManagerConfig`对象。
2. 创建分布式数据库管理器实例。
......@@ -63,6 +65,7 @@
```
3. 获取/创建分布式数据库。
1. 声明需要创建的分布式数据库ID描述。
2. 创建分布式数据库,建议关闭自动同步功能(`autoSync:false`),需要同步时主动调用`sync`接口。
......@@ -96,6 +99,7 @@
> 组网设备间同步数据的场景,建议在应用启动时打开分布式数据库,获取数据库的句柄。在该句柄(如示例中的`kvStore`)的生命周期内无需重复创建数据库,可直接使用句柄对数据库进行数据的插入等操作。
4. 订阅分布式数据变化。
以下为订阅单版本分布式数据库数据变化通知的代码示例:
```js
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
......@@ -104,6 +108,7 @@
```
5. 将数据写入分布式数据库。
1. 构造需要写入分布式数据库的`Key`(键)和`Value`(值)。
2. 将键值数据写入分布式数据库。
......@@ -126,6 +131,7 @@
```
6. 查询分布式数据库数据。
1. 构造需要从单版本分布式数据库中查询的`Key`(键)。
2. 从单版本分布式数据库中获取数据。
......@@ -150,6 +156,7 @@
```
7. 同步数据到其他设备。
选择同一组网环境下的设备以及同步模式,进行数据同步。
> **说明**:
......@@ -183,7 +190,11 @@
});
```
## 相关实例
针对分布式数据开发,有以下相关实例可供参考:
- [`DDMQuery`:结果集与谓词(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/data/DDMQuery)
- [`KvStore`:分布式数据库(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore)
- [`DistributedCalc`:分布式计算器(JS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/DistributeCalc)
- [`DistributedCalc`:分布式计算器(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/DistributeCalc)
- [`DDMQuery`:结果集与谓词(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DDMQuery)
- [`KvStore`:分布式数据库(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/Kvstore)
- [分布式数据库(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData)
\ No newline at end of file
......@@ -273,5 +273,5 @@
## 相关实例
针对关系型数据库开发,有以下相关实例可供参考:
- [`Rdb`:关系型数据库(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Rdb)
- [`DistributedRdb`:分布式关系型数据库(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/data/DistributedRdb)
- [`DistributedRdb`:分布式关系型数据库(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DistributedRdb)
- [关系型数据库(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Data/JSRelationshipData)
......@@ -207,4 +207,4 @@ import stats from '@ohos.bundleState';
```
## 相关实例
针对设备使用信息统计,有以下相关实例可供参考:
- [`DeviceUsageStatistics`:设备使用信息统计(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/device/DeviceUsageStatistics)
\ No newline at end of file
- [`DeviceUsageStatistics`:设备使用信息统计(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/DeviceUsageStatistics)
\ No newline at end of file
......@@ -128,4 +128,4 @@
针对传感器开发,有以下相关实例可供参考:
- [`Sensor`:传感器(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/device/Sensor)
\ No newline at end of file
- [`Sensor`:传感器(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Sensor)
\ No newline at end of file
......@@ -155,4 +155,4 @@ USB设备可作为Host设备连接Device设备进行数据传输。开发示例
```
## 相关实例
针对USB管理开发,有以下相关实例可供参考:
- [`USBManager`:USB管理(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/device/USBManager)
\ No newline at end of file
- [`USBManager`:USB管理(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/USBManager)
\ No newline at end of file
......@@ -89,4 +89,4 @@
针对振动开发,有以下相关实例可供参考:
- [`Vibrator`:振动(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/device/Vibrator)
\ No newline at end of file
- [`Vibrator`:振动(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Vibrator)
\ No newline at end of file
......@@ -94,4 +94,4 @@
针对应用事件打点开发,有以下相关实例可供参考:
- [`JsDotTest`:测试打点(JS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/DFX/JsDotTest)
\ No newline at end of file
- [`JsDotTest`:测试打点(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/DFX/JsDotTest)
\ No newline at end of file
......@@ -256,7 +256,7 @@ export class AudioDemo {
针对音频播放开发,有以下相关实例可供参考:
- [`JsDistributedMusicPlayer`:分布式音乐播放(JS)(API7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer)
- [`JsAudioPlayer`:音频播放和管理(JS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer)
- [`eTsAudioPlayer`: 音频播放器(eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [音频播放器](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
\ No newline at end of file
- [`JsDistributedMusicPlayer:`分布式音乐播放(JS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/JsDistributedMusicPlayer)
- [`JsAudioPlayer`:音频播放和管理(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/JsAudioPlayer)
- [`eTsAudioPlayer`: 音频播放器(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [音频播放器(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
\ No newline at end of file
......@@ -190,7 +190,7 @@ export class AudioRecorderDemo {
针对音频录制开发,有以下相关实例可供参考:
- [`Recorder`:录音机(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder)
- [`JsRecorder`:录音机(JS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/media/JSRecorder)
- [`eTsAudioPlayer`: 音频播放器(eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [音频播放器](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
- [`Recorder:`录音机(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/Recorder)
- [`JsRecorder`:录音机(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/JSRecorder)
- [`eTsAudioPlayer`: 音频播放器(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [音频播放器(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
......@@ -271,3 +271,8 @@ imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> {})
```
## 相关实例
针对图片开发,有以下相关实例可供参考:
- [`Image`:图片处理(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/Image)
......@@ -445,8 +445,3 @@ export class VideoPlayerDemo {
}
}
```
## 相关实例
针对视频播放开发,有以下相关实例可供参考:
- [`VideoPlayer`:视频播放(eTS)(API9)](https://gitee.com/openharmony/app_samples/tree/master/media/VideoPlayer)
\ No newline at end of file
......@@ -638,4 +638,4 @@ export default {
```
## 相关实例
针对Native API的开发,有以下相关实例可供参考:
- [`NativeAPI`:NativeAPI(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/Native/NativeAPI)
- [`NativeAPI`:NativeAPI(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Native/NativeAPI)
......@@ -174,5 +174,5 @@ if (this.subscriber != null) {
针对公共事件开发,有以下相关实例可供参考:
- [`CommonEvent`:订阅公共事件(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/Notification/CommonEvent)
- [`CommonEvent`:订阅公共事件(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Notification/CommonEvent)
......@@ -248,5 +248,4 @@ Notification.cancel(1, "label", cancelCallback)
## 相关实例
针对通知开发,有以下相关可供参考:
- [`Notification`:订阅、发送通知(eTS)(API9)](https://gitee.com/openharmony/app_samples/tree/master/Notification/Notification)
- [`Notification`:通知(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/common/Notification)
- [`Notification`:通知(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/Notification)
......@@ -218,6 +218,8 @@
![zh-cn_image_0000001217527892](figures/zh-cn_image_0000001217527892.png)
恭喜您已经使用JS语言开发(传统代码方式)完成了第一个OpenHarmony应用,快来[探索更多的OpenHarmony功能](../application-dev-guide.md)吧。
## 相关实例
针对使用JS语言(传统代码方式)开发快速入门,有以下相关实例可供参考:
- [`JsHelloWorld`:你好世界(JS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/common/JsHelloWorld)
- [`JsHelloWorld`:你好世界(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/JsHelloWorld)
# 应用帐号管理
# 应用帐号管理
> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
......@@ -15,7 +15,7 @@ import account_appAccount from '@ohos.account.appAccount';
createAppAccountManager(): AppAccountManager
应用帐号管理:获取应用帐号模块对象。
获取应用帐号模块对象。
**系统能力:** SystemCapability.Account.AppAccount
......@@ -151,7 +151,7 @@ addAccountImplicitly(owner: string, authType: string, options: {[key: string]: a
}
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.addAccountImplicitly("LiSi", "readAge", {}, {
appAccountManager.addAccountImplicitly("com.example.ohos.accountjsdemo", "getSocialData", {}, {
onResult: onResultCallback,
onRequestRedirected: onRequestRedirectedCallback
});
......@@ -318,7 +318,8 @@ enableAppAccess(name: string, bundleName: string): Promise&lt;void&gt;
**示例:**
```js
app_account_instance.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => {
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => {
console.log('enableAppAccess Success');
}).catch((err) => {
console.log("enableAppAccess err: " + JSON.stringify(err));
......@@ -331,7 +332,7 @@ checkAppAccountSyncEnable(name: string, callback: AsyncCallback&lt;boolean&gt;):
检查指定应用帐号是否允许应用数据同步,使用callback回调异步返回结果。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC,仅系统应用可用。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.Account.AppAccount
......@@ -358,7 +359,7 @@ checkAppAccountSyncEnable(name: string): Promise&lt;boolean&gt;
检查指定应用帐号是否允许应用数据同步,使用Promise方式异步返回结果。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC,仅系统应用可用。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.Account.AppAccount
......@@ -507,7 +508,7 @@ setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback
设置指定的应用程序帐号是否允许应用程序数据同步,使用callback回调异步返回结果。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC,仅系统应用可用。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.Account.AppAccount
......@@ -534,7 +535,7 @@ setAppAccountSyncEnable(name: string, isEnable: boolean): Promise&lt;void&gt;
设置指定的应用程序帐号是否允许应用程序数据同步,使用Promise方式异步返回结果。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC,仅系统应用可用。
**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC
**系统能力:** SystemCapability.Account.AppAccount
......@@ -582,7 +583,8 @@ setAssociatedData(name: string, key: string, value: string, callback: AsyncCallb
**示例:**
```js
app_account_instance.setAssociatedData("ZhangSan", "k001", "v001", (err) => {
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setAssociatedData("ZhangSan", "k001", "v001", (err) => {
console.log("setAssociatedData err: " + JSON.stringify(err));
});
```
......@@ -1007,7 +1009,7 @@ authenticate(name: string, owner: string, authType: string, options: {[key: stri
}
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.authenticate("LiSi", "com.example.ohos.accountjsdemo", "readAge", {}, {
appAccountManager.authenticate("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", {}, {
onResult: onResultCallback,
onRequestRedirected: onRequestRedirectedCallback
});
......@@ -1034,7 +1036,7 @@ getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCall
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", (err, data) => {
appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", (err, data) => {
console.log('getOAuthToken err: ' + JSON.stringify(err));
console.log('getOAuthToken token: ' + data);
});
......@@ -1066,7 +1068,7 @@ getOAuthToken(name: string, owner: string, authType: string): Promise&lt;string&
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge").then((data) => {
appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData").then((data) => {
console.log('getOAuthToken token: ' + data);
}).catch((err) => {
console.log("getOAuthToken err: " + JSON.stringify(err));
......@@ -1094,7 +1096,7 @@ setOAuthToken(name: string, authType: string, token: string, callback: AsyncCall
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setOAuthToken("LiSi", "readAge", "xxxx", (err) => {
appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx", (err) => {
console.log('setOAuthToken err: ' + JSON.stringify(err));
});
```
......@@ -1125,7 +1127,7 @@ setOAuthToken(name: string, authType: string, token: string): Promise&lt;void&gt
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setOAuthToken("LiSi", "readAge", "xxxx").then(() => {
appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx").then(() => {
console.log('setOAuthToken successfully');
}).catch((err) => {
console.log('setOAuthToken err: ' + JSON.stringify(err));
......@@ -1154,7 +1156,7 @@ deleteOAuthToken(name: string, owner: string, authType: string, token: string, c
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", "xxxxx", (err) => {
appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx", (err) => {
console.log('deleteOAuthToken err: ' + JSON.stringify(err));
});
```
......@@ -1186,7 +1188,7 @@ deleteOAuthToken(name: string, owner: string, authType: string, token: string):
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", "xxxxx").then(() => {
appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx").then(() => {
console.log('deleteOAuthToken successfully');
}).catch((err) => {
console.log("deleteOAuthToken err: " + JSON.stringify(err));
......@@ -1215,7 +1217,7 @@ setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVi
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true, (err) => {
appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true, (err) => {
console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err));
});
```
......@@ -1247,7 +1249,7 @@ setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVi
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.setOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true).then(() => {
appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true).then(() => {
console.log('setOAuthTokenVisibility successfully');
}).catch((err) => {
console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err));
......@@ -1275,7 +1277,7 @@ checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, ca
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.checkOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true, (err, data) => {
appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", (err, data) => {
console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err));
console.log('checkOAuthTokenVisibility isVisible: ' + data);
});
......@@ -1307,7 +1309,7 @@ checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): P
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.checkOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true).then((data) => {
appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo").then((data) => {
console.log('checkOAuthTokenVisibility isVisible: ' + data);
}).catch((err) => {
console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err));
......@@ -1392,7 +1394,7 @@ getOAuthList(name: string, authType: string, callback: AsyncCallback&lt;Array&lt
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "readAge", (err, data) => {
appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData", (err, data) => {
console.log('getOAuthList err: ' + JSON.stringify(err));
console.log('getOAuthList data: ' + JSON.stringify(data));
});
......@@ -1423,7 +1425,7 @@ getOAuthList(name: string, authType: string): Promise&lt;Array&lt;string&gt;&gt;
```js
const appAccountManager = account_appAccount.createAppAccountManager();
appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "readAge").then((data) => {
appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData").then((data) => {
console.log('getOAuthList data: ' + JSON.stringify(data));
}).catch((err) => {
console.log("getOAuthList err: " + JSON.stringify(err));
......@@ -1458,7 +1460,7 @@ getAuthenticatorCallback(sessionId: string, callback: AsyncCallback&lt;Authentic
}
var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi",
[account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo",
[account_appAccount.Constants.KEY_AUTH_TYPE]: "readAge",
[account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData",
[account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"};
callback.OnResult(account_appAccount.ResultCode.SUCCESS, result);
});
......@@ -1494,7 +1496,7 @@ getAuthenticatorCallback(sessionId: string): Promise&lt;AuthenticatorCallback&gt
appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => {
var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi",
[account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo",
[account_appAccount.Constants.KEY_AUTH_TYPE]: "readAge",
[account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData",
[account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"};
callback.OnResult(account_appAccount.ResultCode.SUCCESS, result);
}).catch((err) => {
......@@ -1592,8 +1594,8 @@ getAuthenticatorInfo(owner: string): Promise&lt;AuthenticatorInfo&gt;
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------ | ---- | ---------- |
| owner | string | 是 | 认证器的所有者包名。 |
| iconId | string | 是 | 认证器的图标标识。 |
| labelId | string | 是 | 认证器的标签标识。 |
| iconId | number | 是 | 认证器的图标标识。 |
| labelId | number | 是 | 认证器的标签标识。 |
## Constants<sup>8+</sup>
......@@ -1669,7 +1671,7 @@ onResult: (code: number, result: {[key: string]: any}) =&gt; void
appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => {
var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi",
[account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo",
[account_appAccount.Constants.KEY_AUTH_TYPE]: "readAge",
[account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData",
[account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"};
callback.OnResult(account_appAccount.ResultCode.SUCCESS, result);
}).catch((err) => {
......
......@@ -60,7 +60,7 @@ createVideoPlayer(callback: AsyncCallback\<[VideoPlayer](#videoplayer8)>): void
let videoPlayer
media.createVideoPlayer((error, video) => {
if (typeof(video) != 'undefined') {
if (video != null) {
videoPlayer = video;
console.info('video createVideoPlayer success');
} else {
......@@ -89,7 +89,7 @@ createVideoPlayer(): Promise<[VideoPlayer](#videoplayer8)>
let videoPlayer
media.createVideoPlayer().then((video) => {
if (typeof(video) != 'undefined') {
if (video != null) {
videoPlayer = video;
console.info('video createVideoPlayer success');
} else {
......@@ -307,7 +307,7 @@ seek(timeMs: number): void
```js
audioPlayer.on('timeUpdate', (seekDoneTime) => { //设置'timeUpdate'事件回调
if (typeof (seekDoneTime) == 'undefined') {
if (seekDoneTime == null) {
console.info('audio seek fail');
return;
}
......@@ -380,7 +380,7 @@ function printfDescription(obj) {
}
audioPlayer.getTrackDescription((error, arrlist) => {
if (typeof (arrlist) != 'undefined') {
if (arrlist != null) {
for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]);
}
......@@ -416,7 +416,7 @@ function printfDescription(obj) {
}
audioPlayer.getTrackDescription().then((arrlist) => {
if (typeof (arrlist) != 'undefined') {
if (arrlist != null) {
arrayDescription = arrlist;
} else {
console.log('audio getTrackDescription fail');
......@@ -491,7 +491,7 @@ audioPlayer.on('reset', () => { //设置'reset'事件回调
audioPlayer = undefined;
});
audioPlayer.on('timeUpdate', (seekDoneTime) => { //设置'timeUpdate'事件回调
if (typeof(seekDoneTime) == "undefined") {
if (seekDoneTime == null) {
console.info('audio seek fail');
return;
}
......@@ -546,7 +546,7 @@ on(type: 'timeUpdate', callback: Callback\<number>): void
```js
audioPlayer.on('timeUpdate', (seekDoneTime) => { //设置'timeUpdate'事件回调
if (typeof (seekDoneTime) == 'undefined') {
if (seekDoneTime == null) {
console.info('audio seek fail');
return;
}
......@@ -634,7 +634,7 @@ setDisplaySurface(surfaceId: string, callback: AsyncCallback\<void>): void
```js
videoPlayer.setDisplaySurface(surfaceId, (err) => {
if (typeof (err) == 'undefined') {
if (err == null) {
console.info('setDisplaySurface success!');
} else {
console.info('setDisplaySurface fail!');
......@@ -690,7 +690,7 @@ prepare(callback: AsyncCallback\<void>): void
```js
videoPlayer.prepare((err) => {
if (typeof (err) == 'undefined') {
if (err == null) {
console.info('prepare success!');
} else {
console.info('prepare fail!');
......@@ -740,7 +740,7 @@ play(callback: AsyncCallback\<void>): void;
```js
videoPlayer.play((err) => {
if (typeof (err) == 'undefined') {
if (err == null) {
console.info('play success!');
} else {
console.info('play fail!');
......@@ -790,7 +790,7 @@ pause(callback: AsyncCallback\<void>): void
```js
videoPlayer.pause((err) => {
if (typeof (err) == 'undefined') {
if (err == null) {
console.info('pause success!');
} else {
console.info('pause fail!');
......@@ -840,7 +840,7 @@ stop(callback: AsyncCallback\<void>): void
```js
videoPlayer.stop((err) => {
if (typeof (err) == 'undefined') {
if (err == null) {
console.info('stop success!');
} else {
console.info('stop fail!');
......@@ -890,7 +890,7 @@ reset(callback: AsyncCallback\<void>): void
```js
videoPlayer.reset((err) => {
if (typeof (err) == 'undefined') {
if (err == null) {
console.info('reset success!');
} else {
console.info('reset fail!');
......@@ -941,7 +941,7 @@ seek(timeMs: number, callback: AsyncCallback\<number>): void
```js
videoPlayer.seek((seekTime, err) => {
if (typeof (err) == 'undefined') {
if (err == null) {
console.info('seek success!');
} else {
console.info('seek fail!');
......@@ -969,7 +969,7 @@ seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\<number>): void
```js
videoPlayer.seek((seekTime, seekMode, err) => {
if (typeof (err) == 'undefined') {
if (err == null) {
console.info('seek success!');
} else {
console.info('seek fail!');
......@@ -1033,7 +1033,7 @@ setVolume(vol: number, callback: AsyncCallback\<void>): void
```js
videoPlayer.setVolume((vol, err) => {
if (typeof (err) == 'undefined') {
if (err == null) {
console.info('setVolume success!');
} else {
console.info('setVolume fail!');
......@@ -1089,7 +1089,7 @@ release(callback: AsyncCallback\<void>): void
```js
videoPlayer.release((err) => {
if (typeof (err) == 'undefined') {
if (err == null) {
console.info('release success!');
} else {
console.info('release fail!');
......@@ -1147,7 +1147,7 @@ function printfDescription(obj) {
}
videoPlayer.getTrackDescription((error, arrlist) => {
if (typeof (arrlist) != 'undefined') {
if (arrlist != null) {
for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]);
}
......@@ -1184,7 +1184,7 @@ function printfDescription(obj) {
let arrayDescription;
videoPlayer.getTrackDescription().then((arrlist) => {
if (typeof (arrlist) != 'undefined') {
if (arrlist != null) {
arrayDescription = arrlist;
} else {
console.log('video getTrackDescription fail');
......@@ -1216,7 +1216,7 @@ setSpeed(speed:number, callback: AsyncCallback\<number>): void
```js
videoPlayer.setSpeed((speed:number, err) => {
if (typeof (err) == 'undefined') {
if (err == null) {
console.info('setSpeed success!');
} else {
console.info('setSpeed fail!');
......@@ -1437,7 +1437,7 @@ function printfItemDescription(obj, key) {
}
audioPlayer.getTrackDescription((error, arrlist) => {
if (typeof (arrlist) != 'undefined') {
if (arrlist != null) {
for (let i = 0; i < arrlist.length; i++) {
printfItemDescription(arrlist[i], MD_KEY_TRACK_TYPE); //打印出每条轨道MD_KEY_TRACK_TYPE的值
}
......
......@@ -7,6 +7,8 @@ WebGL标准图形API,对应OpenGL ES 2.0特性集。更多信息请参考[WebG
> **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
>
> WebGL遵循OpenGL协议,不支持多线程调用。
......
......@@ -7,6 +7,8 @@ WebGL标准图形API,对应OpenGL ES 3.0特性集。更多信息请参考[WebG
> **说明:**
>
> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
>
> WebGL2遵循OpenGL协议,不支持多线程调用。
......
......@@ -74,15 +74,15 @@ caretPosition(value: number): void
@Entry
@Component
struct SearchExample {
@State changevalue: string = ''
@State submitvalue: string = ''
@State changeValue: string = ''
@State submitValue: string = ''
controller: SearchController = new SearchController()
build() {
Flex({ direction: FlexDirection.Row, justifyContent: FlexAlign.Center, alignItems: ItemAlign.Center }) {
Text(this.submitvalue)
Text(this.changevalue)
Search({value: this.changevalue, placeholder: 'Type to search', controller: this.controller})
Text(this.submitValue)
Text(this.changeValue)
Search({value: this.changeValue, placeholder: 'Type to search', controller: this.controller})
.searchButton('Search')
.width(400)
.height(35)
......@@ -90,10 +90,10 @@ struct SearchExample {
.placeholderColor(Color.Grey)
.placeholderFont({ size: 26, weight: 10, family: 'serif', style: FontStyle.Normal })
.onSubmit((value: string) => {
this.submitvalue = value
this.submitValue = value
})
.onChange((value: string) => {
this.changevalue += value
this.changeValue = value
})
.margin({ top: 30, left:10, right:10 })
}
......
......@@ -130,16 +130,17 @@ onStart() {
var context = featureAbility.getContext()
let array:Array<string> = ["ohos.permission.PERMISSION2"];
//requestPermissionsFromUser会判断权限的授权状态来决定是否唤起弹窗
context.requestPermissionsFromUser(array).then(function(data) {
console.log("data type:" + typeof(data));
console.log("data:" + data);
console.log("data permissions:" + data.permissions);
console.log("data result:" + data.authResults);
}, (err) => {
console.error('Failed to start ability', err.code);
});
context.requestPermissionsFromUser(array, 1, (err, data)=>{
console.info("====>requestdata====>" + JSON.stringify(data));
console.info("====>requesterrcode====>" + JSON.stringify(err.code));
}
}
```
> **说明:**
> 动态授权申请接口的使用详见[API参考](../reference/apis/js-apis-ability-context.md)。
## 相关实例
针对访问控制,有以下相关实例可供参考:
- [`AbilityAccessCtrl`:访问权限控制(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Safety/AbilityAccessCtrl)
\ No newline at end of file
......@@ -704,4 +704,4 @@ WebGL主要帮助开发者在前端开发中完成图形图像的相关处理,
针对WebGL开发,有以下相关实例可供参考:
- [`JsWbgGL`:WebGL(JS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/Graphics/JsWebGL)
- [`JsWbgGL`:WebGL(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Graphics/JsWebGL)
......@@ -21,7 +21,4 @@ display.getDefaultDisplay().then((disp) => {
}, (err) => {
console.log('display.getDefaultDisplay failed, error : ' + JSON.stringify(err));
})
```
## 相关实例
针对屏幕属性开发,有以下相关实例可供参考:
- [`Screen`:屏幕属性(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/device/Screen)
```
\ No newline at end of file
......@@ -35,6 +35,3 @@ screenshot.save(ScreenshotOptions).then((image) => {
console.log('screenshot.save failed, error : ' + JSON.stringify(err));
})
```
## 相关实例
针对屏幕截图开发,有以下相关实例可供参考:
- [`Screenshot`:屏幕截图(eTS)(API9)](https://gitee.com/openharmony/app_samples/tree/master/Basic/Screenshot)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册