提交 96820d0f 编写于 作者: E ester.zhou

update docs

Signed-off-by: Nester.zhou <ester.zhou@huawei.com>
上级 5278e32a
# Input Method Framework
> **NOTE**
The **inputMethod** module provides an input method framework, which can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more.
> **NOTE**
>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......@@ -8,14 +10,14 @@
## Modules to Import
```
import inputMethod from '@ohos.inputMethod';
import inputMethod from '@ohos.inputmethod';
```
## inputMethod<sup>8+</sup>
Provides the constants.
**System capability**: SystemCapability.Miscservices.InputMethodFramework
**System capability**: SystemCapability.MiscServices.InputMethodFramework
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
......@@ -26,7 +28,7 @@ Provides the constants.
Describes the input method application attributes.
**System capability**: SystemCapability.Miscservices.InputMethodFramework
**System capability**: SystemCapability.MiscServices.InputMethodFramework
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
......@@ -37,15 +39,15 @@ Describes the input method application attributes.
getInputMethodController(): InputMethodController
Obtains an [InputMethodController](#InputMethodController) instance.
Obtains an **[InputMethodController](#inputmethodcontroller)** instance.
**System capability**: SystemCapability.Miscservices.InputMethodFramework
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value**
| Type| Description|
| -------- | -------- |
| [InputMethodController](#InputMethodController) | Returns the current **InputMethodController** instance.|
| Type | Description |
| ----------------------------------------- | ---------------------------- |
| [InputMethodController](#inputmethodcontroller) | Returns the current **InputMethodController** instance.|
**Example**
......@@ -57,25 +59,74 @@ Obtains an [InputMethodController](#InputMethodController) instance.
getInputMethodSetting(): InputMethodSetting
Obtains an [InputMethodSetting](#InputMethodSetting) instance.
Obtains an **[InputMethodSetting](#inputmethodsetting8)** instance.
**System capability**: SystemCapability.Miscservices.InputMethodFramework
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value**
| Type | Description |
| ----------------------------------------- | ---------------------------- |
| [InputMethodSetting](#InputMethodSetting) | Returns the current **InputMethodSetting** instance.|
| [InputMethodSetting](#inputmethodsetting8) | Returns the current **InputMethodSetting** instance.|
**Example**
```js
var InputMethodSetting = inputMethod.getInputMethodSetting();
```
## inputMethod.switchInputMethod<sup>9+</sup>
switchInputMethod(target: InputmethodProperty, callback: AsyncCallback&lt;boolean&gt;): void;
Switches to another input method. This API uses an asynchronous callback to return the result. This API can be used only in the stage model.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
|target | [InputmethodProperty](#inputmethodproperty8) | Yes| Input method to switch to.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the execution result. |
**Example**
```js
inputMethod.switchInputMethod({packageName:"com.ohos.inputApp", methodId:"InputDemoService"}).then(res => {
prompt.showToast({message:"Input method switched." + this.imeList[this.flag].packageName, duration: 200});
});
```
## inputMethod.switchInputMethod<sup>9+</sup>
switchInputMethod(target: InputmethodProperty): Promise&lt;boolean&gt;
Switches to another input method. This API uses a promise to return the result. This API can be used only in the stage model.
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
|target | [InputmethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.|
**Return value**
| Type | Description |
| ----------------------------------------- | ---------------------------- |
| Promise\<boolean> | Promise used to return the execution result. |
**Example**
```js
inputMethod.switchInputMethod({packageName:"com.ohos.inputApp", methodId:"InputDemoService"}).then(res => {
prompt.showToast({message:"Input method switched." + this.imeList[this.flag].packageName, duration: 200});
});
```
## InputMethodController
In the following API examples, you must first use [getInputMethodController](#getInputMethodController) to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance.
In the following API examples, you must first use **[getInputMethodController](#inputmethodgetinputmethodcontroller)** to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance.
### stopInput
......@@ -83,7 +134,7 @@ stopInput(callback: AsyncCallback&lt;boolean&gt;): void
Hides the keyboard. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
......@@ -105,13 +156,13 @@ stopInput(): Promise&lt;boolean&gt;
Hides the keyboard. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return whether the keyboard is successfully hidden.|
| Promise&lt;boolean&gt; | Promise used to return whether the keyboard is successfully hidden. |
**Example**
......@@ -123,7 +174,7 @@ Hides the keyboard. This API uses an asynchronous callback to return the result.
## InputMethodSetting<sup>8+</sup>
In the following API examples, you must first use [getInputMethodSetting](#getInputMethodSetting) to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance.
In the following API examples, you must first use **[getInputMethodSetting](#inputmethodgetinputmethodsetting8)** to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance.
### listInputMethod
......@@ -131,13 +182,12 @@ listInputMethod(callback: AsyncCallback&lt;Array&lt;InputMethodProperty&gt;&gt;)
Obtains the list of installed input methods. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------------------- | ---- | ---------------------- |
| callback | Array<[InputMethodProperty](#InputMethodProperty)> | Yes | Callback used to return the list of installed input methods.|
| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | Yes | Callback used to return the list of installed input methods.|
**Example**
......@@ -156,13 +206,12 @@ listInputMethod(): Array&lt;InputMethodProperty&gt;
Obtains the list of installed input methods. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value**
| Type | Description |
| ----------------------------------------------------------- | ---------------------- |
| Promise<Array<[InputMethodProperty](#InputMethodProperty)>> | Promise used to return the list of installed input methods.|
| Promise<Array<[InputMethodProperty](#inputmethodproperty8)>> | Promise used to return the list of installed input methods. |
**Example**
......@@ -180,15 +229,16 @@ displayOptionalInputMethod(callback: AsyncCallback&lt;void&gt;): void
Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework
**System capability**: SystemCapability.MiscServices.InputMethodFramework
- Parameters
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the execution result.|
**Example**
```js
InputMethodSetting.displayOptionalInputMethod(()=>{
console.info('displayOptionalInputMethod is called');
......@@ -197,20 +247,20 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono
### displayOptionalInputMethod
displayOptionalInputMethod(): Promise&lt;void&gt;
displayOptionalInputMethod(): Promise&lt;void&gt;
Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Miscservices.InputMethodFramework
**System capability**: SystemCapability.MiscServices.InputMethodFramework
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | Promise used to return the execution result.|
| Promise&lt;void&gt; | Promise used to return the execution result. |
**Example**
```js
InputMethodSetting.displayOptionalInputMethod();
```
\ No newline at end of file
```
......@@ -91,7 +91,11 @@ struct ProgressExample {
Text('Capsule Progress').fontSize(9).fontColor(0xCCCCCC).width('90%')
Row({ space: 40 }) {
Progress({ value: 10, type: ProgressType.Capsule }).width(100).height(50)
Progress({ value: 20, total: 150, type: ProgressType.Capsule }).color(Color.Grey).value(50).width(100).height(50)
Progress({ value: 20, total: 150, type: ProgressType.Capsule })
.color(Color.Grey)
.value(50)
.width(100)
.height(50)
}
}.width('100%').margin({ top: 30 })
}
......
# Slider
> **NOTE**<br>
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **&lt;Slider&gt;** component is used to quickly adjust settings, such as the volume and brightness.
The *\<Slider>** component is used to quickly adjust settings, such as the volume and brightness.
## Required Permissions
......@@ -15,7 +16,7 @@ None
## Child Components
None
Not supported
## APIs
......@@ -44,12 +45,12 @@ Slider(value:{value?: number, min?: number, max?: number, step?: number, style?:
Touch target configuration is not supported.
| Name | Type | Default Value | Description |
| ------------- | ------- | ------------- | -------------------------------------------------------------------- |
| blockColor | Color | - | Color of the slider. |
| trackColor | Color | - | Background color of the slider. |
| selectedColor | Color | - | Color of the slider rail that has been slid. |
| showSteps | boolean | false | Whether to display the current step. |
| Name | Type | Default Value | Description |
| ------------- | ------- | ------------- | ---------------------------------------- |
| blockColor | Color | - | Color of the slider. |
| trackColor | Color | - | Background color of the slider. |
| selectedColor | Color | - | Color of the slider rail that has been slid. |
| showSteps | boolean | false | Whether to display the current step. |
| showTips | boolean | false | Whether to display a bubble to indicate the percentage when sliding. |
......@@ -62,17 +63,18 @@ Among all the universal events, only **OnAppear** and **OnDisAppear** are suppor
| onChange(callback: (value: number, mode: SliderChangeMode) =&gt; void) | Callback invoked when the slider slides.<br/>**value**: current progress.<br/>**mode**: dragging state. |
- SliderChangeMode enums
| Name | Description |
| ------ | ----------------------------------- |
| Begin | The user starts to drag the slider. |
| Moving | The user is dragging the slider. |
| End | The user stops dragging the slider. |
| Name | Value | Description |
| ------ | ----- | ----------------------------------- |
| Begin | 0 | The user starts to drag the slider. |
| Moving | 1 | The user is dragging the slider. |
| End | 2 | The user stops dragging the slider. |
## Example
```
```ts
// xxx.ets
@Entry
@Component
struct SliderExample {
......
# CanvasGradient
> **NOTE**<br>
> **NOTE**
>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
......@@ -17,18 +18,18 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| offset | number | Yes | 0 | Proportion of the distance between the color stop and the start point to the total length. The value ranges from 0 to 1. |
| color | string | Yes | 'ffffff' | Gradient color to set. |
| offset | number | Yes | 0 | Proportion of the distance between the color stop and the start point to the total length. The value ranges from 0 to 1. |
| color | string | Yes | '#ffffff'| Gradient color to set. |
- Example
```
```ts
// xxx.ets
@Entry
@Component
struct Page45 {
private settings: RenderingContextSettings = new RenderingContextSettings(true)
private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings)
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Canvas(this.context)
......@@ -37,9 +38,9 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse
.backgroundColor('#ffff00')
.onReady(() =>{
var grad = this.context.createLinearGradient(50,0, 300,100)
this.grad.addColorStop(0.0, 'red')
this.grad.addColorStop(0.5, 'white')
this.grad.addColorStop(1.0, 'green')
grad.addColorStop(0.0, 'red')
grad.addColorStop(0.5, 'white')
grad.addColorStop(1.0, 'green')
this.context.fillStyle = grad
this.context.fillRect(0, 0, 500, 500)
})
......
# Scroll
> **NOTE**
> - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
> - When a **\<List>** is nested in this component, you are advised to specify the width and height of the **\<List>** under scenarios where consistently high performance is required. If the width and height are not specified, this component will load all content of the **\<List>**.
> **NOTE**<br>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
The **<Scroll\>** component scrolls the content when the layout size of a component exceeds the viewport of its parent component.
The **\<Scroll>** component scrolls the content when the layout size of a component exceeds the viewport of its parent component.
## Required Permissions
None
None.
## Child Components
......@@ -25,35 +25,45 @@ Scroll(scroller?: Scroller)
## Attributes
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| scrollable | ScrollDirection | ScrollDirection.Vertical | Scroll method. |
| scrollBar | [BarState](ts-appendix-enums.md#barstate-enums) | Auto | Scroll bar status. |
| scrollBarColor | Color | - | Color of the scroll bar. |
| scrollBarWidth | Length | - | Width of the scrollbar. |
| Name | Type | Default Value | Description |
| -------------- | ---------------------------------------- | ------------------------ | --------- |
| scrollable | ScrollDirection | ScrollDirection.Vertical | Scroll method. |
| scrollBar | [BarState](ts-appendix-enums.md#barstate-enums)| ScrollDirection.Auto | Scrollbar status. |
| scrollBarColor | Color | - | Color of the scrollbar.|
| scrollBarWidth | Length | - | Width of the scrollbar.|
- ScrollDirection enums
| Name | Description |
| ---------- | ---------- |
| Horizontal | Only horizontal scrolling is supported.|
| Vertical | Only vertical scrolling is supported.|
| None | Scrolling is disabled. |
## Events
- ScrollDirection
| Name | Description |
| -------- | -------- |
| Horizontal | Only horizontal scrolling is supported. |
| Vertical | Only vertical scrolling is supported. |
| None | Scrolling is disabled. |
| Name | Description |
| ---------------------------------------- | ----------------------------- |
| onScrollBegin<sup>9+</sup>(dx: number, dy: number)&nbsp;=&gt;&nbsp;{ dxRemain: number, dyRemain: number } | Invoked when scrolling starts.<br>Parameters:<br>- **dx**: amount to scroll by in the horizontal direction.<br>- **dy**: amount to scroll by in the vertical direction.<br>Return value:<br>- **dxRemain**: remaining amount to scroll by in the horizontal direction.<br>- **dyRemain**: remaining amount to scroll by in the vertical direction.|
| onScroll(xOffset:&nbsp;number,&nbsp;yOffset:&nbsp;number)&nbsp;=&gt;&nbsp;void | Invoked to return the horizontal and vertical offsets during scrolling when the specified scroll event occurs.|
| onScrollEdge(side:&nbsp;Edge)&nbsp;=&gt;&nbsp;void | Invoked when scrolling reaches the edge. |
| onScrollEnd()&nbsp;=&gt;&nbsp;void | Invoked when scrolling stops. |
> **NOTE**
> If the **onScrollBegin** event and **scrollBy** API are used to implement nested scrolling, you must set **edgeEffect** of the scrolling child node to **None**. For example, if a **\<List>** is nested in the **\<Scroll>** component, the **edgeEffect** attribute of the **\<List>** must be set to **EdgeEffect.None**.
## Scroller
Controller of the scrollable container component. You can bind this component to the container component and use it to control the scrolling of the container component. Currently, this component can be bound to the **<List\>** and **<Scroll\>** components.
Controller of the scrollable container component. You can bind this component to a container component and use it to control the scrolling of that component. Currently, this component can be bound to the **\<List>** and **\<Scroll>** components.
### Objects to Import
```
scroller: Scroller = new Scroller()
```
### scroller.scrollTo
### scrollTo
scrollTo(value: { xOffset: number | string, yOffset: number | string, animation?: { duration: number, curve: Curve } }): void
......@@ -62,14 +72,14 @@ Scrolls to the specified position.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| xOffset | Length | Yes | - | Horizontal scrolling offset. |
| yOffset | Length | Yes | - | Vertical scrolling offset. |
| animation | {<br/>duration: number,<br/>curve: Curve \|<br/>CubicBezier \|<br/>SpringCurve<br/>} | No | | Animation configuration, which includes the following:<br/>- **duration**: scrolling duration.<br/>- **curve**: scrolling curve. |
| Name | Type | Mandatory | Default Value | Description |
| --------- | ---------------------------------------- | ---- | ---- | ---------------------------------------- |
| xOffset | Length | Yes | - | Horizontal scrolling offset. |
| yOffset | Length | Yes | - | Vertical scrolling offset. |
| animation | {<br>duration:&nbsp;number,<br>curve:&nbsp;[Curve](ts-animatorproperty.md)&nbsp;\|<br>CubicBezier&nbsp;\|<br>SpringCurve<br>} | No | | Animation configuration, which includes the following:<br>- **duration**: scrolling duration.<br>- **curve**: scrolling curve.|
### scroller.scrollEdge
### scrollEdge
scrollEdge(value: Edge): void
......@@ -78,68 +88,80 @@ Scrolls to the edge of the container.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| value | Edge | Yes | - | Edge position to scroll to. |
| Name | Type| Mandatory | Default Value | Description |
| ----- | ---- | ---- | ---- | --------- |
| value | Edge | Yes | - | Edge position to scroll to.|
### scroller.scrollPage
### scrollPage
scrollPage(value: { next: boolean, direction?: Axis }): void
Scrolls to the next or previous page.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| next | boolean | Yes | - | Whether to turn to the next page. The value **true** means to scroll to the next page, and the value **false** means to scroll to the previous page. |
| Name | Type | Mandatory | Default Value | Description |
| --------- | ------- | ---- | ---- | ------------------------------ |
| next | boolean | Yes | - | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.|
| direction | Axis | No | - | Scrolling direction: horizontal or vertical. |
### scroller.currentOffset
### currentOffset
scroller.currentOffset(): Object
currentOffset(): Object
Obtains the scrolling offset.
- Return value
| Type | Description |
| -------- | -------- |
| {<br/>xOffset: number,<br/>yOffset: number<br/>} | - **xOffset**: horizontal scrolling offset.<br/>- **yOffset**: vertical scrolling offset. |
| Type | Description |
| ------------------------------------------------------- | ------------------------------------------------------------ |
| {<br>xOffset:&nbsp;number,<br>yOffset:&nbsp;number<br>} | **xOffset**: horizontal scrolling offset.<br>**yOffset**: vertical scrolling offset. |
### scroller.scrollToIndex
### scrollToIndex
scroller.scrollToIndex(value: number): void
scrollToIndex(value: number): void
Scrolls to the specified index.
Scrolls to the item with the specified index.
> **NOTE**<br>
> Only the **<List\>** component is supported.
> **NOTE**
> Only the **\<List>** component is supported.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| value | number | Yes | - | Index of the item to be scrolled to in the list. |
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| value | number | Yes | - | Index of the item to be scrolled to in the list.|
## Events
### scrollBy
| Name | Description |
| -------- | -------- |
| onScroll(xOffset: number, yOffset: number) =&gt; void | Invoked to return the horizontal and vertical scrolling offsets when the specified scroll event occurs. |
| onScrollEdge(side: Edge) =&gt; void | Invoked when an item is scrolled to the edge. |
| onScrollEnd() =&gt; void | Invoked when scrolling stops. |
scrollBy(dx: Length, dy: Length): void
## Example
Scrolls by the specified amount.
```
> **NOTE**
> Only the **\<Scroll>** component is supported.
- Parameters
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| dx | Length | Yes | - | Amount to scroll by in the horizontal direction.|
| dy | Length | Yes | - | Amount to scroll by in the vertical direction.|
## Example
```ts
// xxx.ets
@Entry
@Component
struct ScrollExample {
......@@ -152,14 +174,20 @@ struct ScrollExample {
Column() {
ForEach(this.arr, (item) => {
Text(item.toString())
.width('90%').height(150).backgroundColor(0xFFFFFF)
.borderRadius(15).fontSize(16).textAlign(TextAlign.Center)
.width('90%')
.height(150)
.backgroundColor(0xFFFFFF)
.borderRadius(15)
.fontSize(16)
.textAlign(TextAlign.Center)
.margin({ top: 10 })
}, item => item)
}.width('100%')
}
.scrollable(ScrollDirection.Vertical).scrollBar(BarState.On)
.scrollBarColor(Color.Gray).scrollBarWidth(30)
.scrollable(ScrollDirection.Vertical)
.scrollBar(BarState.On)
.scrollBarColor(Color.Gray)
.scrollBarWidth(30)
.onScroll((xOffset: number, yOffset: number) => {
console.info(xOffset + ' ' + yOffset)
})
......@@ -171,17 +199,17 @@ struct ScrollExample {
})
Button('scroll 100')
.onClick(() => {// Click to scroll down 100.0.
.onClick(() => { // Click to scroll down 100.0.
this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 })
})
.margin({ top: 10, left: 20 })
Button('back top')
.onClick(() => {// Click to go back to the top.
.onClick(() => { // Click to go back to the top.
this.scroller.scrollEdge(Edge.Top)
})
.margin({ top: 60, left: 20 })
Button('next page')
.onClick(() => {// Click to scroll down to the bottom.
.onClick(() => { // Click to scroll down to the bottom.
this.scroller.scrollPage({ next: true })
})
.margin({ top: 110, left: 20 })
......@@ -191,3 +219,58 @@ struct ScrollExample {
```
![en-us_image_0000001256978363](figures/en-us_image_0000001256978363.gif)
```ts
@Entry
@Component
struct NestedScroll {
@State listPosition: number = 0 // 0 indicates scrolling to the top of the list, 1 indicates scrolling to the center of the list, and 2 indicates scrolling to the bottom of the list.
private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
private scroller: Scroller = new Scroller()
build() {
Flex() {
Scroll(this.scroller) {
Column() {
Text("Scroll Area")
.width("100%").height("40%").backgroundColor(0X330000FF)
.fontSize(16).textAlign(TextAlign.Center)
List({ space: 20 }) {
ForEach(this.arr, (item) => {
ListItem() {
Text("ListItem" + item)
.width("100%").height("100%").borderRadius(15)
.fontSize(16).textAlign(TextAlign.Center).backgroundColor(Color.White)
}.width("100%").height(100)
}, item => item)
}
.width("100%").height("50%").edgeEffect(EdgeEffect.None)
.onReachStart(() => {
this.listPosition = 0
})
.onReachEnd(() => {
this.listPosition = 2
})
.onScrollBegin((dx: number, dy: number) => {
if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) {
this.scroller.scrollBy(0, -dy)
return { dxRemain: dx, dyRemain: 0 }
}
this.listPosition = 1;
return { dxRemain: dx, dyRemain: dy }
})
Text("Scroll Area")
.width("100%").height("40%").backgroundColor(0X330000FF)
.fontSize(16).textAlign(TextAlign.Center)
}
}
.width("100%").height("100%")
}.width('100%').height('100%').backgroundColor(0xDCDCDC).padding(20)
}
}
```
![NestedScroll](figures/NestedScroll.gif)
# Button
The **\<Button>** component can be used to create different types of buttons.
> **NOTE**
>
> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions
None
## Child Components
Supported
## APIs
- Button(options?: {type?: ButtonType, stateEffect?: boolean})
**Table 1** options parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| type | ButtonType | No | Capsule | Button type. |
| stateEffect | boolean | No | true | Whether to enable the state switchover effect when a button is pressed. When the state is set to **false**, the state switchover effect is disabled. |
- Button(label?: ResourceStr, options?: { type?: ButtonType, stateEffect?: boolean })
Creates a button component based on text content. In this case, the **\<Button>** component cannot contain child components.
**Table 2** Parameters
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------- | -------- | -------- | -------- |
| label | [ResourceStr](../../ui/ts-types.md) | No | - | Button text. |
| options | Object | No | - | For details, see the **options** parameters. |
## Attributes
| Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- |
| type | ButtonType | Capsule | Button type. |
| stateEffect | boolean | true | Whether to enable the state switchover effect. When the state is set to **false**, the state switchover effect is disabled. |
**ButtonType** enums
| Name | Description |
| -------- | -------- |
| Capsule | Capsule-type button (the round corner is half of the height by default). |
| Circle | Circle button. |
| Normal | Normal button (without rounded corners by default). |
> **NOTE**
> - The rounded corner of a button is set by using [Border](ts-universal-attributes-border.md). (The rounded corner cannot be set by using a border API.)
> - When the button type is **Capsule**, the **borderRadius** settings do not take effect, and the rounded corner of the button is always half of the button height.
> - When the button type is **Circle**, the value of **borderRadius** is used as the button radius. If **borderRadius** is not set, the button radius is half of the width or height, whichever is smaller.
> - The button text is set using the [common text style](ts-universal-attributes-text-style.md).
## Example
```ts
// xxx.ets
@Entry
@Component
struct ButtonExample {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) {
Text('Common button').fontSize(9).fontColor(0xCCCCCC)
Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Button('Ok', { type: ButtonType.Normal, stateEffect: true }).borderRadius(8).backgroundColor(0x317aff).width(90)
Button({ type: ButtonType.Normal, stateEffect: true }) {
Row() {
// You are advised to reference an image by using $r to create a Resource object.
Image($r('app.media.loading')).width(20).height(20).margin({ left: 12 })
Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 })
}.alignItems(VerticalAlign.Center)
}.borderRadius(8).backgroundColor(0x317aff).width(90)
Button('Disable', { type: ButtonType.Normal, stateEffect: false }).opacity(0.5)
.borderRadius(8).backgroundColor(0x317aff).width(90)
}
Text('Capsule button').fontSize(9).fontColor(0xCCCCCC)
Flex({ alignItems: ItemAlign.Center, justifyContent: FlexAlign.SpaceBetween }) {
Button('Ok', { type: ButtonType.Capsule, stateEffect: true }).backgroundColor(0x317aff).width(90)
Button({ type: ButtonType.Capsule, stateEffect: true }) {
Row() {
Image($r('app.media.loading')).width(20).height(20).margin({ left: 12 })
Text('loading').fontSize(12).fontColor(0xffffff).margin({ left: 5, right: 12 })
}.alignItems(VerticalAlign.Center).width(90)
}.backgroundColor(0x317aff)
.onClick((event: ClickEvent) => {
AlertDialog.show({ message: 'The login is successful' })
})
Button('Disable', { type: ButtonType.Capsule, stateEffect: false }).opacity(0.5)
.backgroundColor(0x317aff).width(90)
}
Text('Circle button').fontSize(9).fontColor(0xCCCCCC)
Flex({ alignItems: ItemAlign.Center, wrap: FlexWrap.Wrap }) {
Button({ type: ButtonType.Circle, stateEffect: true }) {
Image($r('app.media.ic_public_app_filled')).width(20).height(20)
}.width(55).height(55).backgroundColor(0x317aff)
Button({ type: ButtonType.Circle, stateEffect: true }) {
Image($r('app.media.ic_public_delete_filled')).width(30).height(30)
}.width(55).height(55).margin({ left: 20 }).backgroundColor(0xF55A42)
}
}.height(400).padding({ left: 35, right: 35, top: 35 })
}
}
```
![en-us_image_0000001257138341](figures/en-us_image_0000001257138341.gif)
# @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.
- Chain call<sup>9+</sup>: Universal attributes can be invoked in chain call mode to change the component style.
- 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-function-build.md).
For details about componentization, see [About @Component](ts-custom-component-initialization.md).
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**:
> - The build method must be defined for a custom component.
>
> - Custom constructors are prohibited for custom components.
> **NOTE**
>
> - 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:
The following code illustrates how to create a custom component named **MyComponent**:
```
```ts
@Component
struct MyComponent {
build() {
......@@ -37,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:
The following code illustrates how to use **MyComponent**:
```
```ts
@Component
struct ParentComponent {
build() {
......@@ -56,9 +55,10 @@ struct ParentComponent {
```
MyComponent can be applied multiple times and reused in different components, as shown in the code below:
**MyComponent** can be applied multiple times and reused in different components, as shown in the code below:
```
```ts
@Component
struct ParentComponent {
build() {
......@@ -76,12 +76,47 @@ struct ParentComponent {
}
}
private aboutToAppear() {
aboutToAppear() {
console.log('ParentComponent: Just created, about to become rendered first time.')
}
private aboutToDisappear() {
aboutToDisappear() {
console.log('ParentComponent: About to be removed from the UI.')
}
}
```
Universal attributes can be invoked in chain call mode to diversify component styles.
> **NOTE**
>
> This feature is supported since API version 9.
>
> The chain call for custom components does not support trailing closures in the following scenario: When the custom component is initialized, the component name is followed by a pair of braces ({}) to form a trailing closure (as in `Index(){}`). You can consider a trailing closure as a container and add content to it, as in `{Column(){Text("content")}`.
```ts
@Entry
@Component
struct Index {
@State bannerValue: string = 'Hello,world';
build() {
Column() {
Chind({ ChindBannerValue:$bannerValue })
.height(60)
.width(250)
.border({ width:5, color:Color.Red, radius:10, style: BorderStyle.Dotted })
}
}
}
@Component
struct Chind {
@Link ChindBannerValue: string;
build() {
Column() {
Text(this.ChindBannerValue)
.fontSize(30)
}
}
}
```
......@@ -14,17 +14,17 @@ A component can access only one **LocalStorage** instance, and a **LocalStorage*
## @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.
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 value predefined in the **LocalStorage**. If no initial value is assigned in 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.
One-way data binding can be established between a component and the **LocalStorage** through the component's state variable decorated by **@LocalStorageProp(*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.
> 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
## LocalStorage
### constructor
......@@ -34,9 +34,25 @@ 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)**.|
| Name | Type | Mandatory | Default Value | Description |
| ---------------------- | ------ | :--: | ---- | ---------------------------------------- |
| initializingProperties | Object | No | - | Object attributes and their values returned by **object.keys(obj)**.|
### GetShared
static GetShared(): LocalStorage
Obtains the current shared **LocalStorage** object.
This API can be used only in the stage model.
**Return value**
| Type | Description |
| ----------------------------- | ----------------- |
| [LocalStorage](#localstorage) | **LocalStorage** object.|
......@@ -48,14 +64,14 @@ Checks whether the **LocalStorage** contains the specified attribute value.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| -------- | ------ | :--: | ------ | -------------- |
| propName | string | Yes | - | Attribute value.|
| Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | :--: | ---- | ------- |
| propName | string | Yes | - | Attribute value.|
**Return value**
| Type | Description |
| ------- | -------------------------- |
| Type | Description |
| ------- | ------------- |
| boolean | Whether the attribute value is contained.|
......@@ -68,14 +84,14 @@ Obtains the value corresponding to the given key.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| -------- | ------ | :--: | ------ | ------------------- |
| propName | string | Yes | - | Key of the value to obtain.|
| Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | :--: | ---- | ----------- |
| propName | string | Yes | - | Key of the value to obtain.|
**Return value**
| Type | Description |
| -------------- | ------------------------------------------------------- |
| Type | Description |
| -------------- | ---------------------------------------- |
| T \| undefined | Returns the value if it is found; returns **undefined** otherwise.|
......@@ -88,15 +104,15 @@ 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.|
| 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 |
| ------- | ----------------------------------------------------- |
| Type | Description |
| ------- | ----------------------------------- |
| boolean | Returns **true** if the value is successfully set for the key; returns **false** otherwise.|
......@@ -109,16 +125,16 @@ 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.|
| 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**.|
| 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 of the T type as its default value and returns **false** otherwise. **true** cannot be returned for **undefined** or **null**.|
......@@ -130,14 +146,14 @@ Establishes two-way data binding between an attribute and this **LocalStorage**
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| -------- | ------ | :--: | ------ | ---------------------- |
| propName | string | Yes | - | Key of the target attribute.|
| Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | :--: | ---- | ----------- |
| propName | string | Yes | - | Key of the target attribute.|
**Return value**
| Type| Description |
| ---- | ------------------------------------------------------------ |
| 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.|
......@@ -146,20 +162,20 @@ Establishes two-way data binding between an attribute and this **LocalStorage**
setAndLink\<T>(propName: string, defaultValue: T): T
Establishes two-way data binding between an attribute and this **LocalStorage** instance.
Establishes two-way data binding between an attribute and this **LocalStorage** instance. This API works in a way similar to the **link** API.
**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.|
| Name | Type | Mandatory | Default Value | Description |
| ------------ | ------ | :--: | ---- | ----------- |
| propName | string | Yes | - | Key of the target attribute.|
| defaultValue | T | Yes | - | Default value 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.|
| Type | Description |
| ------------------------------------- | ---------------------------------------- |
| [@Link](ts-component-states-link.md ) | Returns the value corresponding to the specified key if the key is stored in the **LocalStorage**; creates and returns a **Link** instance with the specified value as its default value otherwise|
......@@ -171,15 +187,15 @@ 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.|
| 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.|
| Type | Description |
| ------------------------------------ | ---------------------------------------- |
| [@Prop](ts-component-states-prop.md) | Returns one-way binding to an attribute with a given key if the attribute exists; returns **undefined** otherwise. This means that attribute changes made through the **LocalStorage** will be synchronized to the variable or component, but attribute changes made by the variable or component will be synchronized to the **LocalStorage**. Note that the variables returned are immutable variables, which are applicable to mutable and immutable state variables. |
......@@ -187,20 +203,20 @@ Establishes one-way data binding with an attribute to update its status.
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**.
Sets up one-way data binding with the **localStorage**. This API works in a way similar to the **Prop** API.
**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. |
| Name | Type | Mandatory | Default Value | Description |
| ------------ | ------ | :--: | ---- | --------------- |
| propName | string | Yes | - | Key value in the key-value pair to be saved.|
| defaultValue | T | Yes | - | Default value to set. |
**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.|
| Type | Description |
| ------------------------------------ | ---------------------------------------- |
| [@Prop](ts-component-states-prop.md) | Returns the value corresponding to the specified key if the key is stored in the **LocalStorage**; creates and returns a **Prop** instance with the specified value as its default value otherwise.|
......@@ -212,15 +228,15 @@ 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.|
| 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.|
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the key-value pair exists and is successfully deleted; returns **false** otherwise.|
......@@ -232,8 +248,8 @@ Searches for all keys.
**Return value**
| Type | Description |
| ------------- | ---------------------------- |
| Type | Description |
| -------------- | -------------- |
| array\<string> | Returns an array of strings containing all keys.|
......@@ -246,8 +262,8 @@ Number of existing key-value pairs.
**Return value**
| Type | Description |
| ------ | ------------------ |
| Type | Description |
| ------ | --------- |
| number | Number of key-value pairs.|
......@@ -260,14 +276,14 @@ 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.|
| Type | Description |
| ------- | --------------------------------- |
| boolean | Returns **true** if all attributes are deleted; returns **false** if any of the attributes is being referenced by a state variable.|
### Example 1 (Creating a LocalStorage in an Ability)
```javascript
import Ability from '@ohos.appLication.Ability'
```ts
import Ability from '@ohos.application.Ability'
export default class MainAbility extends Ability {
storage : LocalStorage
onCreate(want) {
......@@ -296,7 +312,7 @@ export default class MainAbility extends Ability {
The @Component decorated component obtains data.
```
```ts
let storage = LocalStorage.GetShared()
@Entry(storage)
@Component
......@@ -318,28 +334,28 @@ struct LocalStorageComponent {
### Example 2 (Defining LocalStorage on the Entry Page)
```
```ts
let storage = new LocalStorage({"PropA":47});
@Entry(storage)
@Component
struct ComA {
@LocalStorageLink("PropA") storLink : number = 1;
@LocalStorageLink("PropA") storLink: number = 1;
build() {
Column() {
Text(`Parent from LocalStorage $(this.storLink)`)
Text(`Parent from LocalStorage ${ this.storLink }`)
.onClick(()=>this.storLink+=1)
Child()
}
Child()
}
}
}
@Component
struct Child{
@LocalStorageLink("PropA") storLink : number = 1;
@LocalStorageLink("PropA") storLink: number = 1;
build() {
Text(`Parent from LocalStorage $(this.storLink)`)
.onClick(()=>this.storLink1+=1)
Text(`Parent from LocalStorage ${ this.storLink }`)
.onClick(()=>this.storLink+=1)
}
}
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册
反馈
建议
客服 返回
顶部