diff --git a/en/application-dev/faqs/faqs-ui-ets.md b/en/application-dev/faqs/faqs-ui-ets.md index 3ec2b755e3e99db07930d5f8a6d01975985f4948..074a404683bda39d3e5499c66bb193d97784c4dd 100644 --- a/en/application-dev/faqs/faqs-ui-ets.md +++ b/en/application-dev/faqs/faqs-ui-ets.md @@ -1,43 +1,14 @@ # ArkUI (ArkTS) Development - - -## What are the restrictions on using generator functions in TypeScript? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -Below are the restrictions on using generator functions in TypeScript: - -- Expressions can be used only in character strings (in the ${expression} format), **if** conditions, **ForEach** parameters, and component parameters. - -- No expressions should cause any application state variables (including **\@State**, **\@Link**, and **\@Prop**) to change. Otherwise, undefined and potentially unstable framework behavior may occur. - -- The generator function cannot contain local variables. - -None of the above restrictions apply to anonymous function implementations of event handlers (such as **onClick**). - -Negative example: - - -``` -build() { - let a: number = 1 // invalid: variable declaration not allowed - Column() { - Text('Hello ${this.myName.toUpperCase()}') // ok. - ForEach(this.arr.reverse(), ..., ...) // invalid: Array.reverse modifies the @State array varible in place - } - buildSpecial() // invalid: no function calls - Text(this.calcTextValue()) // this function call is ok. -} -``` - ## How do I use router to implement page redirection in the stage model? Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 -To implement page redirection through **router**, add all redirected-to pages to the pages list in the **main_pages.json** file. +1. To implement page redirection through **router**, add all redirected-to pages to the pages list in the **main_pages.json** file. + +2. Page routing APIs in **router** can be invoked only after page rendering is complete. Do not call these APIs in **onInit** or **onReady** when the page is still in the rendering phase. -Page routing APIs in **router** can be invoked only after page rendering is complete. Do not call these APIs in **onInit** or **onReady** when the page is still in the rendering phase. +Reference: [Page Routing](../reference/apis/js-apis-router.md) ## Will a page pushed into the stack through router.push be reclaimed? @@ -45,82 +16,6 @@ Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 After being pushed to the stack through **router.push**, a page can be reclaimed only when it is popped from the stack through **router.back**. -## How do I dynamically replace the %s placeholder in a resource file? - -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 - -In an application, you can replace the %s placeholder by using the second parameter in `$r('app.string.xx')`, which is used to reference application resources. - -Example: - -``` -build() { - //do something - // The second parameter indicates the referenced string resource, which can be used to replace the %s placeholder. - Text($r('app.string.entry_desc','aaa')) - .fontSize(100) - .fontColor(Color.Black) - //do something -} -``` - -## How do I read an XML file in Resource and convert data in it to the string type? - -Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 - -1. Obtain data in Uint8Array format by calling the **RawFile** API of **resourceManager**. - -2. Convert data in Uint8Array format to the string type by calling the **String.fromCharCode** API. - -Reference: [Resource Management](../reference/apis/js-apis-resource-manager.md) - -Example: - - -``` -resourceManager.getRawFile(path, (error, value) => { - if (error != null) { - console.log("error is " + error); - } else { - let rawFile = value; - let xml = String.fromCharCode.apply(null, rawFile) - } -}); -``` - -## How do I convert a Resource object to the string type? - -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 - -Use the **resourceManager.getString()** API of the **\@ohos.resourceManager** module. - -Reference: [Resource Management](../reference/apis/js-apis-resource-manager.md#getstring) - -## What should I do if the global static variables of a class do not work? - -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 - -Objects imported to abilities and pages are packaged into two different closures, that is, two global objects. In this case, a static variable referenced by the abilities is not the same object as that referenced by the pages. Therefore, global variables cannot be defined by defining static variables in the class. You are advised to use AppStorage to manage global variables. - -## How do I obtain resources in the stage model? - -Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 - -The stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This method, however, is not applicable to the FA model. - -Example: - - -``` -const context = getContext(this) as any -context - .resourceManager - .getString($r('app.string.entry_desc').id) - .then(value => { - this.message = value.toString() -}) -``` - ## How do I position a container component to the bottom of the screen? Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 @@ -152,7 +47,7 @@ build() { Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 -No. Currently, **CustomDialog** can be used only on ArkTS pages. +No. **CustomDialog** can be used only on ArkTS pages. Reference: [Custom Dialog Box](../reference/arkui-ts/ts-methods-custom-dialog-box.md) @@ -166,32 +61,70 @@ Example: ``` -// CustomDialog component +// Dialog box component @CustomDialog struct MyDialog { controller: CustomDialogController title: string - data: string - cancel: () => void confirm: (data: string) => void - Button('confirm') - .onClick(() => { - this.controller.close() - this.data = 'test' - this.confirm(this.data) - }).backgroundColor(0xffffff).fontColor(Color.Red) -// Page + data: string = '' + + build() { + Row() { + Column({ space: 10 }) { + Text(this.title) + .fontSize(30) + .fontColor(Color.Blue) + TextInput({ placeholder: "Enter content", text: this.data }) + .onChange((data) => { + this.data = data // Obtain the data in the text box. + }) + Button('confirm') + .onClick(() => { + this.confirm(this.data) // Transfer the data in the text box to the main page through the callback. + this.controller.close() + }).backgroundColor(0xffffff).fontColor(Color.Red) + }.width("50%") + }.height("50%") + } +} + +// Main page @Entry @Component struct DialogTest { + @State dialogTitle: string = '' + @State dialogData: string = '' dialogController: CustomDialogController = new CustomDialogController({ - builder: MyDialog({ title:'Custom Title',cancel: this.onCancel, - confirm: this.onAccept.bind(this)}), // Bind the custom callback to the button. - cancel: this.existApp, - autoCancel: true + builder: MyDialog({ + title: this.dialogTitle, // Bind data. + data: this.dialogData, + confirm: this.confirm.bind(this) // Bind the custom callback. Change the direction of this here. + }) }) - onAccept(data:string) { - console.info('Callback when the second button is clicked ' + data) + + confirm(data: string) { + this.dialogData = data + console.info(`recv dialog data: ${data}`) // Obtain the information entered in the dialog box. + } + + build() { + Row() { + Column({ space: 10 }) { + Button ('Open Dialog Box') + .onClick(() => { + this.dialogTitle ='Dialog Box' + this.dialogController.open() + }) + Text(`Accept pop-up window data:`) + .fontSize(20) + TextInput ({ placeholder: "Input", text: this.dialogData }) + .width("50%") + .onChange((data) => { + this.dialogData = data //Obtain the data in the text box. + }) + }.width("100%") + }.height("100%") } } ``` @@ -210,7 +143,7 @@ By default, child components in a **\** are horizontally aligned Nest a **\** component and set it to **justifyContent(FlexAlign.Center)**. For details, see [Grid Layout](../reference/arkui-ts/ts-container-gridcontainer.md). - Example: +Example: ``` GridContainer({ sizeType: SizeType.SM, columns: 12 }) { @@ -247,7 +180,7 @@ async function enterImmersion(mainWindow: window.Window) { }) await mainWindow.setFullScreen(true) await mainWindow.setSystemBarEnable(["status", "navigation"]) - await mainWindow.setSystemBarProperties({ + await mainWindow.sArkTSystemBarProperties({ navigationBarColor: "#00000000", statusBarColor: "#00000000", navigationBarContentColor: "#FF0000", @@ -265,16 +198,459 @@ export default class MainAbility extends Ability { } ``` -## How do I execute JavaScript functions in the \ component in ArkTS code? +## How do I fix misidentification of the pan gesture where container nesting is involved? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +Set the **distance** attribute to **1** for the gesture. By default, this attribute is set to **5**. + +## How do I obtain the height of a component? + +Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 + +You can obtain the changes in the width and height of a component through **onAreaChange**. + +Example: + + +``` +Column() { + Text(this.value) + .backgroundColor(Color.Green).margin(30).fontSize(20) + .onClick(() => { + this.value = this.value + 'Text' + }) + .onAreaChange((oldValue: Area, newValue: Area) => { + console.info(`Ace: on area change, oldValue is ${JSON.stringify(oldValue)} value is ${JSON.stringify(newValue)}`) + this.size = JSON.stringify(newValue) + }) +``` + +## How do I obtain the offset of the \ component? Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 -Call the **runJavaScript** API in the **WebController** to asynchronously execute JavaScript scripts. This API uses a callback to return the execution result. Note: **runJavaScript** can only be called after **loadUrl** has been completed. For example, it can be called in **onPageEnd**. +Bind the **\** component to a **Scoller** object and obtain the offset through **currentOffset**. -Reference: [Web](../reference/arkui-ts/ts-basic-components-web.md) +Example: -## How do I fix misidentification of the pan gesture where container nesting is involved? -Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 +``` +Column() { + List({ space: 20, initialIndex: 0,scroller: this.scroller}) { + ForEach(this.arr, (item) => { + ListItem() { + Text('' + item) + .width('100%').height(100).fontSize(16) + .textAlign(TextAlign.Center).borderRadius(10).backgroundColor(0xFFFFFF) + }.editable(true) + }, item => item) + } + .listDirection(Axis.Vertical) // Arrangement direction + .editMode(this.editFlag) + .onScroll((xOffset: number, yOffset: number) => { + console.info("yOffset======="+this.scroller.currentOffset().yOffset) + }) +}.width('100%') +``` -Set the **distance** attribute to **1** for the gesture. By default, this attribute is set to **5**. +## How do I obtain the value of param for the target page of redirection implemented using router? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + + +``` +// In versions earlier than 3.1.5.5, obtain the value through router.getParams().key. +private value: string = router.getParams().value; +// In 3.1.6.5 and later versions, obtain the value through router.getParams()['key']. +private value: string = router.getParams()['value']; +``` + +## Does the \ component support redirection to a local page? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +No. This feature is not supported. + +## How do I disable the transition effect for pages switched using router or navigator? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +1. Define the **pageTransition** method for the current and target pages, by following instructions in [Example](../reference/arkui-ts/ts-page-transition-animation.md#example). + +2. Set the **duration** parameter of both **PageTransitionEnter** and **PageTransitionExit** to **0**. + +## How do I select the pixel unit during UI development? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +It depends. + +The vp unit ensures consistency of visual effects across resolutions. For example, it ensures that an icon is displayed consistently under different resolutions. + +The lpx unit produces a visual effect where items are zoomed in or out proportionally. + +If you are concerned about visual effect consistency of items, for example, buttons, texts, and lists, use the vp unit. If your focus is on the layout, for example, 1/2 grid, the lpx is a better choice. + +## What color formats are used in ArkTS? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +The color can be represented in two formats, for example, 0x7F000000 or '\#7F000000'. The first two digits indicate opacity, and the last six digits indicate RGB. + + +``` +fontColor(0x7F000000) +fontColor( '#7F000000' ) +``` + +## How do I listen for the return operation on a page? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +When a return operation is performed on a page, the system calls the **onBackPress()** callback of the **@Entry** decorated custom component. You can implement related service logic in the callback. + +Reference: [Custom Component Lifecycle Callbacks](../ui/ui-ts-custom-component-lifecycle-callbacks.md) + +## Can I customize the eye icon for the \ component in password mode? + +Applicable to: OpenHarmony SDK 3.0, stage model of API version 9 + +No. The eye icon can be shown or hidden through **showPasswordIcon** when **type** of the **\** component is set to **InputType.Password**. It cannot be customized. + +Reference: [TextInput](../reference/arkui-ts/ts-basic-components-textinput.md) + +## Why can't images be loaded over HTTP? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +HTTP is insecure and HTTP sources will be filtered out by the trustlist. For security purposes, use HTTPS. + +## What should I do if the spacing set for the TextView layout does not fit the UI? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +By default, the **align** attribute of **TextView** is set to **Center**. To display the text from left to right, set the **align** attribute to **Start**. + +## Why do the constraintSize settings fail to take effect? + +Applicable to: OpenHarmony SDK 3.0, stage model of API version 9 + +If **constraintSize** is set for a component and the width of its child component is set to a percentage, for example, **width('100%')**, **constraintSize** takes effect by multiplying the maximum width by the percentage. As a result, the child component may overflow, in which case it looks like the **constraintSize** settings fail to take effect. + +## How do I set the background color to transparent? + +Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9 + +Set **backgroundColor** to **'\#00000000'**. + +## What should I do if the \ component cannot scroll to the bottom? + +Applicable to: OpenHarmony SDK 3.0, stage model of API version 9 + +Unless otherwise specified, the height of the **\** component is equal to the window height. In this case, the component's bottom area will be blocked by components (if any) outside of it. To fix this issue, set the height of the **\** component or use the flex layout to limit this height. + +## How do I use the onSubmit event of the \ component? + +Applicable to: OpenHarmony SDK 3.0, stage model of API version 9 + +The **onSubmit** event is triggered when the Enter key is pressed and accepts the current Enter key type as its input parameter. You can set the Enter key type for the **\** component through the **enterKeyType** attribute. The Enter key style of the soft keyboard requires the support of the input method. + +Reference: [TextInput](../reference/arkui-ts/ts-basic-components-textinput.md) + +## What is the maximum number of pages allowed during page routing? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +The maximum number of pages supported by the page stack is 32. When this limit is reached, the **router.push** API cannot be used for page redirection. + +## Does ArkUI allow components to be dynamically created in code? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +Yes. You can dynamically creaete components using [conditional rendering](../quick-start/arkts-rendering-control.md#conditional-rendering) and [loop rendering](../quick-start/arkts-rendering-control.md#loop-rendering). + +## What should I do if the PixelMap object carried in page routing cannot be obtained from the target page? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +Page routing supports only the common object type and common JSON data structure. To pass a **PixelMap** object to the target page, store it in the **localStorage**. + +## How do I use .caretPosition(0) to move the caret to the start of the text area when onEditChange is triggered for the \ component? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +The **onEditChange** event is triggered when the input box gains focus. Under this scenario, the caret position is related to the position where the gesture is when the event is triggered, and **caretPosition** cannot be used to change the caret position. Call **setTimeout** for asynchronous processing first. + +## Is there any method for selecting all items in the \ component? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +No. This feature is not supported yet. + +## Why can't I select a date when the type attribute of the input text box is set to date? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +Setting the **type** attribute of the input component to **date** means that the component accepts dates as input and the user will be notified of the valid input format. It does not display a date picker. To display a date picker, use the **\** component. + +## What should I do if the displayed input keyboard gets squeezed when using the **\** component? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +This issue may occur when the flex layout is used. To fix it, switch to the column layout. + +## How does the parent component pass values to a @Link decorated member variable in its child component? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +To pass a value from the parent component to the **@Link** decorated member variable in a child component, add **"$"** in front of the value. + +Example: + + +``` +@Component +struct FoodImageDisplay { + @Link imageSrc: Resource + + build() { + Stack({ alignContent: Alignment.BottomStart }) { + Image(this.imageSrc) + .objectFit(ImageFit.Contain) + Text('Tomato') + .fontSize(26) + .fontWeight(500) + .margin({ left: 26, bottom: 17.4 }) + } + .backgroundColor('#FFedf2f5') + .height(357) + } +} + +@Entry +@Component +struct FoodDetail { + + @State imageSrc: Resource = $r('app.media.Tomato') + + build() { + Column() { + FoodImageDisplay({imageSrc:$imageSrc}) + } + .alignItems(HorizontalAlign.Center) + } +} +``` + +## How do I share variables between Page abilities? + +Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9 + +1. Use a lightweight database. + +2. Use persistent data management. + +3. Use the emitter event communication mechanism. + + +## How do I customize the control bar style of the \