#跟着晓明学鸿蒙# HarmonyOS联系人列表实现:打造专业的即时通讯界面
·
目录
- 案例介绍
- 代码实现
- 代码详解
- 数据结构设计
- 界面布局实现
- 交互功能实现
- 总结
案例介绍
本篇文章将详细介绍如何在HarmonyOS NEXT中实现一个专业的即时通讯应用中的联系人列表界面。通过合理的数据结构设计和UI组件布局,我们将实现一个包含搜索、联系人展示和未读消息提醒的功能完整的列表界面。
代码实现
@Entry
@Component
struct ChatApp {
// 联系人列表数据结构
@State contacts: Array<{
id: number,
name: string,
avatar: Resource,
lastMessage: string,
time: string,
unread: number
}> = [
{
id: 1,
name: '张三',
avatar: $r('app.media.avatar1'),
lastMessage: '晚上一起吃饭吗?',
time: '14:30',
unread: 2
},
{
id: 2,
name: '李四',
avatar: $r('app.media.avatar2'),
lastMessage: '项目进展如何?',
time: '12:45',
unread: 0
},
{
id: 3,
name: '王五',
avatar: $r('app.media.avatar3'),
lastMessage: '文档已经发送给你了',
time: '昨天',
unread: 1
}
]
// 当前选中的联系人ID
@State currentContact: number = 1
build() {
Column() {
// 搜索框实现
TextInput({ placeholder: '搜索联系人' })
.width('100%')
.height(40)
.backgroundColor('#F5F5F5')
.margin({ top: 10, bottom: 10 })
.padding({ left: 10, right: 10 })
// 联系人列表实现
List() {
ForEach(this.contacts, (contact) => {
ListItem() {
Row() {
// 头像和未读消息徽标
Stack() {
Image(contact.avatar)
.width(40)
.height(40)
.borderRadius(20)
if (contact.unread > 0) {
Badge({
count: contact.unread,
position: BadgePosition.RightTop
}) {}
}
}
// 联系人信息区域
Column() {
Text(contact.name)
.fontSize(16)
Text(contact.lastMessage)
.fontSize(14)
.fontColor('#999')
.margin({ top: 4 })
}
.alignItems(HorizontalAlign.Start)
.margin({ left: 10 })
.layoutWeight(1)
// 时间显示
Text(contact.time)
.fontSize(12)
.fontColor('#999')
}
.width('100%')
.padding(10)
.backgroundColor(this.currentContact === contact.id ? '#F0F0F0' : Color.White)
.onClick(() => {
this.currentContact = contact.id
})
}
})
}
.width('100%')
.layoutWeight(1)
}
.width(280)
.height('100%')
.backgroundColor(Color.White)
}
}
代码详解
数据结构设计
- 联系人数据模型
- 使用@State装饰器定义响应式数据
- 包含id、name、avatar等基本信息
- 添加lastMessage和time表示最新消息
- unread字段记录未读消息数量
界面布局实现
-
搜索框设计
- 使用TextInput组件实现搜索输入
- 设置合适的内外边距和背景色
- 优化视觉效果和交互体验
-
列表项布局
- Row组件实现水平布局
- Stack组件叠加显示头像和未读标记
- Column组件垂直排列联系人信息
- 合理使用layoutWeight分配空间
交互功能实现
-
联系人选择
- 通过onClick事件处理点击
- 更新currentContact状态
- 根据选中状态改变背景色
-
未读消息提醒
- 使用Badge组件显示未读数量
- 条件渲染控制徽标显示
- 自动定位到头像右上角
总结
本篇文章详细介绍了如何实现一个专业的即时通讯应用联系人列表界面:
- 设计了完整的联系人数据结构
- 实现了搜索框和列表的布局
- 添加了未读消息提醒功能
- 优化了列表项的交互体验
更多推荐
所有评论(0)