diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md index a3ee6ebcbf0c7408d9532eba466c89ba04f85ae4..92f40c92f26257e614135694d49d69608ea32a23 100644 --- a/en/application-dev/reference/apis/js-apis-webview.md +++ b/en/application-dev/reference/apis/js-apis-webview.md @@ -1,6 +1,6 @@ -# Webview +# @ohos.web.webview (Webview) The **Webview** module provides APIs for web control. @@ -11,6 +11,7 @@ The **Webview** module provides APIs for web control. > - You can preview how the APIs of this module work on a real device. The preview is not yet available in the DevEco Studio Previewer. ## Required Permissions + **ohos.permission.INTERNET**, required for accessing online web pages. For details about how to apply for a permission, see [Declaring Permissions](../../security/accesstoken-guidelines.md). ## Modules to Import @@ -2122,6 +2123,366 @@ struct WebComponent { } ``` +### getOriginalUrl + +getOriginalUrl(): string + +Obtains the original URL of this page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------ | ----------------------- | +| string | Original URL of the current page.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getOrgUrl') + .onClick(() => { + try { + let url = this.controller.getOriginalUrl(); + console.log("original url: " + url); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getFavicon + +getFavicon(): image.PixelMap + +Obtains the favicon of this page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| -------------------------------------- | ------------------------------- | +| [PixelMap](js-apis-image.md#pixelmap7) | **PixelMap** object of the favicon of the page.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; +import image from "@ohos.multimedia.image" +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State pixelmap: image.PixelMap = undefined; + + build() { + Column() { + Button('getFavicon') + .onClick(() => { + try { + this.pixelmap = this.controller.getFavicon(); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### setNetworkAvailable + +setNetworkAvailable(enable: boolean): void + +Sets the **window.navigator.onLine** attribute in JavaScript. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | --------------------------------- | +| enable | boolean | Yes | Whether to enable **window.navigator.onLine**.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | +| 401 | Invalid input parameter. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('setNetworkAvailable') + .onClick(() => { + try { + this.controller.setNetworkAvailable(true); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### hasImage + +hasImage(callback: AsyncCallback): void + +Checks whether this page contains images. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | +| 401 | Invalid input parameter. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('hasImageCb') + .onClick(() => { + try { + this.controller.hasImage((err, data) => { + if (error) { + console.info(`hasImage error: ` + JSON.stringify(error)) + return; + } + console.info("hasImage: " + data); + }); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### hasImage + +hasImage(): Promise + +Checks whether this page contains images. This API uses a promise to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ----------------- | --------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | +| 401 | Invalid input parameter. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('hasImagePm') + .onClick(() => { + try { + this.controller.hasImage().then((data) => { + console.info('hasImage: ' + data); + }) + .catch(function (error) { + console.error("error: " + error); + }) + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### removeCache + +removeCache(clearRom: boolean): void + +Clears the cache in the application. This API will clear the cache for all webviews in the same application. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | -------------------------------------------------------- | +| clearRom | boolean | Yes | Whether to clear the cache in the ROM and RAM at the same time. The value **false** means to only clear the cache in the RAM.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | +| 401 | Invalid input parameter. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('removeCache') + .onClick(() => { + try { + this.controller.removeCache(false); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getBackForwardEntries + +getBackForwardEntries(): BackForwardList + +Obtains the historical information list of the current webview. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ----------------------------------- | --------------------------- | +| [BackForwardList](#backforwardlist) | Historical information list of the current webview.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getBackForwardEntries') + .onClick(() => { + try { + let list = this.controller.getBackForwardEntries() + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + ## WebCookieManager Implements a **WebCookie** object to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookie** object. @@ -3750,3 +4111,89 @@ Provides usage information of the Web SQL Database. | origin | string | Yes | No| Index of the origin.| | usage | number | Yes | No| Storage usage of the origin. | | quota | number | Yes | No| Storage quota of the origin. | + +## BackForwardList + +Provides the historical information list of the current webview. + +**System capability**: SystemCapability.Web.Webview.Core + +| Name | Type | Readable| Writable| Description | +| ------------ | ------ | ---- | ---- | ---------------------------- | +| currentIndex | number | Yes | No | Index of the current page in the page history stack.| +| size | number | Yes | No | Number of indexes in the history stack. | + +### getItemAtIndex + +getItemAtIndex(index: number): HistoryItem + +Obtains the page record with the specified index in the history stack. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| index | number | Yes | Index of the target page record in the history stack.| + +**Return value** + +| Type | Description | +| --------------------------- | ------------ | +| [HistoryItem](#historyitem) | Historical page record.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ----------------------- | +| 401 | Invalid input parameter | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; +import image from "@ohos.multimedia.image" + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State icon: image.PixelMap = undefined; + + build() { + Column() { + Button('getBackForwardEntries') + .onClick(() => { + try { + let list = this.controller.getBackForwardEntries(); + let historyItem = list.getItemAtIndex(list.currentIndex); + console.log("HistoryItem: " + JSON.stringify(historyItem)); + this.icon = item.icon; + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +## HistoryItem + +Describes a historical page record. + +**System capability**: SystemCapability.Web.Webview.Core + +| Name | Type | Readable| Writable| Description | +| ------------- | -------------------------------------- | ---- | ---- | ---------------------------- | +| icon | [PixelMap](js-apis-image.md#pixelmap7) | Yes | No | **PixelMap** object of the icon on the historical page.| +| historyUrl | string | Yes | No | URL of the historical page. | +| historyRawUrl | string | Yes | No | Original URL of the historical page. | +| title | string | Yes | No | Title of the historical page. | + +### diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md index 0c7861677bbfeb4f67f1c83b2c2fcf4286db02b7..0e9b480a1326760e25e56bca698bd8e8581bbb68 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -672,6 +672,316 @@ Sets whether to enable web debugging. } ``` +### blockNetwork9+ + +blockNetwork(block: boolean) + +Sets whether to block online downloads. + +**Parameters** + +| Name| Type| Mandatory| Default Value| Description | +| ------ | -------- | ---- | ------ | ----------------------------------- | +| block | boolean | Yes | false | Whether to block online downloads.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State block: boolean = true + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .blockNetwork(this.block) + } + } + } + ``` + +### defaultFixedFontSize9+ + +defaultFixedFontSize(size: number) + +Sets the default fixed font size of the web page. + +**Parameters** + +| Name| Type| Mandatory| Default Value| Description | +| ------ | -------- | ---- | ------ | ---------------------------- | +| size | number | Yes | 13 | Default fixed font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State size: number = 16 + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .defaultFixedFontSize(this.size) + } + } + } + ``` + +### defaultFontSize9+ + +defaultFontSize(size: number) + +Sets the default font size of the web page. + +**Parameters** + +| Name| Type| Mandatory| Default Value| Description | +| ------ | -------- | ---- | ------ | ------------------------ | +| size | number | Yes | 16 | Default font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State size: number = 13 + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .defaultFontSize(this.size) + } + } + } + ``` + +### minFontSize9+ + +minFontSize(size: number) + +Sets the minimum font size of the web page. + +**Parameters** + +| Name| Type| Mandatory| Default Value| Description | +| ------ | -------- | ---- | ------ | ------------------------ | +| size | number | Yes | 8 | Minimum font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State size: number = 13 + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .minFontSize(this.size) + } + } + } + ``` + +### webFixedFont9+ + +webFixedFont(family: string) + +Sets the fixed font family of the web page. + +**Parameters** + +| Name| Type| Mandatory| Default Value | Description | +| ------ | -------- | ---- | --------- | ---------------------------- | +| family | string | Yes | monospace | Fixed font family of the web page.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State family: string = "monospace" + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .webFixedFont(this.family) + } + } + } + ``` + +### webSansSerifFont9+ + +webSansSerifFont(family: string) + +Sets the sans serif font family of the web page. + +**Parameters** + +| Name| Type| Mandatory| Default Value | Description | +| ------ | -------- | ---- | ---------- | --------------------------------- | +| family | string | Yes | sans-serif | Sans serif font family of the web page.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State family: string = "sans-serif" + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .webSansSerifFont(this.family) + } + } + } + ``` + +### webSerifFont9+ + +webSerifFont(family: string) + +Sets the serif font family of the web page. + +**Parameters** + +| Name| Type| Mandatory| Default Value| Description | +| ------ | -------- | ---- | ------ | ---------------------------- | +| family | string | Yes | serif | Serif font family of the web page.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State family: string = "serif" + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .webSerifFont(this.family) + } + } + } + ``` + +### webStandardFont9+ + +webStandardFont(family: string) + +Sets the standard font family of the web page. + +**Parameters** + +| Name| Type| Mandatory| Default Value | Description | +| ------ | -------- | ---- | ---------- | ------------------------------- | +| family | string | Yes | sans serif | Standard font family of the web page.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State family: string = "sans-serif" + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .webStandardFont(this.family) + } + } + } + ``` + +### webFantasyFont9+ + +webFantasyFont(family: string) + +Sets the fantasy font family of the web page. + +**Parameters** + +| Name| Type| Mandatory| Default Value | Description | +| ------ | -------- | ---- | ------- | ------------------------------ | +| family | string | Yes | fantasy | Fantasy font family of the web page.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State family: string = "fantasy" + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .webFantasyFont(this.family) + } + } + } + ``` + +### webCursiveFont9+ + +webCursiveFont(family: string) + +Sets the cursive font family of the web page. + +**Parameters** + +| Name| Type| Mandatory| Default Value | Description | +| ------ | -------- | ---- | ------- | ------------------------------ | +| family | string | Yes | cursive | Cursive font family of the web page.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State family: string = "cursive" + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .webCursiveFont(this.family) + } + } + } + ``` + ## Events The universal events are not supported. @@ -1635,7 +1945,7 @@ Invoked when an SSL error occurs during resource loading. ### onClientAuthenticationRequest9+ -onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array, issuers : Array}) => void) +onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array\, issuers : Array\}) => void) Invoked when an SSL client certificate request is received. @@ -1646,7 +1956,7 @@ Invoked when an SSL client certificate request is received. | handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | The user's operation. | | host | string | Host name of the server that requests a certificate. | | port | number | Port number of the server that requests a certificate. | -| keyTypes | Array\ | Acceptable asymmetric private key types. | +| keyTypes | Array\ | Acceptable asymmetric private key types. | | issuers | Array\ | Issuer of the certificate that matches the private key.| **Example** @@ -1978,14 +2288,14 @@ Registers a callback for window creation. @Entry @Component struct WebComponent { - controller:WebController = new WebController() + controller: web_webview.WebviewController = new web_webview.WebviewController() build() { Column() { Web({ src:'www.example.com', controller: this.controller }) .multiWindowAccess(true) .onWindowNew((event) => { console.log("onWindowNew...") - var popController: WebController = new WebController() + var popController: web_webview.WebviewController = new web_webview.WebviewController() event.handler.setWebController(popController) }) } @@ -2059,9 +2369,184 @@ Invoked to notify the caller of the search result on the web page. } ``` +### onDataResubmitted9+ + +onDataResubmitted(callback: (event: {handler: DataResubmissionHandler}) => void) + +Invoked when the web form data is resubmitted. + +**Parameters** + +| Name | Type | Description | +| ------- | ---------------------------------------------------- | ---------------------- | +| handler | [DataResubmissionHandler](#dataresubmissionhandler9) | Handler for resubmitting web form data.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + Web({ src:'www.example.com', controller: this.controller }) + .onDataResubmitted((event) => { + console.log('onDataResubmitted') + event.handler.resend(); + }) + } + } + } + ``` + +### onPageVisible9+ + +onPageVisible(callback: (event: {url: string}) => void) + +Invoked when the old page is not displayed and the new page is about to be visible. + +**Parameters** + +| Name| Type| Description | +| ------ | -------- | ------------------------------------------------- | +| url | string | URL of the new page that is able to be visible when the old page is not displayed.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + Web({ src:'www.example.com', controller: this.controller }) + .onPageVisible((event) => { + console.log('onPageVisible url:' + event.url) + }) + } + } + } + ``` + +### onInterceptKeyEvent9+ + +onInterceptKeyEvent(callback: (event: KeyEvent) => boolean) + +Invoked when the key event is intercepted, before being consumed by the Webview. + +**Parameters** + +| Name| Type | Description | +| ------ | ------------------------------------------------------- | -------------------- | +| event | [KeyEvent](ts-universal-events-key.md#keyevent) | Key event that is triggered.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Whether to continue to transfer the key event to the Webview kernel.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + Web({ src:'www.example.com', controller: this.controller }) + .onInterceptKeyEvent((event) => { + if (event.keyCode == 2017 || event.keyCode == 2018) { + console.info(`onInterceptKeyEvent get event.keyCode ${event.keyCode}`) + return true; + } + return false; + }) + } + } + } + ``` + +### onTouchIconUrlReceived9+ + +onTouchIconUrlReceived(callback: (event: {url: string, precomposed: boolean}) => void) + +Invoked when an apple-touch-icon URL is received. + +**Parameters** + +| Name | Type| Description | +| ----------- | -------- | ---------------------------------- | +| url | string | Received apple-touch-icon URL.| +| precomposed | boolean | Whether the apple-touch-icon is precomposed.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + Web({ src:'www.baidu.com', controller: this.controller }) + .onTouchIconUrlReceived((event) => { + console.log('onTouchIconUrlReceived:' + JSON.stringify(event)) + }) + } + } + } + ``` + +### onFaviconReceived9+ + +onFaviconReceived(callback: (event: {favicon: image.PixelMap}) => void) + +Invoked when this web page receives a new favicon. + +**Parameters** + +| Name | Type | Description | +| ------- | ---------------------------------------------- | ----------------------------------- | +| favicon | [PixelMap](../apis/js-apis-image.md#pixelmap7) | **PixelMap** object of the received favicon.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + import image from "@ohos.multimedia.image" + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + @State icon: image.PixelMap = undefined; + build() { + Column() { + Web({ src:'www.example.com', controller: this.controller }) + .onFaviconReceived((event) => { + console.log('onFaviconReceived:' + JSON.stringify(event)) + this.icon = event.favicon; + }) + } + } + } + ``` + ## ConsoleMessage -Implements the **ConsoleMessage** object. For details about the sample code, see [onConsole](#onconsole). +Implements the **ConsoleMessage** object. For the sample code, see [onConsole](#onconsole). ### getLineNumber @@ -2113,7 +2598,7 @@ Obtains the path and name of the web page source file. ## JsResult -Implements the **JsResult** object, which indicates the result returned to the **\** component to indicate the user operation performed in the dialog box. For details about the sample code, see [onAlert Event](#onalert). +Implements the **JsResult** object, which indicates the result returned to the **\** component to indicate the user operation performed in the dialog box. For the sample code, see [onAlert Event](#onalert). ### handleCancel @@ -2141,7 +2626,7 @@ Notifies the **\** component of the user's confirm operation in the dialog ## FullScreenExitHandler9+ -Implements a **FullScreenExitHandler** object for listening for exiting full screen mode. For the sample code, see [onFullScreenEnter](#onfullscreenenter9). +Implements a **FullScreenExitHandler** object for listening for exiting full screen mode. For the sample code, see onFullScreenEnter. ### exitFullScreen9+ @@ -2151,23 +2636,23 @@ Exits full screen mode. ## ControllerHandler9+ -Implements a **WebController** object for new **\** components. For the sample code, see [onWindowNew](#onwindownew9). +Implements a **WebviewController** object for new **\** components. For the sample code, see [onWindowNew](#onwindownew9). ### setWebController9+ -setWebController(controller: WebController): void +setWebController(controller: WebviewController): void -Sets a **WebController** object. +Sets a **WebviewController** object. **Parameters** | Name | Type | Mandatory | Default Value | Description | | ---------- | ------------- | ---- | ---- | ------------------------- | -| controller | WebController | Yes | - | **WebController** object to set.| +| controller | [WebviewController](../apis/js-apis-webview.md#webviewcontroller) | Yes | - | **WebviewController** object of the **\** component.| ## WebResourceError -Implements the **WebResourceError** object. For details about the sample code, see [onErrorReceive](#onerrorreceive). +Implements the **WebResourceError** object. For the sample code, see [onErrorReceive](#onerrorreceive). ### getErrorCode @@ -2195,7 +2680,7 @@ Obtains error information about resource loading. ## WebResourceRequest -Implements the **WebResourceRequest** object. For details about the sample code, see [onErrorReceive](#onerrorreceive). +Implements the **WebResourceRequest** object. For the sample code, see [onErrorReceive](#onerrorreceive). ### getRequestHeader @@ -2269,7 +2754,7 @@ Describes the request/response header returned by the **\** component. ## WebResourceResponse -Implements the **WebResourceResponse** object. For details about the sample code, see [onHttpErrorReceive](#onhttperrorreceive). +Implements the **WebResourceResponse** object. For the sample code, see [onHttpErrorReceive](#onhttperrorreceive). ### getReasonMessage @@ -2417,7 +2902,7 @@ Sets the status code of the resource response. ## FileSelectorResult9+ -Notifies the **\** component of the file selection result. For details about the sample code, see [onShowFileSelector](#onshowfileselector9). +Notifies the **\** component of the file selection result. For the sample code, see [onShowFileSelector](#onshowfileselector9). ### handleFileList9+ @@ -2433,7 +2918,7 @@ Instructs the **\** component to select a file. ## FileSelectorParam9+ -Implements the **FileSelectorParam** object. For details about the sample code, see [onShowFileSelector](#onshowfileselector9). +Implements the **FileSelectorParam** object. For the sample code, see [onShowFileSelector](#onshowfileselector9). ### getTitle9+ @@ -2485,7 +2970,7 @@ Checks whether multimedia capabilities are invoked. ## HttpAuthHandler9+ -Implements the **HttpAuthHandler** object. For details about the sample code, see [onHttpAuthRequest](#onhttpauthrequest9). +Implements the **HttpAuthHandler** object. For the sample code, see [onHttpAuthRequest](#onhttpauthrequest9). ### cancel9+ @@ -2526,7 +3011,7 @@ Uses the password cached on the server for authentication. ## SslErrorHandler9+ -Implements an **SslErrorHandler** object. For details about the sample code, see [onSslErrorEventReceive Event](#onsslerroreventreceive9). +Implements an **SslErrorHandler** object. For the sample code, see [onSslErrorEventReceive Event](#onsslerroreventreceive9). ### handleCancel9+ @@ -2542,7 +3027,7 @@ Continues using the SSL certificate. ## ClientAuthenticationHandler9+ -Implements a **ClientAuthenticationHandler** object returned by the **\** component. For details about the sample code, see [onClientAuthenticationRequest](#onclientauthenticationrequest9). +Implements a **ClientAuthenticationHandler** object returned by the **\** component. For the sample code, see [onClientAuthenticationRequest](#onclientauthenticationrequest9). ### confirm9+ @@ -2571,7 +3056,7 @@ Ignores this request. ## PermissionRequest9+ -Implements the **PermissionRequest** object. For details about the sample code, see [onPermissionRequest](#onpermissionrequest9). +Implements the **PermissionRequest** object. For the sample code, see [onPermissionRequest](#onpermissionrequest9). ### deny9+ @@ -2617,7 +3102,7 @@ Grants the permission for resources requested by the web page. ## WebContextMenuParam9+ -Provides the information about the context menu that is displayed when a page element is long pressed. For details about the sample code, see [onContextMenuShow](#oncontextmenushow9). +Provides the information about the context menu that is displayed when a page element is long pressed. For the sample code, see [onContextMenuShow](#oncontextmenushow9). ### x9+ @@ -2655,9 +3140,9 @@ Obtains the URL of the destination link. | ------ | ------------------------- | | string | If it is a link that is being long pressed, the URL that has passed the security check is returned.| -### getUnfilterendLinkUrl9+ +### getUnfilteredLinkUrl9+ -getUnfilterendLinkUrl(): string +getUnfilteredLinkUrl(): string Obtains the URL of the destination link. @@ -2693,7 +3178,7 @@ Checks whether image content exists. ## WebContextMenuResult9+ -Implements the response event executed when a context menu is displayed. For details about the sample code, see [onContextMenuShow](#oncontextmenushow9). +Implements a **WebContextMenuResult** object. For the sample code, see onContextMenuShow. ### closeContextMenu9+ @@ -2709,7 +3194,7 @@ Copies the image specified in **WebContextMenuParam**. ## JsGeolocation -Implements the **PermissionRequest** object. For details about the sample code, see [onGeolocationShow Event](#ongeolocationshow). +Implements the **PermissionRequest** object. For the sample code, see [onGeolocationShow Event](#ongeolocationshow). ### invoke @@ -2727,7 +3212,7 @@ Sets the geolocation permission status of a web page. ## WebController -Implements a **WebController** object to control the behavior of the **\** component. A **WebController** can control only one **\** component, and the APIs in the **WebController** can be invoked only after it has been bound to the target **\** component. +Implements a **WebController** to control the behavior of the **\** component. A **WebController** can control only one **\** component, and the APIs in the **WebController** can be invoked only after it has been bound to the target **\** component. ### Creating an Object @@ -4008,7 +4493,7 @@ Searches for and highlights the next match. ``` ## HitTestValue9+ -Implements the **HitTestValue** object. For details about the sample code, see [getHitTestValue](#gethittestvalue9). +Implements the **HitTestValue** object. For the sample code, see [getHitTestValue](#gethittestvalue9). ### getType9+ getType(): HitTestType @@ -4528,7 +5013,7 @@ Implements the **WebDataBase** object. static existHttpAuthCredentials(): boolean -Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously. +Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously. **Return value** @@ -4591,14 +5076,14 @@ Deletes all HTTP authentication credentials saved in the cache. This API returns static getHttpAuthCredentials(host: string, realm: string): Array\ -Retrieves HTTP authentication credentials for a given host and domain. This API returns the result synchronously. +Retrieves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. **Parameters** | Name | Type | Mandatory | Default Value | Description | | ----- | ------ | ---- | ---- | ---------------- | -| host | string | Yes | - | Host for which you want to obtain the HTTP authentication credentials.| -| realm | string | Yes | - | Realm for which you want to obtain the HTTP authentication credentials. | +| host | string | Yes | - | Host to which HTTP authentication credentials apply.| +| realm | string | Yes | - | Realm to which HTTP authentication credentials apply. | **Return value** @@ -4644,7 +5129,7 @@ Saves HTTP authentication credentials for a given host and realm. This API retur | Name | Type | Mandatory | Default Value | Description | | -------- | ------ | ---- | ---- | ---------------- | -| host | string | Yes | - | Host for which you want to obtain the HTTP authentication credentials.| +| host | string | Yes | - | Host to which HTTP authentication credentials apply.| | realm | string | Yes | - | Realm to which HTTP authentication credentials apply. | | username | string | Yes | - | User name. | | password | string | Yes | - | Password. | @@ -5374,8 +5859,8 @@ Stores this web page. This API uses an asynchronous callback to return the resul | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| baseName | string | Yes| Save path. The value cannot be null.| -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.| +| baseName | string | Yes| Save path. The value cannot be null. +| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. | callback | AsyncCallback | Yes | Callback used to return the save path if the operation is successful and null otherwise.| **Example** @@ -5414,8 +5899,8 @@ Stores this web page. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| baseName | string | Yes| Save path. The value cannot be null.| -| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.| +| baseName | string | Yes| Save path. The value cannot be null. +| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. **Return value** @@ -5670,3 +6155,61 @@ Sets the message port in this object. For the complete sample code, see [postMes } } ``` + +## DataResubmissionHandler9+ + +Implements the **DataResubmissionHandler** for resubmitting or canceling the web form data. + +### resend9+ + +resend(): void + +Resends the web form data. + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + Web({ src:'www.example.com', controller: this.controller }) + .onDataResubmitted((event) => { + console.log('onDataResubmitted') + event.handler.resend(); + }) + } + } + } + ``` + +### cancel9+ + +cancel(): void + +Cancels the resending of web form data. + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController() + build() { + Column() { + Web({ src:'www.example.com', controller: this.controller }) + .onDataResubmitted((event) => { + console.log('onDataResubmitted') + event.handler.cancel(); + }) + } + } + } + ``` diff --git a/en/application-dev/ui/figures/en-us_image_0000001218259634.png b/en/application-dev/ui/figures/en-us_image_0000001218259634.png deleted file mode 100644 index a54bd7cd05accb496c691b2527b08b0a11cd8c66..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001218259634.png and /dev/null differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218579608.png b/en/application-dev/ui/figures/en-us_image_0000001218579608.png deleted file mode 100644 index 74526d5efee72c20ce09c731842c0d1c56159a97..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001218579608.png and /dev/null differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218739568.png b/en/application-dev/ui/figures/en-us_image_0000001218739568.png deleted file mode 100644 index a66ff857ba7629951a39a1c2cc19c7b6fb43b9e1..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001218739568.png and /dev/null differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001218739570.png b/en/application-dev/ui/figures/en-us_image_0000001218739570.png deleted file mode 100644 index 006efca8f390adea7edb0b4f54609c04fd0bd098..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001218739570.png and /dev/null differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001261605867.png b/en/application-dev/ui/figures/en-us_image_0000001261605867.png deleted file mode 100644 index 096d7f530cc2d82391be453a7a5dbe659ba15513..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001261605867.png and /dev/null differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263019461.png b/en/application-dev/ui/figures/en-us_image_0000001263019461.png deleted file mode 100644 index b79b7923adca0d6e2a211c29ef0d34b70bf02583..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001263019461.png and /dev/null differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263139411.png b/en/application-dev/ui/figures/en-us_image_0000001263139411.png deleted file mode 100644 index 3e481248c0e16f3311644a35fa3c71269a3e7877..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001263139411.png and /dev/null differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001263339461.png b/en/application-dev/ui/figures/en-us_image_0000001263339461.png deleted file mode 100644 index 183d9468ca3901183b3fa55facbc976418e7a5f1..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001263339461.png and /dev/null differ diff --git a/en/application-dev/ui/figures/flex.png b/en/application-dev/ui/figures/flex.png index 848ceef3873ed6f83466d9ab42f6aa68cb341fe9..81d0d6365351f8071e21d6968d045dc80486a303 100644 Binary files a/en/application-dev/ui/figures/flex.png and b/en/application-dev/ui/figures/flex.png differ diff --git a/en/application-dev/ui/figures/itemalignstretch.png b/en/application-dev/ui/figures/itemalignstretch.png new file mode 100644 index 0000000000000000000000000000000000000000..0fadb0e9099cc754a281bd1bedfdea4a59f64894 Binary files /dev/null and b/en/application-dev/ui/figures/itemalignstretch.png differ diff --git a/en/application-dev/ui/ui-ts-developing-intro.md b/en/application-dev/ui/ui-ts-developing-intro.md index 0b484ff1c5a42220bd7760d1d595d8fb1affc7a5..3f55b96e103949753a9ce6713327ad91984720fe 100644 --- a/en/application-dev/ui/ui-ts-developing-intro.md +++ b/en/application-dev/ui/ui-ts-developing-intro.md @@ -4,7 +4,7 @@ | Task | Description | Related Resources | | ----------- | ---------------------------------------- | ---------------------------------------- | -| Set up the development environment. | Understand the project structure of the declarative UI.
Learn the resource categories and how to access resources. | [OpenHarmony Project Overview](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-project-overview-0000001218440650)
[Resource Categories and Access](../quick-start/resource-categories-and-access.md) | +| Set up the development environment. | Understand the project structure of the declarative UI.
Learn the resource categories and how to access resources. | [OpenHarmony Project Overview](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-project-overview-0000001218440650)
[Resource Categories and Access](../quick-start/resource-categories-and-access.md)| | Learn ArkTS. | As its name implies, ArkTS is a superset of TypeScript. It is the preferred, primary programming language for application development in OpenHarmony.| [Learning ArkTS](../quick-start/arkts-get-started.md)| | Develop a page. | Select an appropriate layout based on the use case.
Add built-in components and set the component style based on the page content to present.
Update and diversify the page content.| [Creating a Page](#creating-a-page)
[Common Layout Development](ui-ts-layout-linear.md)
[Common Components](ui-ts-components-intro.md)
[Setting the Component Style](#setting-the-component-styles)
[Updating Page Content](#updating-page-content)| | (Optional) Diversify the page content. | Leverage the drawing and animation features to effectively increase user engagement. | [Drawing Components](../reference/arkui-ts/ts-drawing-components-circle.md)
[Canvas Components](../reference/arkui-ts/ts-components-canvas-canvas.md)
[Animation](../reference/arkui-ts/ts-animatorproperty.md)| diff --git a/en/application-dev/ui/ui-ts-layout-flex.md b/en/application-dev/ui/ui-ts-layout-flex.md index 291616ffc189581004105331a270085dfee75add..20ea6ca4cedba93562ccc8ddf2d2233ea9edc1ca 100644 --- a/en/application-dev/ui/ui-ts-layout-flex.md +++ b/en/application-dev/ui/ui-ts-layout-flex.md @@ -1,351 +1,562 @@ # Flex Layout +The flex layout is the most flexible layout used in adaptive layout. It provides simple and powerful tools for distributing space and aligning items. -The **\** component is used to create a flex layout. In a flex container created using the **Flex** API, child components can be laid out flexibly. For example, if there are three child components in a flex container, they can be horizontally centered and vertically equally spaced. +- Container: [\](../reference/arkui-ts/ts-container-flex.md) component, used to set layout attributes. +- Child component: any of the child items in the **\** component. +- Main axis: axis along which items are placed in the **\** component. Child components are laid out along the main axis by default. The start point of the main axis is referred to as main-start, and the end point is referred to as main-end. +- Cross axis: axis that runs perpendicular to the main axis. The start point of the cross axis is referred to as cross-start, and the end point is referred to as cross-end. -## Creating a Flex Layout +The following uses **FlexDirection.Row** as an example. -The available API is as follows: +![](figures/flex.png) + +## Container Attributes + +Create a flex layout through the **Flex** API provided by the **\** component. The sample code is as follows: `Flex(options?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: FlexAlign, alignItems?: ItemAlign, alignContent?: FlexAlign })` -In the preceding code, the **direction** parameter defines the flex layout direction; the **justifyContent** parameter defines the alignment mode of child components in the flex layout direction; the **alignContent** parameter defines the alignment mode of child components in the vertical direction; the **wrap** parameter defines whether the content can wrap onto multiple lines. -## Flex Layout Direction -The flex layout has two directions, following two axes. The main axis is the axis along which the child components follow each other. The cross axis is the axis perpendicular to the main axis. The **direction** parameter establishes the main axis. The available options are as follows: -- **FlexDirection.Row** (default value): The main axis runs along the row horizontally, and the child components are laid out from the start edge of the main axis. +### Flex Layout Direction +The **direction** parameter sets the direction in which items are laid out in the **\** component and thereby defines the main axis. Available values are as follows: - ```ts - Flex({ direction: FlexDirection.Row }) { - Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(50).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` +![](figures/direction.png) - ![en-us_image_0000001218579606](figures/en-us_image_0000001218579606.png) +- **FlexDirection.Row** (default value): The main axis runs along the row horizontally, and the child components are laid out from the start edge of the main axis. + + ```ts + Flex({ direction: FlexDirection.Row }) { + Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(50).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + ![en-us_image_0000001218579606](figures/en-us_image_0000001218579606.png) - **FlexDirection.RowReverse**: The main axis runs along the row horizontally, and the child components are laid out from the end edge of the main axis, in a direction opposite to **FlexDirection.Row**. - ```ts - Flex({ direction: FlexDirection.RowReverse }) { - Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(50).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` + ```ts + Flex({ direction: FlexDirection.RowReverse }) { + Text('1').width('33%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(50).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` - ![en-us_image_0000001218739566](figures/en-us_image_0000001218739566.png) + ![en-us_image_0000001218739566](figures/en-us_image_0000001218739566.png) - **FlexDirection.Column**: The main axis runs along the column vertically, and the child components are laid out from the start edge of the main axis. - ```ts - Flex({ direction: FlexDirection.Column }) { - Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('100%').height(50).backgroundColor(0xD2B48C) - Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` + ```ts + Flex({ direction: FlexDirection.Column }) { + Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('100%').height(50).backgroundColor(0xD2B48C) + Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` - ![en-us_image_0000001263019457](figures/en-us_image_0000001263019457.png) + ![en-us_image_0000001263019457](figures/en-us_image_0000001263019457.png) - **FlexDirection.ColumnReverse**: The main axis runs along the column vertically, and the child components are laid out from the end edge of the main axis, in a direction opposite to **FlexDirection.Column**. - ```ts - Flex({ direction: FlexDirection.ColumnReverse }) { - Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('100%').height(50).backgroundColor(0xD2B48C) - Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) - } - .height(70) - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001263339459](figures/en-us_image_0000001263339459.png) - - -## Wrapping in the Flex Layout - -By default, child components are laid out on a single line (also called an axis) in the flex container. Use the **wrap** parameter to set whether child components can wrap onto multiple lines. The available options are as follows: - -- **FlexWrap.NoWrap**: Child components are laid out on a single line. This may cause the child components to shrink to fit the container when the total width of the child components is greater than the width of the container. - - ```ts - Flex({ wrap: FlexWrap.NoWrap }) { - Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('50%').height(50).backgroundColor(0xD2B48C) - Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001263139409](figures/en-us_image_0000001263139409.png) - -- **FlexWrap.Wrap**: Child components can break into multiple lines. - - ```ts - Flex({ wrap: FlexWrap.Wrap }) { - Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('50%').height(50).backgroundColor(0xD2B48C) - Text('3').width('50%').height(50).backgroundColor(0xD2B48C) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001218419614](figures/en-us_image_0000001218419614.png) - -- **FlexWrap.WrapReverse**: Child components can break into multiple lines in the reverse order to the row. - - ```ts - Flex({ wrap: FlexWrap.WrapReverse}) { - Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('50%').height(50).backgroundColor(0xD2B48C) - Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001263259399](figures/en-us_image_0000001263259399.png) - - -## Alignment in the Flex Layout - - -### Alignment on the Main Axis + ```ts + Flex({ direction: FlexDirection.ColumnReverse }) { + Text('1').width('100%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('100%').height(50).backgroundColor(0xD2B48C) + Text('3').width('100%').height(50).backgroundColor(0xF5DEB3) + } + .height(70) + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![en-us_image_0000001263339459](figures/en-us_image_0000001263339459.png) + +### Wrapping in the Flex Layout + +By default, child components are laid out on a single line (also called an axis) in the flex container. You can use the **wrap** parameter to set whether child components can wrap onto multiple lines. Available values are as follows: + +- **FlexWrap.NoWrap** (default value): Child components are laid out on a single line. This may cause the child components to shrink to fit the container when the total width of the child components is greater than the width of the container. + + ```ts + Flex({ wrap: FlexWrap.NoWrap }) { + Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('50%').height(50).backgroundColor(0xD2B48C) + Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![en-us_image_0000001263139409](figures/en-us_image_0000001263139409.png) + +- **FlexWrap.Wrap**: Child components can break into multiple lines along the main axis. + + ```ts + Flex({ wrap: FlexWrap.Wrap }) { + Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('50%').height(50).backgroundColor(0xD2B48C) + Text('3').width('50%').height(50).backgroundColor(0xD2B48C) + } + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![en-us_image_0000001218419614](figures/en-us_image_0000001218419614.png) + +- **FlexWrap.WrapReverse**: Child components can break into multiple lines in the reverse direction to the main axis. + + ```ts + Flex({ wrap: FlexWrap.WrapReverse}) { + Text('1').width('50%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('50%').height(50).backgroundColor(0xD2B48C) + Text('3').width('50%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![en-us_image_0000001263259399](figures/en-us_image_0000001263259399.png) + +### Alignment in the Flex Layout + +#### Alignment on the Main Axis Use the **justifyContent** parameter to set alignment of items on the main axis. The available options are as follows: -- **FlexAlign.Start**: The items are aligned with each other toward the start edge of the container along the main axis. - - ```ts - Flex({ justifyContent: FlexAlign.Start }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001218259634](figures/en-us_image_0000001218259634.png) - -- **FlexAlign.Center**: The items are aligned with each other toward the center of the container along the main axis. The space between the first component and the main-start is the same as that between the last component and the main-end. - - ```ts - Flex({ justifyContent: FlexAlign.Center }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001218579608](figures/en-us_image_0000001218579608.png) +![](figures/justifyContent.png) + +- **FlexAlign.Start** (default value): The items are aligned with each other toward the start edge of the container along the main axis. + + ```ts + Flex({ justifyContent: FlexAlign.Start }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![en-us_image_0000001218259634](figures/mainStart.png) + +- **FlexAlign.Center**: The items are aligned with each other toward the center of the container along the main axis. + + ```ts + Flex({ justifyContent: FlexAlign.Center }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![en-us_image_0000001218579608](figures/mainCenter.png) - **FlexAlign.End**: The items are aligned with each other toward the end edge of the container along the main axis. - ```ts - Flex({ justifyContent: FlexAlign.End }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001218739568](figures/en-us_image_0000001218739568.png) - -- **FlexAlign.SpaceBetween**: The items are evenly distributed within the container along the main axis. The first item is aligned with the main-start, the last item is aligned with the main-end, and the remaining items are distributed so that the space between any two adjacent items is the same. - - ```ts - Flex({ justifyContent: FlexAlign.SpaceBetween }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001263019461](figures/en-us_image_0000001263019461.png) - -- **FlexAlign.SpaceAround**: The items are evenly distributed within the container along the main axis. The space between the first item and main-start, and that between the last item and cross-main are both half the size of the space between two adjacent items. - - ```ts - Flex({ justifyContent: FlexAlign.SpaceAround }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001263339461](figures/en-us_image_0000001263339461.png) + ```ts + Flex({ justifyContent: FlexAlign.End }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![en-us_image_0000001218739568](figures/mainEnd.png) + +- **FlexAlign.SpaceBetween**: The items are evenly distributed within the container along the main axis. The first and last items are aligned with the edges of the container. + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![en-us_image_0000001263019461](figures/mainSpacebetween.png) + +- **FlexAlign.SpaceAround**: The items are evenly distributed in the container along the main axis. The space between the first item and main-start, and that between the last item and main-end are both half of the space between two adjacent items. + + ```ts + Flex({ justifyContent: FlexAlign.SpaceAround }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263339461](figures/mainSpacearound.png) - **FlexAlign.SpaceEvenly**: The items are equally distributed along the main axis. The space between the first item and main-start, the space between the last item and main-end, and the space between two adjacent items are the same. - ```ts - Flex({ justifyContent: FlexAlign.SpaceEvenly }) { - Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) - Text('2').width('20%').height(50).backgroundColor(0xD2B48C) - Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) - } - .width('90%') - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001263139411](figures/en-us_image_0000001263139411.png) + ```ts + Flex({ justifyContent: FlexAlign.SpaceEvenly }) { + Text('1').width('20%').height(50).backgroundColor(0xF5DEB3) + Text('2').width('20%').height(50).backgroundColor(0xD2B48C) + Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) + } + .width('90%') + .padding({ top: 10, bottom: 10 }) + .backgroundColor(0xAFEEEE) + ``` + + ![zh-cn_image_0000001263139411](figures/mainSpaceevenly.png) +#### Alignment on the Cross Axis -### Alignment on the Cross Axis +Alignment on the cross axis can be set for both the container and child components, with that set for child components having a higher priority. -Use the **alignItems** parameter to set alignment of items on the cross axis. The available options are as follows: +##### Setting Alignment on the Cross Axis for the Container +Use the **alignItems** parameter of the **\** component to set alignment of items on the cross axis. The available options are as follows: - **ItemAlign.Auto**: The items are automatically aligned in the flex container. - ```ts - Flex({ alignItems: ItemAlign.Auto }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` + ```ts + Flex({ alignItems: ItemAlign.Auto }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` - ![en-us_image_0000001218419616](figures/en-us_image_0000001218419616.png) + ![en-us_image_0000001218419616](figures/en-us_image_0000001218419616.png) - **ItemAlign.Start**: The items are aligned with the start edge of the container along the cross axis. - ```ts - Flex({ alignItems: ItemAlign.Start }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001263259401](figures/en-us_image_0000001263259401.png) + ```ts + Flex({ alignItems: ItemAlign.Start }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![en-us_image_0000001263259401](figures/en-us_image_0000001263259401.png) - **ItemAlign.Start**: The items are aligned with the center of the container along the cross axis. - ```ts - Flex({ alignItems: ItemAlign.Center }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001218259636](figures/en-us_image_0000001218259636.png) + ```ts + Flex({ alignItems: ItemAlign.Center }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![en-us_image_0000001218259636](figures/en-us_image_0000001218259636.png) - **ItemAlign.End**: The items are aligned with the end edge of the container along the cross axis. - ```ts - Flex({ alignItems: ItemAlign.End }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001218579610](figures/en-us_image_0000001218579610.png) + ```ts + Flex({ alignItems: ItemAlign.End }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![en-us_image_0000001218579610](figures/en-us_image_0000001218579610.png) - **ItemAlign.Stretch**: The items are stretched along the cross axis. If no constraints are set, the items are stretched to fill the size of the container on the cross axis. - ```ts - Flex({ alignItems: ItemAlign.Stretch }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001218739570](figures/en-us_image_0000001218739570.png) + ```ts + Flex({ alignItems: ItemAlign.Stretch }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![en-us_image_0000001218739570](figures/itemalignstretch.png) - **ItemAlign.Baseline**: The items are aligned at the baseline of the cross axis. - ```ts - Flex({ alignItems: ItemAlign.Baseline }) { - Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) - Text('2').width('33%').height(40).backgroundColor(0xD2B48C) - Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) - } - .size({width: '90%', height: 80}) - .padding(10) - .backgroundColor(0xAFEEEE) - ``` - - ![en-us_image_0000001263019463](figures/en-us_image_0000001263019463.png) - - -### Content Alignment + ```ts + Flex({ alignItems: ItemAlign.Baseline }) { + Text('1').width('33%').height(30).backgroundColor(0xF5DEB3) + Text('2').width('33%').height(40).backgroundColor(0xD2B48C) + Text('3').width('33%').height(50).backgroundColor(0xF5DEB3) + } + .size({width: '90%', height: 80}) + .padding(10) + .backgroundColor(0xAFEEEE) + ``` + + ![en-us_image_0000001263019463](figures/en-us_image_0000001263019463.png) + +##### Setting Alignment on the Cross Axis for Child Components +Use the **alignSelf** attribute of child components to set their alignment in the container on the cross axis. The settings overwrite the default **alignItems** settings in the flex layout container. The sample code is as follows: -Use the **alignContent** parameter to set how content items are aligned within the flex container along the cross axis. - -- **FlexAlign.Start**: The items are packed to the start of the container. +```ts +Flex({ direction: FlexDirection.Row, alignItems: ItemAlign.Center }) { // The items are aligned with the center of the container. + Text('alignSelf Start').width('25%').height(80) + .alignSelf(ItemAlign.Start) + .backgroundColor(0xF5DEB3) + Text('alignSelf Baseline') + .alignSelf(ItemAlign.Baseline) + .width('25%') + .height(80) + .backgroundColor(0xD2B48C) + Text('alignSelf Baseline').width('25%').height(100) + .backgroundColor(0xF5DEB3) + .alignSelf(ItemAlign.Baseline) + Text('no alignSelf').width('25%').height(100) + .backgroundColor(0xD2B48C) + Text('no alignSelf').width('25%').height(100) + .backgroundColor(0xF5DEB3) + +}.width('90%').height(220).backgroundColor(0xAFEEEE) +``` -- **FlexAlign.Center**: The items are packed to the center of the container. +![](figures/alignself.png) + +In the preceding example, both **alignItems** of the **\** component and the **alignSelf** attribute of the child component are set. In this case, the **alignSelf** settings take effect. + +#### Content Alignment + +Use the **alignContent** parameter to set how space is distributed between and around content items along the cross axis. This parameter is valid only for a flex layout that contains multiple lines. The available options are as follows: + +- **FlexAlign.Start**: The items are aligned toward the start edge of the cross axis in the container. + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.Start }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossStart.png](figures/crossStart.png) + +- **FlexAlign.Center**: The items are aligned toward the center of the cross axis in the container. + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.Center }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossCenter.png](figures/crossCenter.png) + +- **FlexAlign.End**: The items are aligned toward the end edge of the cross axis in the container. + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.End }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossEnd.png](figures/crossEnd.png) + +- **FlexAlign.SpaceBetween**: The items are evenly distributed in the container along the cross axis, with the first and last items aligned with the edges of the cross axis. + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceBetween }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossSpacebetween.png](figures/crossSpacebetween.png) + +- **FlexAlign.SpaceAround**: The items are evenly distributed in the container along the cross axis. The spacing before the first item and after the last item is half of the spacing between two adjacent items. + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceAround }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossSpacearound.png](figures/crossSpacearound.png) + +- **FlexAlign.SpaceEvenly**: The items are evenly distributed in the container along the cross axis. The spacing between each two adjacent items, the spacing between the start edge and the first item, and the spacing between the end edge and the last item, are the same. + + ```ts + Flex({ justifyContent: FlexAlign.SpaceBetween, wrap: FlexWrap.Wrap, alignContent: FlexAlign.SpaceAround }) { + Text('1').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('2').width('60%').height(20).backgroundColor(0xD2B48C) + Text('3').width('40%').height(20).backgroundColor(0xD2B48C) + Text('4').width('30%').height(20).backgroundColor(0xF5DEB3) + Text('5').width('20%').height(20).backgroundColor(0xD2B48C) + } + .width('90%') + .height(100) + .backgroundColor(0xAFEEEE) + ``` + + ![crossSpaceevenly.png](figures/crossSpaceevenly.png) + +### Adaptive Stretching of Flex Layout + +When the size of the container in the flex layout is not large enough, the following attributes of the child component can be used to achieve adaptive layout. +- **flexBasis**: base size of the child component in the container along the main axis. It sets the space occupied by the child component. If this attribute is not set or is set to **auto**, the space occupied by the child component is the value of width/height. + + ```ts + Flex() { + Text('flexBasis("auto")') + .flexBasis('auto') // When width is not set and flexBasis is set to auto, the content is loose. + .height(100) + .backgroundColor(0xF5DEB3) + Text('flexBasis("auto")'+' width("40%")') + .width('40%') + .flexBasis('auto') // When width is set and flexBasis is set to auto, the value of width is used. + .height(100) + .backgroundColor(0xD2B48C) + + Text('flexBasis(100)') // When width is not set and flexBasis is set to 100, the width is 100 vp. + .flexBasis(100) + .height(100) + .backgroundColor(0xF5DEB3) + + Text('flexBasis(100)') + .flexBasis(100) + .width(200) // When width is set to 200 and flexBasis 100, the width is 100 vp, which means that the settings of flexBasis take precedence. + .height(100) + .backgroundColor(0xD2B48C) + }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) + ``` + + ![](figures/flexbasis.png) -- **FlexAlign.End**: The items are packed to the end of the container. +- **flexGrow**: percentage of the flex layout's remaining space that is allocated to the child component. In other words, it is the grow factor of the child component. -- **FlexAlign.SpaceBetween**: The items are evenly distributed; the first item is aligned with the main-start while the last item is aligned with the main-end. + ```ts + Flex() { + Text('flexGrow(1)') + .flexGrow(2) + .width(100) + .height(100) + .backgroundColor(0xF5DEB3) + + Text('flexGrow(3)') + .flexGrow(2) + .width(100) + .height(100) + .backgroundColor(0xD2B48C) + + Text('no flexGrow') + .width(100) + .height(100) + .backgroundColor(0xF5DEB3) + }.width(400).height(120).padding(10).backgroundColor(0xAFEEEE) + ``` + + ![](figures/flexgrow.png) -- **FlexAlign.SpaceAround**: The items are evenly distributed, with the space between the item and the main-start and between the item and the main-end equals half of the space between adjacent items. +In the preceding figure, the width of the parent container is 400 vp, the original width of the three child components is 100 vp, which adds up to the total width of 300 vp. The remaining space 100 vp is allocated to the child components based on their **flexGrow** settings. Child components that do not have **flexGrow** set are not involved in the allocation of remaining space. +The first child component and the second child component receive their share of remaining space at the 2:3 ratio. The width of the first child component is 100 vp + 100 vp x 2/5 = 140 vp, and the width of the second child component is 100 vp + 100 vp x 3/5 = 160 vp. -- **FlexAlign.SpaceEvenly**: The items are evenly distributed, with the space between the item and the main-start and between the item and the main-end equals the space between adjacent items. +- **flexShrink**: shrink factor of the child component when the size of all child components is larger than the flex container. + ```ts + Flex({ direction: FlexDirection.Row }) { + Text('flexShrink(3)') + .flexShrink(3) + .width(200) + .height(100) + .backgroundColor(0xF5DEB3) + + Text('no flexShrink') + .width(200) + .height(100) + .backgroundColor(0xD2B48C) + + Text('flexShrink(2)') + .flexShrink(2) + .width(200) + .height(100) + .backgroundColor(0xF5DEB3) + }.width(400).height(120).padding(10).backgroundColor(0xAFEEEE) + ``` + + ![](figures/flexshrink.png) ## Example Scenario -In this example, a flex layout is designed to achieve the following effects: The child components are laid out horizontally on a single line, even when the total width of the child components exceeds the width of the container; the child components are horizontally aligned at both ends and vertically aligned toward the center of the container; the space is evenly divided by the child components except for the start and end ones. +With the flex layout, child components can be arranged horizontally, aligned at both edges, evenly spaced, and centered in the vertical direction. The sample code is as follows: ```ts -@Entry +@Entry @Component struct FlexExample { build() { @@ -358,7 +569,6 @@ struct FlexExample { } .height(70) .width('90%') - .padding(10) .backgroundColor(0xAFEEEE) }.width('100%').margin({ top: 5 }) }.width('100%') @@ -366,5 +576,4 @@ struct FlexExample { } ``` - -![en-us_image_0000001261605867](figures/en-us_image_0000001261605867.png) +![en-us_image_0000001261605867](figures/flexExample.png)