HarmonyOS应用开发-闪屏启动页

news/2025/2/9 1:40:21/

        这是鸿蒙开发者网站的一个应用《溪村小镇》示例代码,把闪屏启动页单拿出来,分析一下代码。

一、先上效果图

这是应用打开时的一个启动页,启动页会根据三个时间段(白天、傍晚、晚上)来分别展示溪村小镇不同的景色。

二、实现方法:

1.在pages页面下新建一个页面命名为“Splash”,Splash页面的代码在下面展示。

2.然后在onWindowStageCreate生命周期中配置启动页入口,可以看到“pages/Splash”为启动页入口:

// EntryAbility.ets
onWindowStageCreate(windowStage: window.WindowStage) {// 设置沉浸式窗口,背景透明const windowBarMag = new WindowBarManager();windowBarMag.immersiveWindow(windowStage, Const.TRANSPARENT_COLOR, true);// 加载启动页内容windowStage.loadContent('pages/Splash', (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) ?? '');});
}
  • WindowBarManager用于管理窗口样式,这里设置了沉浸式窗口,并将背景设为透明。
  • 通过windowStage.loadContent加载启动页的内容,路径为'pages/Splash'。

        启动页会在aboutToAppear生命周期内初始化轮播图片资源及定时任务,会展示5秒溪村的优美风景,用户可以点击右上角的跳过直接进入应用主页,也可以等5秒结束自动进入应用主页;5秒倒计时结束、用户主动点击跳过或启动页面销毁时都会取消定时器任务。

启动页的代码如下,代码分析在下面:

import router from '@ohos.router';
import { CommonConstants as Const } from '../common/constants/CommonConstants';
import { splashImages } from '../viewmodel/SplashModel';@Entry
@Component
struct Splash {private swiperController: SwiperController = new SwiperController();private data: Resource[]@State showSwiper: boolean = false;@State countdown: number = Const.COUNTDOWN;private timer: number = -1;// 在此生命周期内根据当前时间段分配轮播展示的溪村小镇风景图aboutToAppear(): void {let hours = new Date().getHours();if (hours >= Const.MORNING_TIME && hours < Const.EVENING_TIME) {this.data = splashImages.day;} else if (hours >= Const.EVENING_TIME && hours <= Const.NIGHT_TIME) {this.data = splashImages.dusk;} else {this.data = splashImages.night;}// 启动画面展示3秒后 轮播展示溪村小镇风景setTimeout(() => {this.showSwiper = true;this.startTiming();}, Const.SPLASH_DURATION)}// 轮播展示溪村小镇风景倒计时5秒startTiming() {this.timer = setInterval(() => {this.countdown--;if (this.countdown === 0) {this.clearTiming();// 5秒钟后自动跳转到应用首页this.jumpToMainPage();}}, Const.DURATION);}// 清理定时器clearTiming() {if (this.timer !== -1) {clearInterval(this.timer);this.timer = -1;}}// 跳转到应用首页jumpToMainPage() {this.clearTiming();router.replaceUrl({url: 'pages/Index'});}// 页面销毁时清理定时器aboutToDisappear() {this.clearTiming();}build() {Column() {Stack() {// 轮播展示溪村小镇风景if (this.showSwiper) {Swiper(this.swiperController) {ForEach(this.data, (item: Resource) => {Image(item).width(Const.FULL_SIZE).height(Const.FULL_SIZE).objectFit(ImageFit.Cover)})}.loop(true).interval(2 * Const.DURATION).duration(Const.DURATION).autoPlay(true).indicatorStyle({bottom: $r('app.float.100'),color: $r('app.color.swiper_dot_color')}).curve(Curve.Linear).onChange((index: number) => {console.info(index.toString())})// 轮播倒计时,点击可进入应用主页Text() {Span($r('app.string.skip'))Span(`${this.countdown}`)}.onClick(() => this.jumpToMainPage()).fontColor(Color.White).fontSize($r('app.float.12fp')).backgroundColor($r('app.color.swiper_jump_bg_color')).width($r('app.float.63')).height($r('app.float.24')).borderRadius($r('app.float.10')).textAlign(TextAlign.Center).position({x: Const.PERCENTAGE_78,y: $r('app.float.35')})} else { // 应用启动画面Image($r('app.media.splash_bg')).width(Const.FULL_PERCENT).height(Const.FULL_PERCENT)Image($r('app.media.ic_splash')).width($r('app.float.192')).height($r('app.float.192')).offset({y: `-${Const.PERCENTAGE_15}`}).objectFit(ImageFit.Contain)Column() {Text(Const.SPLASH_DES).fontColor(Color.White).fontSize($r('app.float.font_size_24fp')).fontWeight(FontWeight.Medium)Text(Const.SPLASH_WELCOME).fontSize($r('app.float.font_size_16fp')).fontColor(Color.White).margin({top: $r('app.float.5')})}.offset({y: Const.PERCENTAGE_25})}}}.height(Const.FULL_SIZE).width(Const.FULL_SIZE)}
}

让我来对这段代码进行详细的解释:

  1. 导入模块:

    import router from '@ohos.router';
    import { CommonConstants as Const } from '../common/constants/CommonConstants';
    import { splashImages } from '../viewmodel/SplashModel';
    

    这里导入了一些模块和常量,其中 router 模块用于导航,CommonConstants 包含了一些常量,Const是它的别名,在代码中就可以用Const.COUNTDOWN来使用其COUNTDOWN常量了,splashImages 包含了一些溪村小镇风景图的资源。

  2. 组件定义:

    @Entry
    @Component
    struct Splash {
    

    使用 HarmonyOS 提供的注解 @Entry@Component 定义了一个名为 Splash 的组件结构。

  3. 私有变量和状态:

    private swiperController: SwiperController = new SwiperController();
    private data: Resource[];
    @State showSwiper: boolean = false;
    @State countdown: number = Const.COUNTDOWN;
    private timer: number = -1;
    

    在组件结构中定义了一些私有变量和状态,其中包括一个用于控制轮播的 swiperController,一个存储资源的数组 data,以及控制页面状态的变量和计时器。

  4. 生命周期函数 aboutToAppear

    // 在此生命周期内根据当前时间段分配轮播展示的溪村小镇风景图aboutToAppear(): void {//获取当前的时间:几点钟let hours = new Date().getHours();//大于6点并且小于18点,属于白天if (hours >= Const.MORNING_TIME && hours < Const.EVENING_TIME) {this.data = splashImages.day;} else if (hours >= Const.EVENING_TIME && hours <= Const.NIGHT_TIME) {//大于18点小于19点,属于黄昏this.data = splashImages.dusk;} else {//其他时间就是晚上了this.data = splashImages.night;}// 启动画面展示3秒后 轮播展示溪村小镇风景setTimeout(() => {this.showSwiper = true;this.startTiming();}, Const.SPLASH_DURATION)}

    在组件即将显示的生命周期内,根据当前时间段分配溪村小镇风景图,并设置定时器,在一定时间后展示轮播图。

  5. 定时器函数 startTimingclearTiming

    startTiming() {this.timer = setInterval(() => {this.countdown--;if (this.countdown === 0) {this.clearTiming();this.jumpToMainPage();}}, Const.DURATION);}clearTiming() {if (this.timer !== -1) {clearInterval(this.timer);this.timer = -1;}}

    这两个函数用于启动和清理倒计时定时器。

  6. 页面跳转函数 

    jumpToMainPage() {this.clearTiming();router.replaceUrl({url: 'pages/MainPage'});}
    

             使用系统提供的router组件,用于页面跳转到应用首页,并在跳转前清理定时器。其中router.replaceUrl代表用下一个页面代替当前页,当前页会被销毁,进入到下一页之后如果按返回键也是不能返回到启动页的。                                                                                         此外router还有router.pushUrl方法可以保存当前页并跳转到下一页,router.back返回上一页面或指定的页面,router.clear清空页面栈中的所有历史页面,仅保留当前页面作为栈顶页面等方法。

  7. 生命周期函数 aboutToDisappear

    aboutToDisappear() {this.clearTiming();
    }
    

    在组件即将销毁的生命周期内清理定时器。

  8. 页面构建函数 build

    build() { // ... }

    构建页面的函数,使用 HarmonyOS 提供的组件和样式语法构建了页面的布局和样式。

        总体来说,这段代码实现了一个具有定时展示溪村小镇风景的启动画面,包括轮播图、倒计时和页面跳转等功能。在页面的构建函数中使用了 HarmonyOS 提供的组件和样式语法来定义页面的结构和样式。

代码地址:Codelabs: 分享知识与见解,一起探索HarmonyOS的独特魅力。 - Gitee.com


http://www.ppmy.cn/news/1263975.html

相关文章

如何把kubernetes pod中的文件拷贝到宿主机上或者把宿主机上文件拷贝到kubernetes pod中

1. 创建一个 Kubernetes Pod 首先&#xff0c;下面是一个示例Pod的定义文件&#xff08;pod.yaml&#xff09;&#xff1a; cat > nginx.yaml << EOF apiVersion: v1 kind: Pod metadata:name: my-nginx spec:containers:- name: nginximage: nginx EOF kubectl app…

浅谈低代码

低代码开发是近年来迅速崛起的软件开发方法&#xff0c;让编写应用程序变得更快、更简单。有人说它是美味的膳食&#xff0c;让开发过程高效而满足&#xff0c;但也有人质疑它是垃圾食品&#xff0c;缺乏定制性与深度。你认为低代码到底是美以下方向仅供参考。味的膳食还是垃圾…

智能优化算法应用:基于灰狼算法3D无线传感器网络(WSN)覆盖优化 - 附代码

智能优化算法应用&#xff1a;基于灰狼算法3D无线传感器网络(WSN)覆盖优化 - 附代码 文章目录 智能优化算法应用&#xff1a;基于灰狼算法3D无线传感器网络(WSN)覆盖优化 - 附代码1.无线传感网络节点模型2.覆盖数学模型及分析3.灰狼算法4.实验参数设定5.算法结果6.参考文献7.MA…

Hive数据库系列--Hive数据类型/Hive字段类型/Hive类型转换

文章目录 一、Hive数据类型1.1、数值类型1.2、字符类型1.3、日期时间类型1.4、其他类型1.5、集合数据类型1.5.1、Struct举例1.5.2、Array举例1.5.3、Map举例 二、数据类型转换2.1、隐式转换2.2、显示转换 三、字段类型的使用3.1、DECIMAL(precision&#xff0c;scale) 本章主要…

若依框架启动过程中遇到的控制台使用npm i下载相关依赖报错的问题以及前端启动遇到的问题

目录 报错截图问题解决其他问题 npm : 无法将“npm”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写&#xff0c;如果包括路径&#xff0c;请确保路径正确&#xff0c;然后再试一次。问题解决更改环境变量新建系统变量 其他问题 错误解决Error: error:0…

4.8 构建onnx结构模型-Less

前言 构建onnx方式通常有两种&#xff1a; 1、通过代码转换成onnx结构&#xff0c;比如pytorch —> onnx 2、通过onnx 自定义结点&#xff0c;图&#xff0c;生成onnx结构 本文主要是简单学习和使用两种不同onnx结构&#xff0c; 下面以 Less 结点进行分析 方式 方法一&a…

Ubuntu上svn基本使用(gitee提交下载)

目录 环境准备 1. 获取代码到本地 直接获取 获取代码时加入用户名密码 指定版本更新 2. 提交代码 3. 展示代码列表 4. 添加代码文件(目录) 5. 删除gitee仓库中的文件 参考文档链接 环境准备 当前操作系统为Ubuntu22.04LTS gitee 创建仓库时 需要打开svn的支持 sudo…

Springboot项目实现简单的文件服务器,实现文件上传+图片及文件回显

文章目录 写在前面一、配置1、application.properties2、webMvc配置3、查看效果 二、文件上传 写在前面 平常工作中的项目&#xff0c;上传的文件一般都会传到对象存储云服务中。当接手一个小项目&#xff0c;如何自己动手搭建一个文件服务器&#xff0c;实现图片、文件的回显…