鸿蒙倒计时界面实现并且跳转
·
效果如下:

实现代码如下,下面具体我都写了注释
import { router, window } from '@kit.ArkUI';
import { BusinessError } from '@kit.BasicServicesKit';
import { LogUtil } from '../../utils/logutil';
@Component
@Entry
struct Splash {
timeId?: number; // 定时器
@State num: number = 5; // 倒计时
build() {
Stack() {
// 背景图片
Image($r('app.media.splash_bg'))
.size({ width: '100%', height: '100%' })
.zIndex(-1); // 确保背景图片在最底层
Column() {
// 最右边显示
Button('立即体验' + this.num)
.width('30%')
.height('6%')
.fontSize('16fp')
.margin({ top: '10%', right: '3%' })
.alignSelf(ItemAlign.End) // 对齐到右侧
.onClick(() => {
LogUtil.info('点击立即体验');
this.clearTimerAndNavigate();
});
}.size({ width: '100%', height: '100%' });
}.size({ width: '100%', height: '100%' });
}
/**
* 页面显示时,开始倒计时
*/
onPageShow() {
this.setImmersive();
this.countDown();
LogUtil.info('开始倒计时了');
}
/**
* 沉浸式状态栏
*/
private setImmersive() {
window.getLastWindow(getContext()).then(win => {
win.setWindowLayoutFullScreen(true);
let area = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
let height = area.topRect.height;
let vpheight = px2vp(height);
AppStorage.setOrCreate('topHeight', vpheight);
win.setWindowSystemBarProperties({ statusBarContentColor: '#ffffff' }); // 设置状态栏字体颜色
});
}
/**
* 把倒计时封装方法
*/
private countDown() {
let timeId = setInterval(() => {
this.num--;
if (this.num === 0) {
clearInterval(this.timeId);
LogUtil.info('倒计时结束');
this.navigateToNextPage(); // 跳转到下一页
}
}, 1000);
this.timeId = timeId;
}
/**
* 清除定时器并跳转下一页
*/
private clearTimerAndNavigate() {
clearInterval(this.timeId);
this.navigateToNextPage();
}
/**
* 跳转下一页
*/
private navigateToNextPage() {
router.pushUrl({ url: 'pages/login/Login' }).then(() => {
console.info('成功跳转到第二页。');
}).catch((err: BusinessError) => {
console.error(`无法跳转到第二页。错误码为${err.code}, 错误消息 ${err.message}`);
});
}
/**
* 页面销毁时,清除定时器
*/
onDestroy() {
this.num = 5;
clearInterval(this.timeId);
LogUtil.info('清除定时器');
}
}
更多推荐
所有评论(0)