#跟着若城学鸿蒙# HarmonyOS NEXT学习之LoadingProgress案例四:路由加载效果实现
·
一、案例介绍
本案例将展示如何在页面路由切换过程中使用LoadingProgress组件实现加载效果。通过在页面切换时显示加载动画,为用户提供更好的过渡体验,提升应用的整体交互质量。
二、实现效果
- 页面切换时显示加载动画
- 数据准备完成后平滑过渡
- 加载超时自动处理
- 错误状态优雅降级
三、代码实现
1. 路由管理器
class RouterManager {
private static instance: RouterManager;
private loadingCallback: (loading: boolean) => void;
private constructor() {}
static getInstance(): RouterManager {
if (!RouterManager.instance) {
RouterManager.instance = new RouterManager();
}
return RouterManager.instance;
}
setLoadingCallback(callback: (loading: boolean) => void) {
this.loadingCallback = callback;
}
async navigateTo(options: {
url: string,
params?: object
}) {
try {
this.loadingCallback?.(true);
await this.preloadPageData(options.url, options.params);
router.pushUrl(options);
} catch (error) {
this.handleError(error);
} finally {
this.loadingCallback?.(false);
}
}
private preloadPageData(url: string, params?: object): Promise<void> {
// 模拟页面数据预加载
return new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.1) {
resolve();
} else {
reject(new Error('加载失败'));
}
}, 1000);
});
}
private handleError(error: Error) {
AlertDialog.show({
title: '错误',
message: error.message || '页面加载失败',
confirm: {
value: '确定',
action: () => {
AlertDialog.hide();
}
}
});
}
}
2. 加载遮罩组件
@Component
struct LoadingOverlay {
@Prop isLoading: boolean;
build() {
Stack() {
if (this.isLoading) {
Column() {
LoadingProgress()
.width(48)
.height(48)
.color('#2196F3')
Text('加载中...')
.fontSize(14)
.fontColor('#666666')
.margin({ top: 12 })
}
.width('100%')
.height('100%')
.backgroundColor('rgba(255, 255, 255, 0.9)')
.justifyContent(FlexAlign.Center)
}
}
.width('100%')
.height('100%')
}
}
3. 主页面实现
@Entry
@Component
struct MainPage {
@State isLoading: boolean = false;
private routerManager: RouterManager = RouterManager.getInstance();
aboutToAppear() {
this.routerManager.setLoadingCallback((loading: boolean) => {
this.isLoading = loading;
});
}
build() {
Stack() {
Column() {
this.PageContent()
}
.width('100%')
.height('100%')
LoadingOverlay({ isLoading: this.isLoading })
}
.width('100%')
.height('100%')
}
@Builder
PageContent() {
Column() {
Button('跳转到页面A')
.width('100%')
.margin({ bottom: 16 })
.onClick(() => {
this.routerManager.navigateTo({
url: 'pages/PageA',
params: { id: 1 }
});
})
Button('跳转到页面B')
.width('100%')
.margin({ bottom: 16 })
.onClick(() => {
this.routerManager.navigateTo({
url: 'pages/PageB',
params: { id: 2 }
});
})
Button('跳转到页面C')
.width('100%')
.onClick(() => {
this.routerManager.navigateTo({
url: 'pages/PageC',
params: { id: 3 }
});
})
}
.width('100%')
.padding(16)
}
}
四、总结
本案例通过在页面路由切换过程中使用 LoadingProgress
组件,实现了加载动画的显示,为用户提供了平滑的过渡体验。通过路由管理器统一处理页面加载状态,并结合加载遮罩组件,实现了数据准备、加载超时和错误处理等功能。这种实现方式适用于需要提升页面切换流畅性和用户体验的场景,能够有效改善应用的整体交互质量。
更多推荐
所有评论(0)