未验证 提交 30ed0a9d 编写于 作者: O openharmony_ci 提交者: Gitee

!7347 翻译完成 7138

Merge pull request !7347 from ester.zhou/TR-7138
...@@ -9,6 +9,5 @@ ...@@ -9,6 +9,5 @@
- Development Fundamentals - Development Fundamentals
- [Application Package Structure Configuration File (FA Model)](package-structure.md) - [Application Package Structure Configuration File (FA Model)](package-structure.md)
- [Application Package Structure Configuration File (Stage Model)](stage-structure.md) - [Application Package Structure Configuration File (Stage Model)](stage-structure.md)
- [Resource File Categories](basic-resource-file-categories.md)
- [SysCap](syscap.md) - [SysCap](syscap.md)
- [HarmonyAppProvision Configuration File](app-provision-structure.md) - [HarmonyAppProvision Configuration File](app-provision-structure.md)
# JavaScript-based Web-like Development Paradigm # JavaScript-based Web-like Development Paradigm
- Components - Universal Component Information
- Common - [Universal Attributes](js-components-common-attributes.md)
- [Universal Attributes](js-components-common-attributes.md) - [Universal Styles](js-components-common-styles.md)
- [Universal Styles](js-components-common-styles.md) - [Universal Events](js-components-common-events.md)
- [Universal Events](js-components-common-events.md) - [Universal Methods](js-components-common-methods.md)
- [Universal Methods](js-components-common-methods.md) - [Animation Styles](js-components-common-animation.md)
- [Animation Styles](js-components-common-animation.md) - [Gradient Styles](js-components-common-gradient.md)
- [Gradient Styles](js-components-common-gradient.md) - [Transition Styles](js-components-common-transition.md)
- [Transition Styles](js-components-common-transition.md) - [Media Query](js-components-common-mediaquery.md)
- [Media Query](js-components-common-mediaquery.md) - [Custom Font Styles](js-components-common-customizing-font.md)
- [Custom Font Styles](js-components-common-customizing-font.md) - [Atomic Layout](js-components-common-atomic-layout.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)
- [xcomponent](js-components-basic-xcomponent.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)
- [xcomponent](js-components-basic-xcomponent.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 - Custom Components
- [Basic Usage](js-components-custom-basic-usage.md) - [Basic Usage](js-components-custom-basic-usage.md)
- [Style Inheritance](js-components-custom-style.md) - [Style Inheritance](js-components-custom-style.md)
- [Custom Events](js-components-custom-events.md) - [Custom Events](js-components-custom-events.md)
- [props](js-components-custom-props.md) - [props](js-components-custom-props.md)
- [Event Parameter](js-components-custom-event-parameter.md) - [Event Parameter](js-components-custom-event-parameter.md)
- [slot](js-components-custom-slot.md) - [slot](js-components-custom-slot.md)
- [Lifecycle Definition](js-components-custom-lifecycle.md) - [Lifecycle Definition](js-components-custom-lifecycle.md)
- Appendix - [Data Type Attributes](js-appendix-types.md)
- [Type Attributes](js-appendix-types.md)
# Type Attributes # Data Type Attributes
## Length Type ## Length Type
......
# TypeScript-based Declarative Development Paradigm # TypeScript-based Declarative Development Paradigm
- Components - Universal Component Information
- Universal Components - Universal Events
- Universal Events - [Click Event](ts-universal-events-click.md)
- [Click Event](ts-universal-events-click.md) - [Touch Event](ts-universal-events-touch.md)
- [Touch Event](ts-universal-events-touch.md) - [Show/Hide Event](ts-universal-events-show-hide.md)
- [Show/Hide Event](ts-universal-events-show-hide.md) - [Drag/Drop Event](ts-universal-events-drag-drop.md)
- [Drag/Drop Event](ts-universal-events-drag-drop.md) - [Key Event](ts-universal-events-key.md)
- [Key Event](ts-universal-events-key.md) - [Focus Event](ts-universal-focus-event.md)
- [Focus Event](ts-universal-focus-event.md) - [Mouse Event](ts-universal-mouse-key.md)
- [Mouse Event](ts-universal-mouse-key.md) - [Component Area Change Event](ts-universal-component-area-change-event.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 - Universal Attributes
- [Size](ts-universal-attributes-size.md) - [Size](ts-universal-attributes-size.md)
- [Location](ts-universal-attributes-location.md) - [Location](ts-universal-attributes-location.md)
- [Layout Constraints](ts-universal-attributes-layout-constraints.md) - [Layout Constraints](ts-universal-attributes-layout-constraints.md)
- [Flex Layout](ts-universal-attributes-flex-layout.md) - [Flex Layout](ts-universal-attributes-flex-layout.md)
- [Border](ts-universal-attributes-border.md) - [Border](ts-universal-attributes-border.md)
- [Background](ts-universal-attributes-background.md) - [Border Image](ts-universal-attributes-border-image.md)
- [Opacity](ts-universal-attributes-opacity.md) - [Background](ts-universal-attributes-background.md)
- [Visibility](ts-universal-attributes-visibility.md) - [Opacity](ts-universal-attributes-opacity.md)
- [Enable/Disable](ts-universal-attributes-enable.md) - [Visibility](ts-universal-attributes-visibility.md)
- [Overlay](ts-universal-attributes-overlay.md) - [Enable/Disable](ts-universal-attributes-enable.md)
- [Z-order Control](ts-universal-attributes-z-order.md) - [Overlay](ts-universal-attributes-overlay.md)
- [Transformation](ts-universal-attributes-transformation.md) - [Z-order Control](ts-universal-attributes-z-order.md)
- [Image Effect Configuration](ts-universal-attributes-image-effect.md) - [Transformation](ts-universal-attributes-transformation.md)
- [Shape Clipping](ts-universal-attributes-sharp-clipping.md) - [Image Effect Configuration](ts-universal-attributes-image-effect.md)
- [Text Style](ts-universal-attributes-text-style.md) - [Shape Clipping](ts-universal-attributes-sharp-clipping.md)
- [Grid](ts-universal-attributes-grid.md) - [Text Style](ts-universal-attributes-text-style.md)
- [Gradient Color](ts-universal-attributes-gradient-color.md) - [Grid](ts-universal-attributes-grid.md)
- [Popup Control](ts-universal-attributes-popup.md) - [Gradient Color](ts-universal-attributes-gradient-color.md)
- [Menu Control](ts-universal-attributes-menu.md) - [Popup Control](ts-universal-attributes-popup.md)
- [Click Control](ts-universal-attributes-click.md) - [Menu Control](ts-universal-attributes-menu.md)
- [Focus Control](ts-universal-attributes-focus.md) - [Click Control](ts-universal-attributes-click.md)
- [Hover Effect](ts-universal-attributes-hover-effect.md) - [Focus Control](ts-universal-attributes-focus.md)
- [Component ID](ts-universal-attributes-component-id.md) - [Hover Effect](ts-universal-attributes-hover-effect.md)
- [Touch Target](ts-universal-attributes-touch-target.md) - [Component ID](ts-universal-attributes-component-id.md)
- [Polymorphic Style](ts-universal-attributes-polymorphic-style.md) - [Touch Target](ts-universal-attributes-touch-target.md)
- Gesture Processing - [Polymorphic Style](ts-universal-attributes-polymorphic-style.md)
- [Gesture Binding Methods](ts-gesture-settings.md) - Gesture Processing
- Basic Gestures - [Gesture Binding Methods](ts-gesture-settings.md)
- [TapGesture](ts-basic-gestures-tapgesture.md) - Basic Gestures
- [LongPressGesture](ts-basic-gestures-longpressgesture.md) - [TapGesture](ts-basic-gestures-tapgesture.md)
- [PanGesture](ts-basic-gestures-pangesture.md) - [LongPressGesture](ts-basic-gestures-longpressgesture.md)
- [PinchGesture](ts-basic-gestures-pinchgesture.md) - [PanGesture](ts-basic-gestures-pangesture.md)
- [RotationGesture](ts-basic-gestures-rotationgesture.md) - [PinchGesture](ts-basic-gestures-pinchgesture.md)
- [SwipeGesture](ts-basic-gestures-swipegesture.md) - [RotationGesture](ts-basic-gestures-rotationgesture.md)
- [Combined Gestures](ts-combined-gestures.md) - [SwipeGesture](ts-basic-gestures-swipegesture.md)
- Basic Components - [Combined Gestures](ts-combined-gestures.md)
- [Blank](ts-basic-components-blank.md) - Basic Components
- [Button](ts-basic-components-button.md) - [Blank](ts-basic-components-blank.md)
- [Checkbox](ts-basic-components-checkbox.md) - [Button](ts-basic-components-button.md)
- [CheckboxGroup](ts-basic-components-checkboxgroup.md) - [Checkbox](ts-basic-components-checkbox.md)
- [DataPanel](ts-basic-components-datapanel.md) - [CheckboxGroup](ts-basic-components-checkboxgroup.md)
- [DatePicker](ts-basic-components-datepicker.md) - [DataPanel](ts-basic-components-datapanel.md)
- [Divider](ts-basic-components-divider.md) - [DatePicker](ts-basic-components-datepicker.md)
- [Gauge](ts-basic-components-gauge.md) - [Divider](ts-basic-components-divider.md)
- [Image](ts-basic-components-image.md) - [Gauge](ts-basic-components-gauge.md)
- [ImageAnimator](ts-basic-components-imageanimator.md) - [Image](ts-basic-components-image.md)
- [LoadingProgress](ts-basic-components-loadingprogress.md) - [ImageAnimator](ts-basic-components-imageanimator.md)
- [Marquee](ts-basic-components-marquee.md) - [LoadingProgress](ts-basic-components-loadingprogress.md)
- [Navigation](ts-basic-components-navigation.md) - [Marquee](ts-basic-components-marquee.md)
- [PatternLock](ts-basic-components-patternlock.md) - [Navigation](ts-basic-components-navigation.md)
- [PluginComponent](ts-basic-components-plugincomponent.md) - [PatternLock](ts-basic-components-patternlock.md)
- [Progress](ts-basic-components-progress.md) - [PluginComponent](ts-basic-components-plugincomponent.md)
- [QRCode](ts-basic-components-qrcode.md) - [Progress](ts-basic-components-progress.md)
- [Radio](ts-basic-components-radio.md) - [QRCode](ts-basic-components-qrcode.md)
- [Rating](ts-basic-components-rating.md) - [Radio](ts-basic-components-radio.md)
- [RichText](ts-basic-components-richtext.md) - [Rating](ts-basic-components-rating.md)
- [ScrollBar](ts-basic-components-scrollbar.md) - [RemoteWindow](ts-basic-components-remotewindow.md)
- [Search](ts-basic-components-search.md) - [RichText](ts-basic-components-richtext.md)
- [Select](ts-basic-components-select.md) - [ScrollBar](ts-basic-components-scrollbar.md)
- [Slider](ts-basic-components-slider.md) - [Search](ts-basic-components-search.md)
- [Span](ts-basic-components-span.md) - [Select](ts-basic-components-select.md)
- [Stepper](ts-basic-components-stepper.md) - [Slider](ts-basic-components-slider.md)
- [StepperItem](ts-basic-components-stepperitem.md) - [Span](ts-basic-components-span.md)
- [Text](ts-basic-components-text.md) - [Stepper](ts-basic-components-stepper.md)
- [TextArea](ts-basic-components-textarea.md) - [StepperItem](ts-basic-components-stepperitem.md)
- [TextClock](ts-basic-components-textclock.md) - [Text](ts-basic-components-text.md)
- [TextInput](ts-basic-components-textinput.md) - [TextArea](ts-basic-components-textarea.md)
- [TextPicker](ts-basic-components-textpicker.md) - [TextClock](ts-basic-components-textclock.md)
- [TextTimer](ts-basic-components-texttimer.md) - [TextInput](ts-basic-components-textinput.md)
- [TimePicker](ts-basic-components-timepicker.md) - [TextPicker](ts-basic-components-textpicker.md)
- [Toggle](ts-basic-components-toggle.md) - [TextTimer](ts-basic-components-texttimer.md)
- [Web](ts-basic-components-web.md) - [TimePicker](ts-basic-components-timepicker.md)
- [XComponent](ts-basic-components-xcomponent.md) - [Toggle](ts-basic-components-toggle.md)
- Container Components - [Web](ts-basic-components-web.md)
- [AlphabetIndexer](ts-container-alphabet-indexer.md) - [XComponent](ts-basic-components-xcomponent.md)
- [Badge](ts-container-badge.md) - Container Components
- [Column](ts-container-column.md) - [AbilityComponent](ts-container-ability-component.md)
- [ColumnSplit](ts-container-columnsplit.md) - [AlphabetIndexer](ts-container-alphabet-indexer.md)
- [Counter](ts-container-counter.md) - [Badge](ts-container-badge.md)
- [Flex](ts-container-flex.md) - [Column](ts-container-column.md)
- [GridContainer](ts-container-gridcontainer.md) - [ColumnSplit](ts-container-columnsplit.md)
- [Grid](ts-container-grid.md) - [Counter](ts-container-counter.md)
- [GridItem](ts-container-griditem.md) - [Flex](ts-container-flex.md)
- [List](ts-container-list.md) - [GridContainer](ts-container-gridcontainer.md)
- [ListItem](ts-container-listitem.md) - [Grid](ts-container-grid.md)
- [Navigator](ts-container-navigator.md) - [GridItem](ts-container-griditem.md)
- [Panel](ts-container-panel.md) - [List](ts-container-list.md)
- [Refresh](ts-container-refresh.md) - [ListItem](ts-container-listitem.md)
- [Row](ts-container-row.md) - [Navigator](ts-container-navigator.md)
- [RowSplit](ts-container-rowsplit.md) - [Panel](ts-container-panel.md)
- [Scroll](ts-container-scroll.md) - [Refresh](ts-container-refresh.md)
- [SideBarContainer](ts-container-sidebarcontainer.md) - [RelativeContainer](ts-container-relativecontainer.md)
- [Stack](ts-container-stack.md) - [Row](ts-container-row.md)
- [Swiper](ts-container-swiper.md) - [RowSplit](ts-container-rowsplit.md)
- [Tabs](ts-container-tabs.md) - [Scroll](ts-container-scroll.md)
- [TabContent](ts-container-tabcontent.md) - [SideBarContainer](ts-container-sidebarcontainer.md)
- Media Components - [Stack](ts-container-stack.md)
- [Video](ts-media-components-video.md) - [Swiper](ts-container-swiper.md)
- Drawing Components - [Tabs](ts-container-tabs.md)
- [Circle](ts-drawing-components-circle.md) - [TabContent](ts-container-tabcontent.md)
- [Ellipse](ts-drawing-components-ellipse.md) - Media Components
- [Line](ts-drawing-components-line.md)
- [Polyline](ts-drawing-components-polyline.md) - [Video](ts-media-components-video.md)
- [Polygon](ts-drawing-components-polygon.md) - Drawing Components
- [Path](ts-drawing-components-path.md) - [Circle](ts-drawing-components-circle.md)
- [Rect](ts-drawing-components-rect.md) - [Ellipse](ts-drawing-components-ellipse.md)
- [Shape](ts-drawing-components-shape.md) - [Line](ts-drawing-components-line.md)
- Canvas Components - [Polyline](ts-drawing-components-polyline.md)
- [Canvas](ts-components-canvas-canvas.md) - [Polygon](ts-drawing-components-polygon.md)
- [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) - [Path](ts-drawing-components-path.md)
- [OffscreenCanvasRenderingConxt2D](ts-offscreencanvasrenderingcontext2d.md) - [Rect](ts-drawing-components-rect.md)
- [Lottie](ts-components-canvas-lottie.md) - [Shape](ts-drawing-components-shape.md)
- [Path2D](ts-components-canvas-path2d.md) - Canvas Components
- [CanvasGradient](ts-components-canvas-canvasgradient.md) - [Canvas](ts-components-canvas-canvas.md)
- [ImageBitmap](ts-components-canvas-imagebitmap.md) - [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md)
- [ImageData](ts-components-canvas-imagedata.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 - Animation
- [AnimatorProperty](ts-animatorproperty.md) - [AnimatorProperty](ts-animatorproperty.md)
- [Explicit Animation](ts-explicit-animation.md) - [Explicit Animation](ts-explicit-animation.md)
......
# RemoteWindow
**\<RemoteWindow>** is a component used to control the application window, providing the component animator and application window linkage animator during application startup and exit.
> **NOTE**
>
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
>
> This component is a system API.
## Child Components
Not supported
## APIs
RemoteWindow(target: WindowAnimationTarget)
Creates a **\<RemoteWindow>** through a window animation object.
- Parameters
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| target | [WindowAnimationTarget](#windowanimationtarget) | Yes| - | Description of the animation window to control.|
## WindowAnimationTarget
Implements a target window, which is used to remotely control the animation.
| Name | Type | Description|
| ------- | ------ | ----------------------- |
| bundleName | string | Process corresponding to the animation window.|
| abilityName | string | Ability corresponding to the animation window.|
| windowBounds | [RRect](#rrect) | Actual size of the animation window.|
## RRect
Implements a rounded rectangle.
| Name | Type | Description|
| ------- | ------ | ----------------------- |
| left | number | Horizontal coordinate of the upper left corner of the animation window relative to the screen.|
| top | number | Vertical coordinate of the upper left corner of the animation window relative to the screen.|
| width | number | Width of the animation window.|
| height | number | Height of the animation window.|
| radius | number | Radius of the rounded corner of the animation window.|
## Attributes
The [universal attributes](ts-universal-attributes-size.md) are supported.
## Events
The [universal events](ts-universal-events-click.md) are supported.
## Example
```ts
// xxx.ets
@Entry
@Component
struct RemoteWindowExample {
@State target: WindowAnimationTarget = undefined // Obtained through windowAnimationManager
build() {
Column() {
RemoteWindow(this.target)
.translate({x:100, y:200})
.scale({x:0.5, y:0.5})
.opacity(0.8)
.position({x:px2vp(this.target?.windowBounds.left), y:px2vp(this.target?.windowBounds.top)})
.width(px2vp(this.target?.windowBounds.width))
.height(px2vp(this.target?.windowBounds.height))
}
}
}
```
...@@ -1771,17 +1771,17 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sWidth: number, ...@@ -1771,17 +1771,17 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sWidth: number,
Draws an image. Draws an image.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | 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. | | 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. | | 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. | | 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. | | sWidth | number | No | 0 | Target width to crop the source image. |
| sHeight | number | No | 0 | Target height 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. | | 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. | | 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. | | 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. | | 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 - Example
......
# AbilityComponent
> **NOTE**
>
> This component is supported since API version 9.
>
> The APIs of this module are system APIs and cannot be called by third-party applications.
**\<AbilityComponent>** is a container for independently displaying an ability.
## Constraints
Using **\<AbilityComponent>** requires a signature and related permissions.
**\<AbilityComponent>** is rendered independently and cannot be overlaid with other display content.
**\<AbilityComponent>** cannot process input events. Events are directly distributed to the internal ability for processing without passing through the current ability.
Only width and height can be set for **\<AbilityComponent>**. These attributes are mandatory and cannot be dynamically updated.
The ability to be started must be resizeable.
The ability to start must be set not to display on the recent tasks screen.
## Required Permissions
ohos.permission.INFUSE_EVENTS
ohos.permission.CONTROL_ABILITY_STACKS
ohos.permission.INTEGRATED_ABILITY
ohos.permission.INTEGRATED_INTERIOR_WINDOW
## Child Components
Not supported
## APIs
AbilityComponent(value: {want : Want, controller? : AbilityController})
- Parameters
| Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- |
| want | [Want](../../reference/apis/js-apis-application-Want.md) | Yes| - | Description of the default ability to load.|
| controller | [AbilityController](#abilityController) | No| - | Ability controller.|
## Events
| Name| Description|
| -------- | -------- |
| onReady()&nbsp;=&gt;&nbsp;void | Called when this **\<AbilityComponent>** is started. You can then use APIs in the **\<AbilityComponent>**.|
| onDestroy()&nbsp;=&gt;&nbsp;void | Called when this **\<AbilityComponent>** is destroyed.|
| onAbilityCreated(name:&nbsp;string)&nbsp;=&gt;&nbsp;void | Called when the specified ability is loaded.|
| onAbilityMoveToFont()&nbsp;=&gt;&nbsp;void | Called when this ability is moved to the foreground.|
| onAbilityWillRemove()&nbsp;=&gt;&nbsp;void | Called when this ability is about to be removed.|
## AbilityController
Implements an ability controller, which provides the control APIs for **\<AbilityComponent>**.
| Name | Description |
| --------------------------------------- | ------------------------------------------------------------ |
| startAbility()&nbsp;=&gt;&nbsp;want | Loads an ability inside the **\<AbilityComponent>**.<br>**want**: description of the ability to be loaded.|
| preformBackPress()&nbsp;=&gt;&nbsp;void | Performs a return operation inside the **\<AbilityComponent>**. |
| getStackCount()&nbsp;=&gt;&nbsp;void | Obtains the number of tasks in the internal task stack of the **\<AbilityComponent>**. |
## Example
```ts
// xxx.ets
@Entry
@Component
struct MyComponent {
@State controller: AbilityController = new AbilityController()
build() {
Column() {
AbilityComponent({
want: {
bundleName: '',
abilityName: ''
},
controller: this.controller
})
.onReady(() => {
console.log('AbilityComponent ready');
})
.onDestory(() => {
console.log('AbilityComponent destory');
})
Button("Start New")
.onClick(() => {
this.controller.startAbility({
bundleName: '',
abilityName: ''
});
})
Button("Back")
.onClick(() => {
if (this.controller.getStacjCount() > 1) {
this.controller.preformBackPress();
}
})
}
}
}
```
# RelativeContainer
The **\<RelativeContainer>** component is used for element alignment in complex scenarios.
> **NOTE**
>
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Rules
* Components in a container are aligned horizontally or vertically.
* Alignment modes in the horizontal direction can be left, center, or right, achieved by the **HorizontalAlign.Start**, **HorizontalAlign.Center**, and **HorizontalAlign.End** attributes of the container, respectively.
* Alignment modes in the vertical direction can be top, center, or bottom, achieved by the **VerticalAlign.Top**, **VerticalAlign.Center**, and **VerticalAlign.Bottom** attributes of the container, respectively.
* A child component can set the container or another child component as the anchor point.
* An ID must be set for the child components in the **\<RelativeContainer>**. The container ID is fixed at **__container__**.
* By default, a child component without an ID is positioned in the upper left corner of the container.
* Three positions in a direction of the child component can use three positions in the same direction of the container or another child components as anchor points. When anchor points are set for more than two positions in the same direction, the third position is skipped.
* When anchor points are set for more than two positions in the same direction, the width and height of the child component do not take effect.
* If offset is required after the alignment, it can be set through **offset**.
* Exceptions
* When a mutual or circular dependency occurs, all child components in the container are not drawn.
* If anchors are set for more than two positions in the same direction but the anchor positions are reversed, the size of the child component is 0, that is, the child component is not drawn.
## Required Permissions
None
## Child Components
Multiple child components are supported.
## APIs
RelativeContainer()
## Example
```ts
@Entry
@Component
struct Index {
build() {
Row() {
Button("Extra button").width(100).height(50)
RelativeContainer() {
Button("Button 1").width(120).height(30)
.alignRules({
middle: { anchor: "__container__", align: HorizontalAlign.Center },
})
.id("bt1").borderWidth(1).borderColor(Color.Black)
Text("This is text 2").fontSize(20).padding(10)
.alignRules({
bottom: { anchor: "__container__", align: VerticalAlign.Bottom },
top: { anchor: "bt1", align: VerticalAlign.Bottom },
right:{ anchor: "bt1", align: HorizontalAlign.Center }
}).id("tx2").borderWidth(1).borderColor(Color.Black).height(30)
LoadingProgress().color(Color.Blue)
.alignRules({
left: { anchor: "bt1", align: HorizontalAlign.End },
top: { anchor: "tx2", align: VerticalAlign.Center },
bottom: { anchor: "__container__", align: VerticalAlign.Bottom }
}).id("lp3").borderWidth(1).borderColor(Color.Black)
.height(30).width(30)
Gauge({ value: 50, min: 0, max: 100 })
.startAngle(210).endAngle(150)
.colors([[0x317AF7, 1], [0x5BA854, 1], [0xE08C3A, 1], [0x9C554B, 1], [0xD94838, 1]])
.strokeWidth(20)
.width(50).height(50)
.alignRules({
left: { anchor: "tx2", align: HorizontalAlign.End },
right:{ anchor: "__container__", align: HorizontalAlign.End },
top: { anchor: "__container__", align: VerticalAlign.Top },
bottom: { anchor: "lp3", align: VerticalAlign.Top }
}).id("g4").borderWidth(1).borderColor(Color.Black)
}
.width(200).height(200)
.backgroundColor(Color.Orange)
}
.height('100%')
}
}
```
![relative container](figures/relativecontainer.png)
...@@ -37,7 +37,7 @@ Swiper(value:{controller?: SwiperController}) ...@@ -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. | | 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. | | interval | number | 3000 | Interval for automatic playback, in ms. |
| indicator | boolean | true | Whether to enable the navigation dots. | | 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. | | duration | number | 400 | Duration of the animation for switching child components, in ms. |
| vertical | boolean | false | Whether vertical swiping is used. | | vertical | boolean | false | Whether vertical swiping is used. |
| itemSpace | Length | 0 | Space between child components. | | itemSpace | Length | 0 | Space between child components. |
......
# Border Image
You can draw an image around a component.
> **NOTE**
>
> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Attributes
| Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- |
| source | string \| [Resource](../../ui/ts-types.md) \| [linearGradient](ts-universal-attributes-gradient-color.md) | - | Source or gradient color of the border image.|
| slice | Length \| EdgeWidth | 0 | Slice width of the border image.|
| width | Length \| EdgeWidth | 0 | Width of the border image.|
| outset | Length \| EdgeWidth | 0 | Amount by which the border image is extended beyond the border box.|
| RepeatMode | RepeatMode | RepeatMode.Stretch | Repeat mode of the border image.|
| fill | boolean | false | Whether to fill the center of the border image. |
- EdgeWidth
At least one parameter must be passed to reference an **EdgeWidth** object.
| Name| Type| Mandatory| Default Value |Description|
| -------- | -------- |-------- |-------- |-------- |
| left | Length | No| 0 | Distance on the left.|
| right | Length | No| 0 | Distance on the right.|
| top | Length | No| 0 | Distance at the top.|
| bottom | Length | No| 0 | Distance on the bottom.|
- RepeatMode
| Name| Description|
| -------- | -------- |
| Repeat | The source image's slices are tiled. Tiles beyond the border box will be clipped.|
| Stretch | The source image's slices stretched to fill the border box.|
| Round | The source image's slices are tiled to fill the border box. Tiles may be compressed when needed.|
| Space | The source image's slices are tiled to fill the border box. Extra space will be filled in between tiles.|
## Example
```ts
// xxx.ets
@Entry
@Component
struct Index {
build() {
Row() {
Column() {
Text('This is\nborderImage.').textAlign(TextAlign.Center)
.borderImage({
source: "borderOrigin.png",
slice: {top:"31%", bottom:"31%", left:"31%", right:"31%"},
width: {top:"20px", bottom:"20px", left:"20px", right:"20px"},
outset: {top:"5px", bottom:"5px", left:"5px", right:"5px"},
repeat: RepeatMode.Repeat,
fill: false
});
}
.width('100%')
}
.height('100%')
}
}
```
![zh-cn_image_borderImage](figures/borderImage.png)
```ts
// xxx.ets
@Entry
@Component
struct Index {
build() {
Row() {
Column() {
Text('This is\ngradient color.').textAlign(TextAlign.Center)
.borderImage({
source: {angle:90,
direction: GradientDirection.Left,
colors: [[0xAEE1E1, 0.0], [0xD3E0DC, 0.3], [0xFCD1D1, 1.0]]},
slice: {top:10, bottom:10, left:10, right:10},
width: {top:"10px", bottom:"10px", left: "10px", right:"10px"},
repeat: RepeatMode.Stretch,
fill: false
});
}
.width('100%')
}
.height('100%')
}
}
```
![en-us_image_borderImageGradient](figures/borderImageGradient.png)
# Visible Area Change Event
The visible area change event of a component refers to the change in the visual portion of a component on the screen. It can be used to determine whether the component is completely or partially displayed on the screen. It is usually applicable to scenarios such as advertisement exposure tracing.
> **NOTE**
>
> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Events
| Name| Description|
| -------- | -------- |
| onVisibleAreaChange(ratios: Array\<number>, event: (isVisible: boolean, currentRatio: number) => void) | Called when the visual area of the component changes.<br>- **ratios**: threshold array. Each threshold represents a ratio of the component's visible area (that is, the area of the component that is visible on screen) to the component's total area. This callback is invoked when the ratio of the component's visible area to its total area is greater than or less than the threshold. The value range of the threshold is [0.0, 1.0]. If the threshold set exceeds this range, the value **0.0** or **1.0** will be used.<br>- **isVisible**: indicates whether the ratio of the component's visible area to its total area is greater than the threshold. The value **true** means that the ratio is greater than the threshold, and **false** means that the ratio is less than the threshold.<br>- **currentRatio**: ratio of the component's visible area to its total area when this callback is invoked.|
## Example
```ts
// xxx.ets
@Entry
@Component
struct ScrollExample {
scroller: Scroller = new Scroller()
private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
@State testTextStr: string = "test"
@State testRowStr: string = "test"
build() {
Column() {
Column() {
Text(this.testTextStr)
.fontSize(20)
Text(this.testRowStr)
.fontSize(20)
}
.height(100)
.backgroundColor(Color.Gray)
.opacity(0.3)
Scroll(this.scroller) {
Column() {
Text("Test Text Visible Change")
.fontSize(20)
.height(200)
.margin({ top: 50, bottom: 20 })
.backgroundColor(Color.Green)
// Set ratios to [0.0, 1.0] to invoke the callback when the component is fully visible or invisible on screen.
.onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {
console.info("Test Text isVisible: " + isVisible + ", currentRatio:" + currentRatio)
if (isVisible && currentRatio >= 1.0) {
console.info("Test Text is fully visible. currentRatio:" + currentRatio)
this.testTextStr = "Test Text is fully visible"
}
if (!isVisible && currentRatio <= 0.0) {
console.info("Test Text is completely invisible.")
this.testTextStr = "Test Text is completely invisible"
}
})
Row() {
Text("Test Row Visible Change")
.fontSize(20)
.margin({ bottom: 20 })
}
.height(200)
.backgroundColor(Color.Yellow)
.onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => {
console.info("Test Row isVisible:" + isVisible + ", currentRatio:" + currentRatio)
if (isVisible && currentRatio >= 1.0) {
console.info("Test Row is fully visible.")
this.testRowStr = "Test Row is fully visible"
}
if (!isVisible && currentRatio <= 0.0) {
console.info("Test Row is is completely invisible.")
this.testRowStr = "Test Row is is completely invisible"
}
})
ForEach(this.arr, (item) => {
Text(item.toString())
.width('90%')
.height(150)
.backgroundColor(0xFFFFFF)
.borderRadius(15)
.fontSize(16)
.textAlign(TextAlign.Center)
.margin({ top: 10 })
}, item => item)
}.width('100%')
}
.backgroundColor(0x317aff)
.scrollable(ScrollDirection.Vertical)
.scrollBar(BarState.On)
.scrollBarColor(Color.Gray)
.scrollBarWidth(30)
.onScroll((xOffset: number, yOffset: number) => {
console.info(xOffset + ' ' + yOffset)
})
.onScrollEdge((side: Edge) => {
console.info('To the edge')
})
.onScrollEnd(() => {
console.info('Scroll Stop')
})
}.width('100%').height('100%').backgroundColor(0xDCDCDC)
}
}
```
![en-us_visible_area_change.gif](figures/en-us_visible_area_change.gif)
...@@ -8,10 +8,9 @@ ...@@ -8,10 +8,9 @@
- [Directory Structure](ts-framework-directory.md) - [Directory Structure](ts-framework-directory.md)
- [Rules for Accessing Application Code Files](ts-framework-file-access-rules.md) - [Rules for Accessing Application Code Files](ts-framework-file-access-rules.md)
- ["js" Tag](ts-framework-js-tag.md) - ["js" Tag](ts-framework-js-tag.md)
- Resource Access - Resource Management
- [Accessing Application Resources](ts-application-resource-access.md) - [Resource File Categories](ui-ts-basic-resource-file-categories.md)
- [Accessing System Resources](ts-system-resource-access.md) - [Accessing Resources](ts-resource-access.md)
- [Media Resource Types](ts-media-resource-type.md)
- [Pixel Units](ts-pixel-units.md) - [Pixel Units](ts-pixel-units.md)
- [Types](ts-types.md) - [Types](ts-types.md)
- Declarative Syntax - Declarative Syntax
...@@ -21,6 +20,7 @@ ...@@ -21,6 +20,7 @@
- Declarative UI Description Specifications - Declarative UI Description Specifications
- [Configuration Without Parameters](ts-parameterless-configuration.md) - [Configuration Without Parameters](ts-parameterless-configuration.md)
- [Configuration with Mandatory Parameters](ts-configuration-with-mandatory-parameters.md) - [Configuration with Mandatory Parameters](ts-configuration-with-mandatory-parameters.md)
- [Attribute Configuration](ts-attribution-configuration.md) - [Attribute Configuration](ts-attribution-configuration.md)
- [Event Configuration](ts-event-configuration.md) - [Event Configuration](ts-event-configuration.md)
- [Child Component Configuration](ts-child-component-configuration.md) - [Child Component Configuration](ts-child-component-configuration.md)
...@@ -40,6 +40,7 @@ ...@@ -40,6 +40,7 @@
- [@Link](ts-component-states-link.md) - [@Link](ts-component-states-link.md)
- Managing Application States - Managing Application States
- [AppStorage](ts-application-states-appstorage.md) - [AppStorage](ts-application-states-appstorage.md)
- [LocalStorage](ui-ts-local-storage.md)
- [PersistentStorage](ts-application-states-apis-persistentstorage.md) - [PersistentStorage](ts-application-states-apis-persistentstorage.md)
- [Environment](ts-application-states-apis-environment.md) - [Environment](ts-application-states-apis-environment.md)
- Managing Other States - Managing Other States
...@@ -72,6 +73,7 @@ ...@@ -72,6 +73,7 @@
- [Building a Food Category List Layout](ui-ts-building-category-list-layout.md) - [Building a Food Category List Layout](ui-ts-building-category-list-layout.md)
- [Building a Food Category Grid Layout](ui-ts-building-category-grid-layout.md) - [Building a Food Category Grid Layout](ui-ts-building-category-grid-layout.md)
- [Implementing Page Redirection and Data Transmission](ui-ts-page-redirection-data-transmission.md) - [Implementing Page Redirection and Data Transmission](ui-ts-page-redirection-data-transmission.md)
- JavaScript-based Web-like Development Paradigm - JavaScript-based Web-like Development Paradigm
- [Overview](ui-js-overview.md) - [Overview](ui-js-overview.md)
- Framework - Framework
...@@ -144,4 +146,3 @@ ...@@ -144,4 +146,3 @@
- [Animation Effect](ui-js-animate-dynamic-effects.md) - [Animation Effect](ui-js-animate-dynamic-effects.md)
- [Animation Frame](ui-js-animate-frame.md) - [Animation Frame](ui-js-animate-frame.md)
- [Custom Components](ui-js-custom-components.md) - [Custom Components](ui-js-custom-components.md)
# 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 # 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 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 (/).
- 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.
- Level-2: resource sub-directories > **NOTE**
- Resource sub-directories store basic elements such as character strings, colors, and floating point numbers, and resource files such as media files. > Resource descriptors accept only strings, such as `'app.type.name'`, and cannot be combined.
- 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.|
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** 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.
> Resource descriptors accept only strings, such as `'app.type.name'`, and cannot be combined. .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 ## Resource File Examples
├─ base
│ ├─ element
│ │ ├─ color.json
│ │ ├─ string.json
│ │ └─ float.json
│ └─ media
│ └─ my_background_image.png
└─ rawfile
├─ test.png
└─ newDir
└─ newTest.png
```
The content of the **color.json** file is as follows: The content of the **color.json** file is as follows:
``` ```json
{ {
"color": [ "color": [
{ {
...@@ -73,7 +84,7 @@ The content of the **color.json** file is as follows: ...@@ -73,7 +84,7 @@ The content of the **color.json** file is as follows:
The content of the **float.json** file is as follows: The content of the **float.json** file is as follows:
``` ```json
{ {
"float":[ "float":[
{ {
...@@ -91,7 +102,7 @@ The content of the **float.json** file is as follows: ...@@ -91,7 +102,7 @@ The content of the **float.json** file is as follows:
The content of the **string.json** file is as follows: The content of the **string.json** file is as follows:
``` ```json
{ {
"string":[ "string":[
{ {
...@@ -113,7 +124,7 @@ The content of the **string.json** file is as follows: ...@@ -113,7 +124,7 @@ The content of the **string.json** file is as follows:
The content of the **plural.json** file is as follows: The content of the **plural.json** file is as follows:
``` ```json
{ {
"plural":[ "plural":[
{ {
...@@ -132,40 +143,3 @@ The content of the **plural.json** file is as follows: ...@@ -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)
```
...@@ -26,7 +26,7 @@ resources ...@@ -26,7 +26,7 @@ resources
| Category | base and Qualifiers Sub-directories | rawfile Sub-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. | | 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. | | 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. | | 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. |
...@@ -37,7 +37,7 @@ The name of a qualifiers sub-directory consists of one or more qualifiers that r ...@@ -37,7 +37,7 @@ The name of a qualifiers sub-directory consists of one or more qualifiers that r
**Naming Conventions for Qualifiers Sub-directories** **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. - 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**. - 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**.
...@@ -47,14 +47,14 @@ The name of a qualifiers sub-directory consists of one or more qualifiers that r ...@@ -47,14 +47,14 @@ The name of a qualifiers sub-directory consists of one or more qualifiers that r
| Qualifier Type | Description and Value Range | | 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). | | 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). | | 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). | | 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). | | 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 | | 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 | | 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 | | 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]. | | 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** **Rules for Matching Qualifiers Sub-directories and Device Resources**
...@@ -69,11 +69,59 @@ You can create resource group sub-directories (including element, media, animati ...@@ -69,11 +69,59 @@ You can create resource group sub-directories (including element, media, animati
**Table 3** Resource group sub-directories **Table 3** Resource group sub-directories
| Resource Group Sub-directory | Description | Resource File | | Resource Group Sub-directory | Description | Resource File |
| ---------------------------- | ---------------------------------------- | ---------------------------------------- | | ---------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| element | Indicates 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 | | 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 | Indicates media resources, including non-text files such as images, audios, and videos. | The file name can be customized, for example, **icon.png**. | | media | Media resources, including non-text files such as images, audios, and videos. | The file name can be customized, for example, **icon.png**. |
| animation | Indicates animation resources, in XML format. | The file name can be customized, for example, **zoom_in.xml**. | | profile | Other types of files, which are stored in their raw formats. | The file name can be customized. |
| layout | Indicates layout resources, in XML format. | The file name can be customized, for example, **home_layout.xml**. |
| graphic | Indicates graphic resources, in XML format. | The file name can be customized, for example, **notifications_dark.xml**. | ### Media Resource Types
| profile | Indicates other types of files, which are stored in their raw formats. | The file name can be customized. |
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)
# LocalStorage
> **NOTE**
>
> This component is supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
**LocalStorage** is a storage unit in an application. Its lifecycle is determined by the ability to which it is bound. **LocalStorage** provides storage for variable and non-variable state attributes within the scope of an application. The variable and non-variable state attributes work together to build an application UI, including the UI of abilities.
Application layer: Multiple **LocalStorage** instances can be created for an application. Each ability of an application corresponds to a **LocalStorage** instance.
Ability: An application can have multiple abilities. Only one **LocalStorage** instance can be allocated to the child components of an ability. Once allocated a **LocalStorage** instance, the child components have access to objects stored in the **LocalStorage**.
A component can access only one **LocalStorage** instance, and a **LocalStorage** instance can be allocated to multiple components.
## @LocalStorageLink Decorator
Two-way data binding can be established between a component and the **LocalStorage** through the component's state variable decorated by **@LocalStorageLink(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. When a component that contains a **@LocalStorageLink** decorated state variable is created, the state variable is initialized with the initial value of the **LocalStorage**. If no initial value is assigned for the **LocalStorage**, the state variable will use the value defined by **@LocalStorageLink**. Changes made to this variable in the component will be first synchronized to the **LocalStorage**, and then to other components of the bound ability.
## @LocalStorageProp Decorator
One-way data binding can be established between a component and the **LocalStorage** through the component's state variable decorated by **@LocalStorageLink(*key*)**. Wherein, **key** is the attribute key value in the **LocalStorage**. When a component that contains a **@LocalStorageProp** decorated state variable is created, the state variable is initialized with the value predefined in the **LocalStorage**. Changes made to the value in the **LocalStorage** will cause all UI components of the bound ability to update the state.
> **NOTE**
>
> If a **LocalStorage** instance has initial values assigned when being created, these values will be used for the **@LocalStorageLink** and **@LocalStorageProp** decorated state variables in the component. Otherwise, the initial values assigned for **@LocalStorageLink** and **@LocalStorageProp** will be used instead.
## LocalStorage APIs
### constructor
constructor(initializingProperties?: Object)
Creates and initializes a **LocalStorage** instance.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| ---------------------- | ------ | :--: | ------ | ------------------------------------------------------------ |
| initializingProperties | Object | No | - | Object attributes and their values returned by **object.keys(obj)**.|
### has
has(propName: string): boolean
Checks whether the **LocalStorage** contains the specified attribute value.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| -------- | ------ | :--: | ------ | -------------- |
| propName | string | Yes | - | Attribute value.|
**Return value**
| Type | Description |
| ------- | -------------------------- |
| boolean | Whether the attribute value is contained.|
### get
get\<T>(propName: string): T
Obtains the value corresponding to the given key.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| -------- | ------ | :--: | ------ | ------------------- |
| propName | string | Yes | - | Key of the value to obtain.|
**Return value**
| Type | Description |
| -------------- | ------------------------------------------------------- |
| T \| undefined | Returns the value if it is found; returns **undefined** otherwise.|
### set
set\<T>(propName: string, newValue: T): boolean
Sets the value for the given key.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| -------- | ------ | :--: | ------ | ----------------- |
| propName | string | Yes | - | Key of the value to set. |
| newValue | T | Yes | - | Value to set.|
**Return value**
| Type | Description |
| ------- | ----------------------------------------------------- |
| boolean | Returns **true** if the value is successfully set for the key; returns **false** otherwise.|
### setOrCreate
setOrCreate\<T>(propName: string, newValue: T): boolean
Creates or updates the value for the given key.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| -------- | ------ | :--: | ------ | ----------------------- |
| propName | string | Yes | - | Key of the value to create or update.|
| newValue | T | Yes | - | Value to create or update.|
**Return value**
| Type | Description |
| ------- | ------------------------------------------------------------ |
| boolean | Updates the value of the attribute and returns **true** if an attribute that has the same name as the specified key exists; creates an attribute with the specified value as its default value and returns **false** otherwise. **true** cannot be returned for **undefined** or **null**.|
### link
link\<T>(propName: string): T
Establishes two-way data binding between an attribute and this **LocalStorage** instance.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| -------- | ------ | :--: | ------ | ---------------------- |
| propName | string | Yes | - | Key of the target attribute.|
**Return value**
| Type| Description |
| ---- | ------------------------------------------------------------ |
| T | Returns the two-way data binding if an attribute that has the same name as the specified key exists; returns **undefined** otherwise.|
### setAndLink
setAndLink\<T>(propName: string, defaultValue: T): T
Establishes two-way data binding between an attribute and this **LocalStorage** instance.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| ------------ | ------ | :--: | ------ | -------------------- |
| propName | string | Yes | - | Key of the target attribute. |
| defaultValue | T | Yes | - | Default value of the target attribute to set.|
**Return value**
| Type | Description |
| ------------------------------------- | ------------------------------------------------------------ |
| [@Link](ts-component-states-link.md)| Returns the two-way data binding if an attribute that has the same name as the specified key exists; creates an attribute with the specified value as its default value and returns the attribute otherwise.|
### prop
prop\<T>(propName: string): T
Establishes one-way data binding with an attribute to update its status.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| -------- | ------ | :--: | ------ | ----------------------- |
| propName | string | Yes | - | Key of the target attribute.|
**Return value**
| Type | Description |
| ------------------------------------ | ------------------------------------------------------------ |
| [@Prop](ts-component-states-prop.md) | Returns the one-way data binding if an attribute that has the same name as the specified key exists; returns **undefined** otherwise. Note that the variables returned are immutable variables, which are applicable to variable and immutable state variables.|
### setAndProp
setAndProp\<T>(propName: string, defaultValue: T): T
Works in a way similar to the **Prop** API and sets up one-way data binding with the **localStorage**.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| ------------ | ------ | :--: | ------ | --------------------------- |
| propName | string | Yes | - | Key value in the key-value pair to be saved.|
| defaultValue | T | Yes | - | Default value created. |
**Return value**
| Type | Description |
| ------------------------------------ | ------------------------------------------------------------ |
| [@Prop](ts-component-states-prop.md) | Returns the value corresponding to the key if the current key is stored in the **LocalStorage**; creates and returns a **Prop** instance corresponding to the default value if the key has not been created.|
### delete
delete(propName: string): boolean
Deletes the key-value pair specified by key.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| -------- | ------ | :--: | ------ | --------------------- |
| propName | string | Yes | - | Key value of the attribute to be deleted.|
**Return value**
| Type | Description |
| ------- | ------------------------------------------------------------ |
| boolean | Deletes the key-value pair for the specified key. Returns **true** if the key-value pair exists and is successfully deleted; returns **false** otherwise.|
### keys
keys(): IterableIterator\<string>
Searches for all keys.
**Return value**
| Type | Description |
| ------------- | ---------------------------- |
| array\<string> | Returns an array of strings containing all keys.|
### size
size(): number
Number of existing key-value pairs.
**Return value**
| Type | Description |
| ------ | ------------------ |
| number | Number of key-value pairs.|
### Clear
clear(): boolean
Deletes all attributes.
**Return value**
| Type | Description |
| ------- | ------------------------------------------------------------ |
| boolean | Deletes all attributes. If any of the attributes is being referenced by a state variable, **false** is returned.|
### Example 1 (Creating a LocalStorage in an Ability)
```javascript
import Ability from '@ohos.appLication.Ability'
export default class MainAbility extends Ability {
storage : LocalStorage
onCreate(want) {
this.storage = new LocalStorage();
this.storage.setOrCreate("storageSimpleProp",121);
console.log("[Demo MainAbility onCreate]");
globalThis.abilityWant = want;
}
onDestroy() {
console.log("[Demo MainAbility onDestroy]")
}
onWindowStageCreate(windowStage) {
windowStage.setUIContent(this.context,"pages/index",this.storage)
}
onWindowStageDestroy() {
console.log("[Demo] MainAbility onWindoeStageDestroy")
}
onForeground() {
console.log("[Demo] MainAbility onForeground")
}
onBackground() {
console.log("[Demo] MainAbility onBackground")
}
}
```
The @Component decorated component obtains data.
```
let storage = LocalStorage.GetShared()
@Entry(storage)
@Component
struct LocalStorageComponent {
@LocalStorageLink("storageSimpleProp") simpleVarName: number = 0
build() {
Column(){
Text(this.simpleVarName.toString())
.onClick(()=>{
this.simpleVarName +=1;
})
Text(JSON.stringify(this.simpleVarName))
.fontSize(50)
}
.height(500)
}
}
```
### Example 2 (Defining LocalStorage on the Entry Page)
```
let storage = new LocalStorage({"PropA":47});
@Entry(storage)
@Component
struct ComA {
@LocalStorageLink("PropA") storLink : number = 1;
build() {
Column() {
Text(`Parent from LocalStorage $(this.storLink)`)
.onClick(()=>this.storLink+=1)
Child()
}
}
}
@Component
struct Child{
@LocalStorageLink("PropA") storLink : number = 1;
build() {
Text(`Parent from LocalStorage $(this.storLink)`)
.onClick(()=>this.storLink1+=1)
}
}
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册