跳至主要內容

云音乐2

周子力2025年8月19日大约 1 分钟教学文档HarmonyOSTypeScript

云音乐2-页面跳转

1.跳转原理

先生成一个子窗口,然后在这个子窗口中加载广告页面。主页面的内容在主窗口中加载。 在广告子窗口中,设置一个按钮,点击后关闭广告子窗口。 然后通过 windowStage.loadContent() 方法加载主页面的内容。

EntryAbility.ets


async  onWindowStageCreate(windowStage: window.WindowStage): Promise<void> {
    // Main window is created, set main page for this ability
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    const childWin = await windowStage.createSubWindow("ad_win") // 创建广告子窗口
    await childWin.showWindow() // 显示广告子窗口
    await childWin.setUIContent("pages/Start/Start") // 设置广告子窗口的页面
    // 加载主页

    windowStage.loadContent('pages/Index/Index', (err) => {
      if (err.code) {
        hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
        return;
      }
      hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
    });
  }

2.广告页面

Start.ets

import { window } from '@kit.ArkUI'

@Entry
@Component
struct Advertisement {
  @State time: number = 5 // 广告倒计时时间,默认为5秒
  timer: number = -1 // 定时器ID,默认为-1表示未设置

  aboutToAppear() {
    // 必须重置才能改动画的内容
    //设置一个定时器,每秒减1,直到为0时关闭广告窗口
    this.timer = setInterval(() => {
      if (this.time <= 0) {
        clearInterval(this.timer)
        window.findWindow("ad_win").destroyWindow() // 关闭广告窗口,这里的'ad_win' 是之前创建广告子窗口时设置的名称
        return
      }
      this.time -= 1
    }, 1000)
  }
// 页面消失时,清除定时器
  aboutToDisappear() {
    clearInterval(this.timer)
  }

  build() {
    Stack({ alignContent: Alignment.TopEnd }) {
      Button(`跳过${this.time}`)
        .onClick(() => {
          window.findWindow("ad_win").destroyWindow()
        })
        .margin(12)
        .backgroundColor('#ccc')
        .fontColor('#fff')
    }
    .width('100%')
    .height('100%')
    .backgroundImage($r('app.media.ad'))
    .backgroundImageSize({
      width: '100%',
      height: '100%'
    })
    .padding({
      top: 10,//AppStorage.get("topHeight"),
      bottom:10// AppStorage.get("bottomHeight")
    })
  }
}


上次编辑于: 2025/8/19 09:03:47
贡献者: zilizhou