鸿蒙应用开发-路由与生命周期

2024-02-12  本文已影响0人  程序员阿兵

目录

1. 路由-常用API

如何新建页面,如何跳转和回退操作

@Entry
@Component
struct DetailPage {
 build() {
   Column({ space: 15 }) {
     Text('Detail Page')
       .fontSize(40)
     Button('Back')
   }
   .height('100%')
   .width('100%')
   .justifyContent(FlexAlign.Center)
 }
}
#src/main/resources/base/profile/main_pages.json
{
 "src": [
   "pages/Index",
+    "pages/DetailPage"
 ]
}
TIP
import router from '@ohos.router'
@Entry
@Component
struct Index {
 build() {
   Column({ space: 15 }) {
     Text('Index Page')
       .fontSize(40)
     Button('Jump To Detail Page')
       .onClick(() => {
         // 1. 跳转,压入页面栈顶部
         // router.pushUrl({
         //   url: 'pages/DetailPage'
         // })

         // 2. 跳转,替换当前页面栈
         // router.replaceUrl({
         //   url: 'pages/DetailPage'
         // })

         // 3. 返回
         // router.back()
       })
   }
   .height('100%')
   .width('100%')
   .justifyContent(FlexAlign.Center)
 }
}

页面栈的最大容量为32个页面。如果超过这个限制,可以调用 router.clear() 方法清空历史页面栈,释放内存空间。

2. 路由-参数传递
import router from '@ohos.router'

class User {
 name: string
 age: number
}

@Entry
@Component
struct Index {

 @State
 user: User = {
   name: 'jack',
   age: 18
 }

 build() {
   Column({ space: 15 }) {
     Text('Index Page')
       .fontSize(40)
     Button('Jump To Detail Page')
       .onClick(() => {
         router.pushUrl({
           url: 'pages/DetailPage',
           params: this.user
         })
       })
   }
   .height('100%')
   .width('100%')
   .justifyContent(FlexAlign.Center)
 }
}
import router from '@ohos.router'
import promptAction from '@ohos.promptAction'
@Entry
@Component
struct DetailPage {

 aboutToAppear() {
   const params = router.getParams()
   promptAction.showToast({ message: params['name'] + params['age'] })
 }

 build() {
   Column({ space: 15 }) {
     Text('Detail Page')
       .fontSize(40)
     Button('Back')
       .onClick(() => {
         router.back()
       })
   }
   .height('100%')
   .width('100%')
   .justifyContent(FlexAlign.Center)
 }
}
3. UIAbility-生命周期

当用户打开、切换和返回到对应应用时,应用中的UIAbility实例会在其生命周期的不同状态之间转换。

WechatIMG332.png
1.UIAbility实例创建完成时触发,系统会调用 onCreate() 回调。

2.onForeground() 回调,在 UIAbility 的UI界面可见之前,如 UIAbility切换至前台时触发。

  1. onBackground()回调,在 UIAbility 的UI界面完全不可见之后,如 UIAbility 切换至后台时候触发。

4.Destroy 状态在UIAbility 实例销毁时触发,系统会调用 onDestroy() 回调。

4. UIAbility跳转
Button('Jump To PayAbility Page')
 .onClick(() => {
   const context = getContext(this) as common.UIAbilityContext
   const want: Want = {
     bundleName: 'com.itcast.myapplication',
     abilityName: 'PayAbility'
   }
   context.startAbility(want)
 })

Button('Back')
 .onClick(() => {
   router.back()
 })
上一篇 下一篇

猜你喜欢

热点阅读