【鸿蒙开发】闪屏页面练习

1. 创建页面 Index.ets

javascript 复制代码
@Entry
@Component
struct Index {
  build() {
    Column() {
      Text("首页")
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
    }
    .width('100%')
    .height('100%')
  }
}

2. 创建页面 SplashScreen.ets

javascript 复制代码
@Entry
@Component
struct SplashScreen {
  @State message: string = 'SplashScreen'

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
      }
      .width('100%')
    }
    .height('100%')
  }
}

3. 创建store工具 StoreUtil.ets

javascript 复制代码
import preferences from '@ohos.data.preferences'

export class StoreUtil {
  constructor(private readonly context: Context, private readonly storeName: string) {
  }

  getStore() {
    return preferences.getPreferences(this.context, this.storeName)
  }

  async getData<T>(key): Promise<T> {
    const store = await this.getStore()
    const data = await store.get(key, "{}") as string
    return JSON.parse(data) as T
  }

  async setData<T>(key: string, data: T): Promise<void> {
    const store = await this.getStore()
    await store.put(key, JSON.stringify(data))
    await store.flush()
  }

  async delData(key: string): Promise<void> {
    const store = await this.getStore()
    await store.delete(key)
    await store.flush()
  }
}

4. 创建类型 typs/SplashScreen.ets

javascript 复制代码
export interface ISplashScreen {
  show: boolean
  duration: number
  image: string | Resource
}

5. 修改 EntryAbility

  • 修改 EntryAbility.ts 后缀为 EntryAbility.ets
  • 创建 userStore
  • 模拟获取闪屏数据
  • 从 userStore 获取闪屏数据
  • 加载首页或者闪屏页
javascript 复制代码
  async onWindowStageCreate(windowStage: window.WindowStage) {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    // 用户仓库
    const userStore = new StoreUtil(this.context, "userStore",)
    // 模拟获取闪屏数据
    await new Promise(resolve => {
      setTimeout(async () => {
        const splashScreen: ISplashScreen = {
          show: true,
          duration: 10,
          image: $r("app.media.splash_screen")
        }
        await userStore.setData("userSplashScreen", splashScreen)
        resolve(splashScreen)
      }, 2000)
    })
    // 从仓库获取闪屏数据
    const splashScreen = await userStore.getData<ISplashScreen>("userSplashScreen")
    if (splashScreen.show) {
      // 加载闪屏页面
      windowStage.loadContent('pages/SplashScreen', (err, data) => {
        if (err.code) {
          hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
          return;
        }
        hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
      });
    } else {
      // 加载首页
      windowStage.loadContent('pages/Index', (err, data) => {
        if (err.code) {
          hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
          return;
        }
        hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
      });
    }
  }

6. 修改闪屏页面

修改 SplashScreen.ets

javascript 复制代码
import router from '@ohos.router'
import { ISplashScreen } from '../types/SplashScreen'
import { StoreUtil } from '../utils/StoreUtil'

@Entry
@Component
struct SplashScreen {
  @State timer: number = -1
  @State splashScreenObj: ISplashScreen = { show: true, duration: 10, image: '' }
  userStore: StoreUtil = new StoreUtil(getContext(this), 'userStore')

  aboutToAppear() {
    this.getData()
  }

  aboutToDisappear() {
    clearInterval(this.timer)
  }

  async getData() {
    // 获取闪屏数据
    const data = await this.userStore.getData<ISplashScreen>('userSplashScreen')
    this.splashScreenObj.duration = data?.duration ?? 10
    this.splashScreenObj.image = data?.image ?? $r('app.media.splash_screen')
    // 倒计时
    this.timer = setInterval(() => {
      if (this.splashScreenObj.duration === 0) {
        clearInterval(this.timer)
        router.replaceUrl({ url: 'pages/Index' })
        return
      }
      this.splashScreenObj.duration--
    }, 1000)
  }

  build() {
    Stack({ alignContent: Alignment.TopEnd }) {
      Image(this.splashScreenObj.image)
        .width('100%')
        .height('100%')

      Row() {
        Text(`${this.splashScreenObj.duration}秒后跳过`)
          .padding({ left: 10, right: 10 })
          .margin({ right: 20, top: 20 })
          .height(30)
          .fontSize(14)
          .borderRadius(15)
          .backgroundColor("#ccc")
          .textAlign(TextAlign.Center)

        Text(`跳过`)
          .padding({ left: 10, right: 10 })
          .margin({ right: 20, top: 20 })
          .height(30)
          .fontSize(14)
          .borderRadius(15)
          .backgroundColor("#ccc")
          .textAlign(TextAlign.Center)
          .onClick(() => {
            router.replaceUrl({ url: 'pages/Index' })
          })
      }
    }
    .width('100%')
    .height('100%')
  }
}
相关推荐
鑫不想说话1064762 小时前
ts+vue3出乎意料的推导报错
vue.js·typescript
冉冉同学2 小时前
【HarmonyOS NEXT】解决微信浏览器无法唤起APP的问题
android·前端·harmonyos
别说我什么都不会2 小时前
【仓颉三方库】 数据库驱动——kv4cj
harmonyos
进击的圆儿4 小时前
鸿蒙应用(医院诊疗系统)开发篇2·Axios网络请求封装全流程解析
华为·harmonyos
鸿蒙布道师4 小时前
鸿蒙NEXT开发文件预览工具类(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
鸿蒙布道师4 小时前
鸿蒙NEXT开发全局上下文管理类(ArkTs)
android·ios·华为·harmonyos·arkts·鸿蒙系统·huawei
梦想不只是梦与想4 小时前
鸿蒙系统开发状态更新字段区别对比
android·java·flutter·web·鸿蒙
RxnNing8 小时前
http、https、TLS、证书原理理解,对称加密到非对称加密问题,以及对应的大致流程
前端·网络协议·学习·http·https·typescript
博睿谷IT99_8 小时前
华为HCIE-openEuler认证:能否成为国产操作系统领域的技术稀缺人才?
华为·开源·操作系统·华为认证·hcie·openeuler
宇宙的有趣9 小时前
当 TypeScript 类型嵌套超过了 100 层
前端·typescript