
回复
作为一个曾被UI卡顿逼到崩溃的开发者,今天要揭秘HarmonyOS的UIAbility组件!第一次用它做界面时,同事以为我用了「魔法」,其实只是掌握了这个构建丝滑界面的神器~
想象一场话剧:
生命周期阶段 | 类比场景 | 典型操作 |
---|---|---|
onCreate | 演员化妆准备 | 初始化界面元素 |
onForeground | 演员上台表演 | 加载数据、申请资源 |
onBackground | 演员退到后台 | 释放资源、保存状态 |
onDestroy | 演员谢幕离场 | 销毁实例、清理内存 |
实战代码(演员的一天):
import { UIAbility } from '@ohos.app.ability';
export default class MainAbility extends UIAbility {
onCreate() {
console.log('演员开始化妆(界面初始化)');
this.setUIContent(); // 搭舞台布景
}
onForeground() {
console.log('演员上台(界面显示)');
this.loadData(); // 开始表演(加载数据)
}
onBackground() {
console.log('演员退后台(界面隐藏)');
this.saveState(); // 记台词(保存状态)
}
onDestroy() {
console.log('演员谢幕(界面销毁)');
this.releaseResources(); // 拆舞台(释放资源)
}
}
// 搭建一个登录界面(类比搭积木)
@Entry
@Component
struct LoginPage {
@State account: string = '';
@State password: string = '';
build() {
Column() { // 竖排布局,像舞台上的背景板
Text('HarmonyOS登录') // 标题,像舞台大字幕
.fontSize(28)
.margin({ top: 50 })
TextInput({ placeholder: '账号' }) // 输入框,像演员的台词本
.width('90%')
.margin({ top: 20 })
.onChange((value) => this.account = value)
TextInput({ placeholder: '密码' })
.width('90%')
.margin({ top: 10 })
.type(InputType.Password)
.onChange((value) => this.password = value)
Button('登录') // 按钮,像演员的关键动作
.width('60%')
.margin({ top: 30 })
.onClick(() => this.login())
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
}
login() {
console.log(`账号:${this.account},密码:${this.password}`);
}
}
容器组件 | 布局效果 | 生活类比 |
---|---|---|
Column | 竖排排列 | 剧院座位竖排 |
Row | 横排排列 | 舞台道具横放 |
Stack | 层叠排列 | 舞台布景叠加 |
List | 列表排列 | 剧院座位列表 |
@Entry
@Component
struct DataBindingDemo {
@State count: number = 0; // 数据像木偶的线
build() {
Column() {
Text(`点击次数:${this.count}`) // 界面像木偶,数据动它就动
.fontSize(24)
Button('点击我')
.onClick(() => {
this.count++; // 拉线(改数据)
})
}
.padding(20)
}
}
// 父组件(导演)
@Component
struct ParentComponent {
@State message: string = 'Hello';
build() {
Column {
ChildComponent({ message: $message }) // 传线给子组件
Button('改消息')
.onClick(() => this.message = 'World')
}
}
}
// 子组件(演员)
@Component
struct ChildComponent {
@Link message: string; // 接导演的线
build() {
Text(this.message) // 跟着导演的线动
.fontSize(20)
}
}
@Entry
@Component
struct ClickDemo {
@State isClicked: boolean = false;
build() {
Button(isClicked ? '已点击' : '点击我')
.onClick(() => {
this.isClicked = true;
// 演员听到掌声(点击)后的反应
this.showToast('谢谢点击!');
})
.width(200)
.height(50)
}
showToast(message: string) {
// 显示提示
}
}
@Entry
@Component
struct SwipeDemo {
@State position: number = 0;
build() {
Column {
Text(`位置:${position}`)
.fontSize(24)
Stack() {
Rectangle()
.width(300)
.height(200)
.fill(Color.Blue)
Text('滑动我')
.fontSize(20)
}
.gesture(
PanGesture({ direction: GestureDirection.All })
.onActionUpdate((event) => {
this.position = event.offsetX; // 跟观众挥手方向走
})
)
}
}
}
// 发送方(演员A)
import { getContext } from '@ohos.app.ability';
let eventHub = getContext(this).eventHub;
eventHub.publish('newMessage', '台词已收到'); // 用对讲机发消息
// 接收方(演员B)
eventHub.on('newMessage', (message) => {
console.log(`收到消息:${message}`); // 用对讲机收消息
});
// 存数据(贴公告)
AppStorage.SetOrCreate('userInfo', { name: 'HarmonyOS用户' });
// 取数据(看公告)
let userInfo = AppStorage.Get('userInfo');
console.log(`用户信息:${userInfo.name}`);
export default class FastStartAbility extends UIAbility {
// 预加载资源,像演员提前背台词
async onCreate() {
this.preloadResources(); // 提前加载图片、字体
super.onCreate();
}
preloadResources() {
// 异步加载资源,不阻塞界面
}
}
onBackground() {
// 释放非必要资源,像演员下台收道具
this.clearUnusedComponents();
this.releaseMemoryCache();
}
场景 | 传统开发 | UIAbility开发 |
---|---|---|
界面启动时间 | 800ms | 300ms(快62.5%) |
内存占用 | 25MB | 15MB(少40%) |
滑动流畅度 | 45fps | 60fps(满帧) |
第一次用UIAbility做电商APP时,滑动列表流畅到被老板怀疑「是不是偷偷买了高配手机」~ 其实只是用对了数据绑定和布局优化~