鸿蒙 ArkTS 中实现全局加载提示功能,可以通过以下方式:
- 创建一个全局状态管理器:管理加载状态。
- 设计一个加载组件:用来显示或隐藏加载提示。
- 在需要显示加载提示的场景中切换加载状态。
以下是实现全局加载提示的完整代码示例:
示例代码
1. 创建全局状态管理器
我们可以使用一个单例模式来存储全局的加载状态。
// globalState.ts
export class GlobalState {
private static instance: GlobalState;
isLoading: boolean = false; // 控制加载提示的状态
private constructor() {}
static getInstance(): GlobalState {
if (!GlobalState.instance) {
GlobalState.instance = new GlobalState();
}
return GlobalState.instance;
}
}
export const globalState = GlobalState.getInstance();
2. 创建加载提示组件
// LoadingComponent.ets
@Component
export struct LoadingComponent {
build() {
const state = globalState;
// 根据加载状态显示/隐藏加载提示
return state.isLoading
? Column {
// 背景遮罩
Rectangle {
width: 'match_parent'
height: 'match_parent'
backgroundColor: 'rgba(0, 0, 0, 0.5)'
alignment: 'center'
// 加载内容
Column {
alignment: 'center',
width: '200px',
height: '200px',
backgroundColor: '#FFFFFF',
borderRadius: 12,
alignmentContent: 'center',
// 加载动画
Image {
src: '/common/loading_spinner.gif' // 替换为实际加载动画
width: '50px'
height: '50px'
}
// 提示文字
Text {
text: '加载中...'
fontSize: 16
marginTop: '10px'
color: '#666666'
}
}
}
}
: null;
}
}
3. 在应用主页面中使用加载组件
在根页面中添加加载组件,并确保加载提示能覆盖整个应用界面。
// App.ets
import { globalState } from './globalState';
import { LoadingComponent } from './LoadingComponent';
@Entry
@Component
struct App {
build() {
return Stack {
// 主页面内容
Column {
// 示例内容
Text {
text: '欢迎来到鸿蒙应用'
fontSize: 20
alignment: 'center'
}
Button {
text: '模拟加载'
onClick: () => {
this.simulateLoading();
}
}
}
// 全局加载提示组件
LoadingComponent {}
};
}
// 模拟加载数据的操作
simulateLoading() {
globalState.isLoading = true; // 显示加载提示
// 模拟网络请求
setTimeout(() => {
globalState.isLoading = false; // 隐藏加载提示
}, 3000); // 3秒后关闭加载提示
}
}
4. 触发加载提示
在需要发起网络请求或执行耗时操作的地方,可以通过设置 globalState.isLoading
来显示或隐藏加载提示。例如:
// 示例:发起网络请求时
import http from '@ohos.net.http';
function fetchData() {
globalState.isLoading = true;
const httpRequest = http.createHttp();
httpRequest.request({
method: 'GET',
url: 'https://example.com/api/data',
header: { 'Content-Type': 'application/json' },
}, (err, data) => {
globalState.isLoading = false; // 请求结束后关闭加载提示
if (err) {
console.error('请求失败:', err);
} else {
console.log('请求成功:', data.result);
}
});
}
代码解析
-
globalState
:- 提供全局共享的加载状态管理。
- 所有需要显示加载提示的页面或组件都可以访问此状态。
-
LoadingComponent
:- 一个通用的加载提示组件。
- 包含遮罩背景、加载动画(可自定义)、提示文字。
-
全局引入:
- 在根页面中引入
LoadingComponent
。 - 通过
globalState.isLoading
控制加载提示的显示或隐藏。
- 在根页面中引入
-
触发时机:
- 在网络请求、文件读取等耗时操作开始时设置
globalState.isLoading = true
。 - 操作结束后设置
globalState.isLoading = false
。
- 在网络请求、文件读取等耗时操作开始时设置