在本篇博客中,介绍一个仿微信的 HarmonyOS 应用,应用包括微信的首页、通讯录、发现、我的页面,以及聊天界面。
一、先上效果图:
二、代码解读
以聊天界面为例,代码如下(解读在代码下面):
import {Title} from '../model/CommonStyle'
import router from '@ohos.router'@Entry
@Component// 定义聊天详情页面的结构
export struct ChatDetailPage {// 用户头像private userAvatar: string = router.getParams()['userAvatar'] as string// 用户名private userName: string = router.getParams()['userName'] as string// 聊天详情private chatDetail: string = router.getParams()['chatDetail'] as string// 构建方法build() {Column() {// 标题Title({ text: this.userName })// 左侧消息气泡LeftMsgBubble({ imageSrc: this.userAvatar, text: "今天天气真好,想不想一起去户外活动?" })// 右侧消息气泡RightMsgBubble({ imageSrc: "user20.webp", text: "当然想啊,你打算去哪里?" })// 左侧消息气泡LeftMsgBubble({ imageSrc: this.userAvatar, text: "我想去公园,逛逛花花草草,你觉得怎么样?" })// 右侧消息气泡RightMsgBubble({ imageSrc: "user20.webp", text: "好主意!我也喜欢大自然的感觉。" })// 右侧消息气泡RightMsgBubble({ imageSrc: "user20.webp", text: "我们可以带上飞盘或者羽毛球,一起玩玩怎么样?" })// 左侧消息气泡LeftMsgBubble({ imageSrc: this.userAvatar, text: "太棒了,我会准备一些小吃,我们一起享受阳光吧!" })}.height("100%")}
}// 左侧消息气泡组件
@Component
struct LeftMsgBubble {private imageSrc: stringprivate text: string// 构建方法build() {Row() {// 用户头像Image($rawfile(this.imageSrc)).width('120px').height('120px').margin({ left: '10px', right: '10px' })// 文本消息Text(this.text).fontSize('14fp').backgroundColor("#cccccc").padding(10).borderRadius(10).margin({ right: '280px' })}.width('100%').margin({ top: '20px', bottom: '20px' }).alignItems(VerticalAlign.Top)}
}// 右侧消息气泡组件
@Component
struct RightMsgBubble {private imageSrc: stringprivate text: string// 构建方法build() {Flex({ direction: FlexDirection.RowReverse }) {// 用户头像Image($rawfile(this.imageSrc)).width('120px').height('120px').margin({ left: '10px', right: '10px' }).objectFit(ImageFit.Contain)Flex({ direction: FlexDirection.RowReverse, justifyContent: FlexAlign.Start }) {// 文本消息Text(this.text).fontSize('14fp').backgroundColor("#1dde40").padding(10).borderRadius(10).margin({ left: '140px' })}}.margin({ top: '20px', bottom: '20px' })}
}
这段代是使用ArkTS语言 来构建聊天详情页面的 UI 组件。以下是对代码的简要解释:
- ChatDetailPage 结构体:
- userAvatar、userName、chatDetail 是私有成员变量,通过路由获取用户头像、用户名和聊天详情。
- build 方法定义了页面的结构,包括标题和一系列的消息气泡。
- LeftMsgBubble 和 RightMsgBubble 组件:
- 这两个组件分别表示左侧和右侧的消息气泡。
- imageSrc 存储用户头像的路径,text 存储消息文本。
- build 方法定义了每个消息气泡的结构,包括图片和文本。左侧消息气泡的背景色为灰色,右侧消息气泡的背景色为绿色。
- Flex 和 Column:
- Flex 和 Column 是布局相关的组件,用于定义灵活的盒状模型,方便构建响应式的用户界面。
- Image 和 Text 组件:
- Image 和 Text 组件用于显示图片和文本内容。
- 通过 $rawfile 函数获取图片资源。
- 样式设置:
- 通过方法链式调用设置了消息气泡的样式,包括大小、边距、背景色、文本大小等。
- Flex 相关属性:
- 使用了 FlexDirection、FlexAlign 等属性,通过这些属性设置了消息气泡的布局方式。
- 组件嵌套:
- 左右两侧的消息气泡组件被嵌套在 Column 和 Flex 中,形成了聊天页面的布局。
三、项目地址
完整项目代码:
OurChat: HarmonyOS ArkUI的仿微信界面