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

!12801 翻译完成 12669+12647+12343+11926

Merge pull request !12801 from ester.zhou/TR-12647
# Webview # @ohos.web.webview (Webview)
The **Webview** module provides APIs for web control. The **Webview** module provides APIs for web control.
...@@ -11,6 +11,7 @@ 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. > - 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 ## 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). **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 ## Modules to Import
...@@ -2122,6 +2123,366 @@ struct WebComponent { ...@@ -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<boolean>): 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\<boolean> | 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<boolean>
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\<boolean> | 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 ## WebCookieManager
Implements a **WebCookie** object to manage behavior of cookies in **\<Web>** components. All **\<Web>** components in an application share a **WebCookie** object. Implements a **WebCookie** object to manage behavior of cookies in **\<Web>** components. All **\<Web>** components in an application share a **WebCookie** object.
...@@ -3750,3 +4111,89 @@ Provides usage information of the Web SQL Database. ...@@ -3750,3 +4111,89 @@ Provides usage information of the Web SQL Database.
| origin | string | Yes | No| Index of the origin.| | origin | string | Yes | No| Index of the origin.|
| usage | number | Yes | No| Storage usage of the origin. | | usage | number | Yes | No| Storage usage of the origin. |
| quota | number | Yes | No| Storage quota 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. |
###
...@@ -672,6 +672,316 @@ Sets whether to enable web debugging. ...@@ -672,6 +672,316 @@ Sets whether to enable web debugging.
} }
``` ```
### blockNetwork<sup>9+</sup>
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)
}
}
}
```
### defaultFixedFontSize<sup>9+</sup>
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)
}
}
}
```
### defaultFontSize<sup>9+</sup>
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)
}
}
}
```
### minFontSize<sup>9+</sup>
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)
}
}
}
```
### webFixedFont<sup>9+</sup>
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)
}
}
}
```
### webSansSerifFont<sup>9+</sup>
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)
}
}
}
```
### webSerifFont<sup>9+</sup>
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)
}
}
}
```
### webStandardFont<sup>9+</sup>
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)
}
}
}
```
### webFantasyFont<sup>9+</sup>
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)
}
}
}
```
### webCursiveFont<sup>9+</sup>
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 ## Events
The universal events are not supported. The universal events are not supported.
...@@ -1635,7 +1945,7 @@ Invoked when an SSL error occurs during resource loading. ...@@ -1635,7 +1945,7 @@ Invoked when an SSL error occurs during resource loading.
### onClientAuthenticationRequest<sup>9+</sup> ### onClientAuthenticationRequest<sup>9+</sup>
onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array<string>, issuers : Array<string>}) => void) onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array\<string>, issuers : Array\<string>}) => void)
Invoked when an SSL client certificate request is received. Invoked when an SSL client certificate request is received.
...@@ -1978,14 +2288,14 @@ Registers a callback for window creation. ...@@ -1978,14 +2288,14 @@ Registers a callback for window creation.
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller:WebController = new WebController() controller: web_webview.WebviewController = new web_webview.WebviewController()
build() { build() {
Column() { Column() {
Web({ src:'www.example.com', controller: this.controller }) Web({ src:'www.example.com', controller: this.controller })
.multiWindowAccess(true) .multiWindowAccess(true)
.onWindowNew((event) => { .onWindowNew((event) => {
console.log("onWindowNew...") console.log("onWindowNew...")
var popController: WebController = new WebController() var popController: web_webview.WebviewController = new web_webview.WebviewController()
event.handler.setWebController(popController) event.handler.setWebController(popController)
}) })
} }
...@@ -2059,9 +2369,184 @@ Invoked to notify the caller of the search result on the web page. ...@@ -2059,9 +2369,184 @@ Invoked to notify the caller of the search result on the web page.
} }
``` ```
### onDataResubmitted<sup>9+</sup>
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();
})
}
}
}
```
### onPageVisible<sup>9+</sup>
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)
})
}
}
}
```
### onInterceptKeyEvent<sup>9+</sup>
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;
})
}
}
}
```
### onTouchIconUrlReceived<sup>9+</sup>
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))
})
}
}
}
```
### onFaviconReceived<sup>9+</sup>
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 ## 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 ### getLineNumber
...@@ -2113,7 +2598,7 @@ Obtains the path and name of the web page source file. ...@@ -2113,7 +2598,7 @@ Obtains the path and name of the web page source file.
## JsResult ## JsResult
Implements the **JsResult** object, which indicates the result returned to the **\<Web>** 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 **\<Web>** component to indicate the user operation performed in the dialog box. For the sample code, see [onAlert Event](#onalert).
### handleCancel ### handleCancel
...@@ -2141,7 +2626,7 @@ Notifies the **\<Web>** component of the user's confirm operation in the dialog ...@@ -2141,7 +2626,7 @@ Notifies the **\<Web>** component of the user's confirm operation in the dialog
## FullScreenExitHandler<sup>9+</sup> ## FullScreenExitHandler<sup>9+</sup>
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.
### exitFullScreen<sup>9+</sup> ### exitFullScreen<sup>9+</sup>
...@@ -2151,23 +2636,23 @@ Exits full screen mode. ...@@ -2151,23 +2636,23 @@ Exits full screen mode.
## ControllerHandler<sup>9+</sup> ## ControllerHandler<sup>9+</sup>
Implements a **WebController** object for new **\<Web>** components. For the sample code, see [onWindowNew](#onwindownew9). Implements a **WebviewController** object for new **\<Web>** components. For the sample code, see [onWindowNew](#onwindownew9).
### setWebController<sup>9+</sup> ### setWebController<sup>9+</sup>
setWebController(controller: WebController): void setWebController(controller: WebviewController): void
Sets a **WebController** object. Sets a **WebviewController** object.
**Parameters** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | 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 **\<Web>** component.|
## WebResourceError ## 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 ### getErrorCode
...@@ -2195,7 +2680,7 @@ Obtains error information about resource loading. ...@@ -2195,7 +2680,7 @@ Obtains error information about resource loading.
## WebResourceRequest ## 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 ### getRequestHeader
...@@ -2269,7 +2754,7 @@ Describes the request/response header returned by the **\<Web>** component. ...@@ -2269,7 +2754,7 @@ Describes the request/response header returned by the **\<Web>** component.
## WebResourceResponse ## 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 ### getReasonMessage
...@@ -2417,7 +2902,7 @@ Sets the status code of the resource response. ...@@ -2417,7 +2902,7 @@ Sets the status code of the resource response.
## FileSelectorResult<sup>9+</sup> ## FileSelectorResult<sup>9+</sup>
Notifies the **\<Web>** component of the file selection result. For details about the sample code, see [onShowFileSelector](#onshowfileselector9). Notifies the **\<Web>** component of the file selection result. For the sample code, see [onShowFileSelector](#onshowfileselector9).
### handleFileList<sup>9+</sup> ### handleFileList<sup>9+</sup>
...@@ -2433,7 +2918,7 @@ Instructs the **\<Web>** component to select a file. ...@@ -2433,7 +2918,7 @@ Instructs the **\<Web>** component to select a file.
## FileSelectorParam<sup>9+</sup> ## FileSelectorParam<sup>9+</sup>
Implements the **FileSelectorParam** object. For details about the sample code, see [onShowFileSelector](#onshowfileselector9). Implements the **FileSelectorParam** object. For the sample code, see [onShowFileSelector](#onshowfileselector9).
### getTitle<sup>9+</sup> ### getTitle<sup>9+</sup>
...@@ -2485,7 +2970,7 @@ Checks whether multimedia capabilities are invoked. ...@@ -2485,7 +2970,7 @@ Checks whether multimedia capabilities are invoked.
## HttpAuthHandler<sup>9+</sup> ## HttpAuthHandler<sup>9+</sup>
Implements the **HttpAuthHandler** object. For details about the sample code, see [onHttpAuthRequest](#onhttpauthrequest9). Implements the **HttpAuthHandler** object. For the sample code, see [onHttpAuthRequest](#onhttpauthrequest9).
### cancel<sup>9+</sup> ### cancel<sup>9+</sup>
...@@ -2526,7 +3011,7 @@ Uses the password cached on the server for authentication. ...@@ -2526,7 +3011,7 @@ Uses the password cached on the server for authentication.
## SslErrorHandler<sup>9+</sup> ## SslErrorHandler<sup>9+</sup>
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).
### handleCancel<sup>9+</sup> ### handleCancel<sup>9+</sup>
...@@ -2542,7 +3027,7 @@ Continues using the SSL certificate. ...@@ -2542,7 +3027,7 @@ Continues using the SSL certificate.
## ClientAuthenticationHandler<sup>9+</sup> ## ClientAuthenticationHandler<sup>9+</sup>
Implements a **ClientAuthenticationHandler** object returned by the **\<Web>** component. For details about the sample code, see [onClientAuthenticationRequest](#onclientauthenticationrequest9). Implements a **ClientAuthenticationHandler** object returned by the **\<Web>** component. For the sample code, see [onClientAuthenticationRequest](#onclientauthenticationrequest9).
### confirm<sup>9+</sup> ### confirm<sup>9+</sup>
...@@ -2571,7 +3056,7 @@ Ignores this request. ...@@ -2571,7 +3056,7 @@ Ignores this request.
## PermissionRequest<sup>9+</sup> ## PermissionRequest<sup>9+</sup>
Implements the **PermissionRequest** object. For details about the sample code, see [onPermissionRequest](#onpermissionrequest9). Implements the **PermissionRequest** object. For the sample code, see [onPermissionRequest](#onpermissionrequest9).
### deny<sup>9+</sup> ### deny<sup>9+</sup>
...@@ -2617,7 +3102,7 @@ Grants the permission for resources requested by the web page. ...@@ -2617,7 +3102,7 @@ Grants the permission for resources requested by the web page.
## WebContextMenuParam<sup>9+</sup> ## WebContextMenuParam<sup>9+</sup>
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).
### x<sup>9+</sup> ### x<sup>9+</sup>
...@@ -2655,9 +3140,9 @@ Obtains the URL of the destination link. ...@@ -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.| | string | If it is a link that is being long pressed, the URL that has passed the security check is returned.|
### getUnfilterendLinkUrl<sup>9+</sup> ### getUnfilteredLinkUrl<sup>9+</sup>
getUnfilterendLinkUrl(): string getUnfilteredLinkUrl(): string
Obtains the URL of the destination link. Obtains the URL of the destination link.
...@@ -2693,7 +3178,7 @@ Checks whether image content exists. ...@@ -2693,7 +3178,7 @@ Checks whether image content exists.
## WebContextMenuResult<sup>9+</sup> ## WebContextMenuResult<sup>9+</sup>
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.
### closeContextMenu<sup>9+</sup> ### closeContextMenu<sup>9+</sup>
...@@ -2709,7 +3194,7 @@ Copies the image specified in **WebContextMenuParam**. ...@@ -2709,7 +3194,7 @@ Copies the image specified in **WebContextMenuParam**.
## JsGeolocation ## 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 ### invoke
...@@ -2727,7 +3212,7 @@ Sets the geolocation permission status of a web page. ...@@ -2727,7 +3212,7 @@ Sets the geolocation permission status of a web page.
## WebController ## WebController
Implements a **WebController** object to control the behavior of the **\<Web>** component. A **WebController** can control only one **\<Web>** component, and the APIs in the **WebController** can be invoked only after it has been bound to the target **\<Web>** component. Implements a **WebController** to control the behavior of the **\<Web>** component. A **WebController** can control only one **\<Web>** component, and the APIs in the **WebController** can be invoked only after it has been bound to the target **\<Web>** component.
### Creating an Object ### Creating an Object
...@@ -4008,7 +4493,7 @@ Searches for and highlights the next match. ...@@ -4008,7 +4493,7 @@ Searches for and highlights the next match.
``` ```
## HitTestValue<sup>9+</sup> ## HitTestValue<sup>9+</sup>
Implements the **HitTestValue** object. For details about the sample code, see [getHitTestValue](#gethittestvalue9). Implements the **HitTestValue** object. For the sample code, see [getHitTestValue](#gethittestvalue9).
### getType<sup>9+</sup> ### getType<sup>9+</sup>
getType(): HitTestType getType(): HitTestType
...@@ -4591,14 +5076,14 @@ Deletes all HTTP authentication credentials saved in the cache. This API returns ...@@ -4591,14 +5076,14 @@ Deletes all HTTP authentication credentials saved in the cache. This API returns
static getHttpAuthCredentials(host: string, realm: string): Array\<string\> static getHttpAuthCredentials(host: string, realm: string): Array\<string\>
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** **Parameters**
| Name | Type | Mandatory | Default Value | Description | | 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 for which you want to obtain the HTTP authentication credentials. | | realm | string | Yes | - | Realm to which HTTP authentication credentials apply. |
**Return value** **Return value**
...@@ -4644,7 +5129,7 @@ Saves HTTP authentication credentials for a given host and realm. This API retur ...@@ -4644,7 +5129,7 @@ Saves HTTP authentication credentials for a given host and realm. This API retur
| Name | Type | Mandatory | Default Value | Description | | 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. | | realm | string | Yes | - | Realm to which HTTP authentication credentials apply. |
| username | string | Yes | - | User name. | | username | string | Yes | - | User name. |
| password | string | Yes | - | Password. | | password | string | Yes | - | Password. |
...@@ -5374,8 +5859,8 @@ Stores this web page. This API uses an asynchronous callback to return the resul ...@@ -5374,8 +5859,8 @@ Stores this web page. This API uses an asynchronous callback to return the resul
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- | | -------- | ---------------------------------------- | ---- | ----------------------------------- |
| baseName | string | Yes| Save path. The value cannot be null.| | baseName | string | Yes| Save path. The value cannot be null.
| autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>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.| | autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>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<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise.| | callback | AsyncCallback<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise.|
**Example** **Example**
...@@ -5414,8 +5899,8 @@ Stores this web page. This API uses a promise to return the result. ...@@ -5414,8 +5899,8 @@ Stores this web page. This API uses a promise to return the result.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- | | -------- | ---------------------------------------- | ---- | ----------------------------------- |
| baseName | string | Yes| Save path. The value cannot be null.| | baseName | string | Yes| Save path. The value cannot be null.
| autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>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.| | autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>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** **Return value**
...@@ -5670,3 +6155,61 @@ Sets the message port in this object. For the complete sample code, see [postMes ...@@ -5670,3 +6155,61 @@ Sets the message port in this object. For the complete sample code, see [postMes
} }
} }
``` ```
## DataResubmissionHandler<sup>9+</sup>
Implements the **DataResubmissionHandler** for resubmitting or canceling the web form data.
### resend<sup>9+</sup>
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();
})
}
}
}
```
### cancel<sup>9+</sup>
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();
})
}
}
}
```
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
| Task | Description | Related Resources | | Task | Description | Related Resources |
| ----------- | ---------------------------------------- | ---------------------------------------- | | ----------- | ---------------------------------------- | ---------------------------------------- |
| Set up the development environment. | Understand the project structure of the declarative UI.<br>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)<br>[Resource Categories and Access](../quick-start/resource-categories-and-access.md) | | Set up the development environment. | Understand the project structure of the declarative UI.<br>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)<br>[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)| | 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.<br>Add built-in components and set the component style based on the page content to present.<br>Update and diversify the page content.| [Creating a Page](#creating-a-page)<br> [Common Layout Development](ui-ts-layout-linear.md)<br> [Common Components](ui-ts-components-intro.md)<br>[Setting the Component Style](#setting-the-component-styles)<br>[Updating Page Content](#updating-page-content)| | Develop a page. | Select an appropriate layout based on the use case.<br>Add built-in components and set the component style based on the page content to present.<br>Update and diversify the page content.| [Creating a Page](#creating-a-page)<br> [Common Layout Development](ui-ts-layout-linear.md)<br> [Common Components](ui-ts-components-intro.md)<br>[Setting the Component Style](#setting-the-component-styles)<br>[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)<br>[Canvas Components](../reference/arkui-ts/ts-components-canvas-canvas.md)<br>[Animation](../reference/arkui-ts/ts-animatorproperty.md)| | (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)<br>[Canvas Components](../reference/arkui-ts/ts-components-canvas-canvas.md)<br>[Animation](../reference/arkui-ts/ts-animatorproperty.md)|
......
# Flex Layout # 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 **\<Flex>** 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: [\<Flex>](../reference/arkui-ts/ts-container-flex.md) component, used to set layout attributes.
- Child component: any of the child items in the **\<Flex>** component.
- Main axis: axis along which items are placed in the **\<Flex>** 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 **\<Flex>** component. The sample code is as follows:
`Flex(options?: { direction?: FlexDirection, wrap?: FlexWrap, justifyContent?: FlexAlign, alignItems?: ItemAlign, alignContent?: FlexAlign })` `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:
### Flex Layout Direction
The **direction** parameter sets the direction in which items are laid out in the **\<Flex>** component and thereby defines the main axis. Available values are as follows:
![](figures/direction.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. - **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.
...@@ -28,7 +38,6 @@ The flex layout has two directions, following two axes. The main axis is the axi ...@@ -28,7 +38,6 @@ The flex layout has two directions, following two axes. The main axis is the axi
.padding(10) .padding(10)
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
![en-us_image_0000001218579606](figures/en-us_image_0000001218579606.png) ![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**. - **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**.
...@@ -79,12 +88,11 @@ The flex layout has two directions, following two axes. The main axis is the axi ...@@ -79,12 +88,11 @@ The flex layout has two directions, following two axes. The main axis is the axi
![en-us_image_0000001263339459](figures/en-us_image_0000001263339459.png) ![en-us_image_0000001263339459](figures/en-us_image_0000001263339459.png)
### Wrapping in the Flex Layout
## 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:
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. - **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 ```ts
Flex({ wrap: FlexWrap.NoWrap }) { Flex({ wrap: FlexWrap.NoWrap }) {
...@@ -99,7 +107,7 @@ By default, child components are laid out on a single line (also called an axis) ...@@ -99,7 +107,7 @@ By default, child components are laid out on a single line (also called an axis)
![en-us_image_0000001263139409](figures/en-us_image_0000001263139409.png) ![en-us_image_0000001263139409](figures/en-us_image_0000001263139409.png)
- **FlexWrap.Wrap**: Child components can break into multiple lines. - **FlexWrap.Wrap**: Child components can break into multiple lines along the main axis.
```ts ```ts
Flex({ wrap: FlexWrap.Wrap }) { Flex({ wrap: FlexWrap.Wrap }) {
...@@ -114,7 +122,7 @@ By default, child components are laid out on a single line (also called an axis) ...@@ -114,7 +122,7 @@ By default, child components are laid out on a single line (also called an axis)
![en-us_image_0000001218419614](figures/en-us_image_0000001218419614.png) ![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. - **FlexWrap.WrapReverse**: Child components can break into multiple lines in the reverse direction to the main axis.
```ts ```ts
Flex({ wrap: FlexWrap.WrapReverse}) { Flex({ wrap: FlexWrap.WrapReverse}) {
...@@ -129,15 +137,15 @@ By default, child components are laid out on a single line (also called an axis) ...@@ -129,15 +137,15 @@ By default, child components are laid out on a single line (also called an axis)
![en-us_image_0000001263259399](figures/en-us_image_0000001263259399.png) ![en-us_image_0000001263259399](figures/en-us_image_0000001263259399.png)
### Alignment in the Flex Layout
## Alignment in the Flex Layout #### Alignment on the Main Axis
### Alignment on the Main Axis
Use the **justifyContent** parameter to set alignment of items on the main axis. The available options are as follows: 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. ![](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 ```ts
Flex({ justifyContent: FlexAlign.Start }) { Flex({ justifyContent: FlexAlign.Start }) {
...@@ -146,13 +154,13 @@ Use the **justifyContent** parameter to set alignment of items on the main axis. ...@@ -146,13 +154,13 @@ Use the **justifyContent** parameter to set alignment of items on the main axis.
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
} }
.width('90%') .width('90%')
.padding(10) .padding({ top: 10, bottom: 10 })
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
![en-us_image_0000001218259634](figures/en-us_image_0000001218259634.png) ![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. The space between the first component and the main-start is the same as that between the last component and the main-end. - **FlexAlign.Center**: The items are aligned with each other toward the center of the container along the main axis.
```ts ```ts
Flex({ justifyContent: FlexAlign.Center }) { Flex({ justifyContent: FlexAlign.Center }) {
...@@ -161,11 +169,11 @@ Use the **justifyContent** parameter to set alignment of items on the main axis. ...@@ -161,11 +169,11 @@ Use the **justifyContent** parameter to set alignment of items on the main axis.
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
} }
.width('90%') .width('90%')
.padding(10) .padding({ top: 10, bottom: 10 })
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
![en-us_image_0000001218579608](figures/en-us_image_0000001218579608.png) ![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. - **FlexAlign.End**: The items are aligned with each other toward the end edge of the container along the main axis.
...@@ -176,13 +184,13 @@ Use the **justifyContent** parameter to set alignment of items on the main axis. ...@@ -176,13 +184,13 @@ Use the **justifyContent** parameter to set alignment of items on the main axis.
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
} }
.width('90%') .width('90%')
.padding(10) .padding({ top: 10, bottom: 10 })
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
![en-us_image_0000001218739568](figures/en-us_image_0000001218739568.png) ![en-us_image_0000001218739568](figures/mainEnd.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. - **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 ```ts
Flex({ justifyContent: FlexAlign.SpaceBetween }) { Flex({ justifyContent: FlexAlign.SpaceBetween }) {
...@@ -191,13 +199,13 @@ Use the **justifyContent** parameter to set alignment of items on the main axis. ...@@ -191,13 +199,13 @@ Use the **justifyContent** parameter to set alignment of items on the main axis.
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
} }
.width('90%') .width('90%')
.padding(10) .padding({ top: 10, bottom: 10 })
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
![en-us_image_0000001263019461](figures/en-us_image_0000001263019461.png) ![en-us_image_0000001263019461](figures/mainSpacebetween.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. - **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 ```ts
Flex({ justifyContent: FlexAlign.SpaceAround }) { Flex({ justifyContent: FlexAlign.SpaceAround }) {
...@@ -206,11 +214,11 @@ Use the **justifyContent** parameter to set alignment of items on the main axis. ...@@ -206,11 +214,11 @@ Use the **justifyContent** parameter to set alignment of items on the main axis.
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
} }
.width('90%') .width('90%')
.padding(10) .padding({ top: 10, bottom: 10 })
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
![en-us_image_0000001263339461](figures/en-us_image_0000001263339461.png) ![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. - **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.
...@@ -221,16 +229,18 @@ Use the **justifyContent** parameter to set alignment of items on the main axis. ...@@ -221,16 +229,18 @@ Use the **justifyContent** parameter to set alignment of items on the main axis.
Text('3').width('20%').height(50).backgroundColor(0xF5DEB3) Text('3').width('20%').height(50).backgroundColor(0xF5DEB3)
} }
.width('90%') .width('90%')
.padding(10) .padding({ top: 10, bottom: 10 })
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
![en-us_image_0000001263139411](figures/en-us_image_0000001263139411.png) ![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 **\<Flex>** 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. - **ItemAlign.Auto**: The items are automatically aligned in the flex container.
...@@ -305,7 +315,7 @@ Use the **alignItems** parameter to set alignment of items on the cross axis. Th ...@@ -305,7 +315,7 @@ Use the **alignItems** parameter to set alignment of items on the cross axis. Th
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
``` ```
![en-us_image_0000001218739570](figures/en-us_image_0000001218739570.png) ![en-us_image_0000001218739570](figures/itemalignstretch.png)
- **ItemAlign.Baseline**: The items are aligned at the baseline of the cross axis. - **ItemAlign.Baseline**: The items are aligned at the baseline of the cross axis.
...@@ -322,27 +332,228 @@ Use the **alignItems** parameter to set alignment of items on the cross axis. Th ...@@ -322,27 +332,228 @@ Use the **alignItems** parameter to set alignment of items on the cross axis. Th
![en-us_image_0000001263019463](figures/en-us_image_0000001263019463.png) ![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:
### Content Alignment ```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)
```
Use the **alignContent** parameter to set how content items are aligned within the flex container along the cross axis. ![](figures/alignself.png)
- **FlexAlign.Start**: The items are packed to the start of the container. In the preceding example, both **alignItems** of the **\<Flex>** component and the **alignSelf** attribute of the child component are set. In this case, the **alignSelf** settings take effect.
- **FlexAlign.Center**: The items are packed to the center of the container. #### Content Alignment
- **FlexAlign.End**: The items are packed to the end of the container. 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.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. - **FlexAlign.Start**: The items are aligned toward the start edge of the cross axis in the container.
- **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. ```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.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. - **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)
- **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.
```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)
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.
- **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 ## 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 ```ts
@Entry @Entry
...@@ -358,7 +569,6 @@ struct FlexExample { ...@@ -358,7 +569,6 @@ struct FlexExample {
} }
.height(70) .height(70)
.width('90%') .width('90%')
.padding(10)
.backgroundColor(0xAFEEEE) .backgroundColor(0xAFEEEE)
}.width('100%').margin({ top: 5 }) }.width('100%').margin({ top: 5 })
}.width('100%') }.width('100%')
...@@ -366,5 +576,4 @@ struct FlexExample { ...@@ -366,5 +576,4 @@ struct FlexExample {
} }
``` ```
![en-us_image_0000001261605867](figures/flexExample.png)
![en-us_image_0000001261605867](figures/en-us_image_0000001261605867.png)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册