实现要点组件拆解资源引入页面路由WebView
开始实践由于前面的木鱼和现在的烟花都是同一个小工具运用,公用组件的拆分、页面跳转和资源的引入全有涉及,以是就连同 WebView 一起总结一下。
组件拆解
在 ArkUI 中,UI 显示的内容均为组件,由框架直接供应的称为系统组件,由开拓者定义的称为自定义组件。这里我们将所有页面的导航拆分成一个公用组件,并定义为 HdNav.ets。
import { router } from 39;@kit.ArkUI'@Componentexport struct HdNav { @StorageProp('topHeight') topHeight: number = 0 @Prop title: string = 'hello world' @Prop hasBorder: boolean = false @Prop leftIcon: ResourceStr = $r('app.media.ic_common_back') @Prop rightIcon: ResourceStr = $r('sys.media.ohos_ic_public_more') @Prop showRightIcon: boolean = true @Prop iconColor: ResourceStr = $r('app.color.black') @Prop titleColor: string = '#131313' @BuilderParam menuBuilder: () => void = this.defaultMenu @Builder defaultMenu() { } build() { Row({ space: 16 }) { Image(this.leftIcon) .size({ width: 24, height: 24 }) .onClick(() => router.back()) .fillColor(this.iconColor) Row() { if (this.title) { Text(this.title) .fontWeight(600) .fontColor(this.titleColor) .layoutWeight(1) .textAlign(TextAlign.Center) .fontSize(18) .maxLines(1) .textOverflow({ overflow: TextOverflow.Ellipsis }) } } .height(56) .layoutWeight(1) if (this.showRightIcon) { Image(this.rightIcon) .size({ width: 24, height: 24 }) .objectFit(ImageFit.Contain) .bindMenu(this.menuBuilder) } else { Blank() .width(24) } } .padding({ left: 16, right: 16, top: this.topHeight }) .height(56 + this.topHeight) .width('100%') .border({ width: { bottom: this.hasBorder ? $r('app.float.common_border_width') : 0 }, color: $r('app.color.common_gray_bg') }) }}
资源引入
运用开拓过程中,常常须要用到颜色、字体、间距、图片等资源,在不同的设备或配置中,这些资源的值可能不同。
运用资源:借助资源文件能力,开拓者在运用中自定义资源,自行管理这些资源在不同的设备或配置中的表现。系统资源:开拓者直策应用系统预置的资源定义。# 引入resouces/base/media下的home_selected的图片$r('app.media.home_selected')# 导入resources/rawfile下的index.html文件$rawfile("index.html")# 获取resources/rawfile下的audio.mp3音频await getContext(this).resourceManager.getRawFd("audio.mp3")
页面路由
页面路由 router 根据页面的 uri 找到目标页面,从而实现跳转。以最根本的两个页面之间的跳转为例,详细实现步骤如下:
在 “Project“窗口,打开 src> main >ets,右键点击 pages 文件夹,创建一个页面。在 resources/base/profile 下的 main_pages.json,新建一个 pages 中创建页面的文件名(把稳大小写)。调用 router.push () 路由到指定页面。调用 router.back () 回到首页。WebView
页面加载是 Web 组件的基本功能。根据页面加载数据来源可以分为三种常用场景,包括加载网络页面、加载本地页面、加载 HTML 格式的富文本数据。
页面加载过程中,若涉及网络资源获取,须要配置 ohos.permission.INTERNET 网络访问权限,下面以本地静态文件的方法举例。
将资源文件放置在运用的 resources/rawfile 目录下。鸿蒙 Next 运用代码import web_webview from '@ohos.web.webview';import { HdNav } from '@mygames/basic';@Entry@Componentstruct WebComponent { controller: web_webview.WebviewController = new web_webview.WebviewController(); build() { Column() { HdNav({ title: '看烟花秀', showRightIcon: false, iconColor: $r('app.color.black') }) Button('loadData') .onClick(() => { try { this.controller.loadUrl($rawfile("index.html")); } catch (error) { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); } }) // 组件创建时,加载www.example.com Web({ src: $rawfile("index.html"), controller: this.controller }) } }}
烟花代码
到这里鸿蒙 Next 运用实战暂告一段落了。但是鸿蒙系统供应了开箱即用的原生 AI 能力,更方便了我们开拓者实现运用的快速智能化,以是,鸿蒙 Next 智能运用实战,待续~