温馨提示:本篇博客的详细代码已发布到 git : https://gitcode.com/nutpi/HarmonyosNext 可以下载运行哦!
本文将详细解析一个基于 HarmonyOS Next API 12 实现的高性能列表渲染示例。该示例展示了如何通过合理的代码组织和多种优化技巧来提升列表性能。主要包含以下几个核心部分:
案例运行效果如下
class ArrayDataSource implements IDataSource {
private dataArray: ItemData[];
constructor(data: ItemData[]) {
this.dataArray = data;
}
totalCount(): number {
return this.dataArray.length;
}
getData(index: number): ItemData {
return this.dataArray[index];
}
registerDataChangeListener(listener: DataChangeListener): void {
// 简单实现可暂不处理
}
unregisterDataChangeListener(listener: DataChangeListener): void {
// 简单实现可暂不处理
}
}
性能优化要点:
interface ItemData {
id: number
title: string
description: string
avatar: string
type: 'simple' | 'badge'
unreadCount?: number
}
优化考虑:
@Component
struct OptimizedListItem {
@Prop item: ItemData
@Builder
ItemContent() {
Row() {
Image(this.item.avatar)
.width(40)
.height(40)
.margin({ right: 10 })
Column() {
Text(this.item.title)
.fontSize(16)
.fontWeight(FontWeight.Medium)
Text(this.item.description)
.fontSize(14)
.opacity(0.6)
}
.alignItems(HorizontalAlign.Start)
}
.width('100%')
.padding(10)
.backgroundColor('#F5F5F5')
.border({
width: 1,
color: '#E0E0E0',
style: BorderStyle.Solid
})
}
build() {
if (this.item.type === 'simple') {
this.ItemContent()
} else {
Stack() {
this.ItemContent()
Badge({
value: this.item.unreadCount+'',
position: BadgePosition.RightTop,
style: { badgeSize: 16, badgeColor: '#FA2A2D' }
}) {
Text('').width(40).height(40)
}
}
}
}
}
性能优化策略:
@Entry
@Component
struct ListDemo {
@State dataList: ItemData[] = [
{
id: 1,
title: '消息通知',
description: '您有一条新的系统通知',
avatar: '/assets/userPhone.JPG',
type: 'badge',
unreadCount: 3
},
{
id: 2,
title: '系统更新',
description: '系统有新版本可用',
avatar: '/assets/userPhone.JPG',
type: 'simple'
}
]
build() {
List() {
LazyForEach(new ArrayDataSource(this.dataList), (item: ItemData) => {
ListItem() {
OptimizedListItem({ item: item })
}
.onClick(() => {
console.info(`Clicked item: ${item.title}`)
})
}, (item: ItemData) => item.id.toString())
}
.width('100%')
.height('100%')
}
}
核心优化策略: