这段时间一直学习华为自主研发的鸿蒙OS Next
全场景操作系统。花了一个月捣鼓了一款HarmonyOS聊天App项目。
harmonyos-chat原创自研鸿蒙os聊天系统,包括聊天、通讯录、我、朋友圈等模块,实现类似微信消息UI布局结构。
基于HarmonyOSArkTs
和ArkUI
实现下拉刷新、长按/下拉菜单、自定义弹窗、朋友圈等功能。
采用DevEco Studio 5.0.3.906
编辑器构建项目模板。
想快速的入门进阶开发,先把官方文档撸一遍,然后找个实战项目案例再撸一遍。
// 自定义页面
@Builder customPage() {
if(this.pageIndex === 0) {
IndexPage()
}else if(this.pageIndex === 1) {
FriendPage()
}else if(this.pageIndex === 2) {
MyPage()
}
}
build() {
Navigation() {
this.customPage()
}
.toolbarConfiguration(this.customToolBar)
.height('100%')
.width('100%')
.backgroundColor($r('sys.color.background_secondary'))
.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
}
// 自定义底部菜单栏
@Builder customToolBar() {
Row() {
Row() {
Badge({
count: 8,
style: {},
position: BadgePosition.RightTop
}) {
Column({space: 2}) {
SymbolGlyph($r('sys.symbol.ellipsis_message_fill'))
Text('聊天').fontSize(12)
}
}
}
.layoutWeight(1)
.justifyContent(FlexAlign.Center)
.onClick(() => {
this.pageIndex = 0
})
Row() {
Column({space: 2}) {
SymbolGlyph($r('sys.symbol.person_2'))
Text('通讯录').fontSize(12)
}
}
.layoutWeight(1)
.justifyContent(FlexAlign.Center)
.onClick(() => {
this.pageIndex = 1
})
Row() {
Badge({
value: '',
style: { badgeSize: 8, badgeColor: '#fa2a2d' }
}) {
Column({space: 2}) {
SymbolGlyph($r('sys.symbol.person_crop_circle_fill_1'))
Text('我').fontSize(12)
}
}
}
.layoutWeight(1)
.justifyContent(FlexAlign.Center)
.onClick(() => {
this.pageIndex = 2
})
}
.height(56)
.width('100%')
.backgroundColor($r('sys.color.background_secondary'))
.borderWidth({top: 1})
.borderColor($r('sys.color.background_tertiary'))
}
/**
* 登录模板
* @author andy
*/
import { router, promptAction } from '@kit.ArkUI'
@Entry
@Component
struct Login {
@State name: string = ''
@State pwd: string = ''
// 提交
handleSubmit() {
if(this.name === '' || this.pwd === '') {
promptAction.showToast({ message: '账号或密码不能为空' })
}else {
// 登录接口逻辑...
promptAction.showToast({ message: '登录成功' })
setTimeout(() => {
router.replaceUrl({ url: 'pages/Index' })
}, 2000)
}
}
build() {
Column() {
Column({space: 10}) {
Image('pages/assets/images/logo.png').height(50).width(50)
Text('HarmonyOS-Chat').fontSize(18).fontColor('#0a59f7')
}
.margin({top: 50})
Column({space: 15}) {
TextInput({placeholder: '请输入账号'})
.onChange((value) => {
this.name = value
})
TextInput({placeholder: '请输入密码'}).type(InputType.Password)
.onChange((value) => {
this.pwd = value
})
Button('登录').height(45).width('100%')
.linearGradient({ angle: 135, colors: [['#0a59f7', 0.1], ['#07c160', 1]] })
.onClick(() => {
this.handleSubmit()
})
}
.margin({top: 30})
.width('80%')
Row({space: 15}) {
Text('忘记密码').fontSize(14).opacity(0.5)
Text('注册账号').fontSize(14).opacity(0.5)
.onClick(() => {
router.pushUrl({url: 'pages/views/auth/Register'})
})
}
.margin({top: 20})
}
.height('100%')
.width('100%')
.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
}
}
Stack({alignContent: Alignment.End}) {
TextInput({placeholder: '验证码'})
.onChange((value) => {
this.code = value
})
Button(`${this.codeText}`).enabled(!this.disabled).controlSize(ControlSize.SMALL).margin({right: 5})
.onClick(() => {
this.handleVCode()
})
}
// 验证码参数
@State codeText: string = '获取验证码'
@State disabled: boolean = false
@State time: number = 60
// 获取验证码
handleVCode() {
if(this.tel === '') {
promptAction.showToast({ message: '请输入手机号' })
}else if(!checkMobile(this.tel)) {
promptAction.showToast({ message: '手机号格式错误' })
}else {
const timer = setInterval(() => {
if(this.time > 0) {
this.disabled = true
this.codeText = `获取验证码(${this.time--})`
}else {
clearInterval(timer)
this.codeText = '获取验证码'
this.time = 5
this.disabled = false
}
}, 1000)
}
}
Refresh({
refreshing: $$this.isRefreshing,
builder: this.customRefreshTips
}) {
List() {
ForEach(this.queryData, (item: RecordArray) => {
ListItem() {
// ...
}
.stateStyles({pressed: this.pressedStyles, normal: this.normalStyles})
.bindContextMenu(this.customCtxMenu, ResponseType.LongPress)
.onClick(() => {
// ...
})
}, (item: RecordArray) => item.cid.toString())
}
.height('100%')
.width('100%')
.backgroundColor('#fff')
.divider({ strokeWidth: 1, color: '#f5f5f5', startMargin: 70, endMargin: 0 })
.scrollBar(BarState.Off)
}
.pullToRefresh(true)
.refreshOffset(64)
// 当前刷新状态变更时触发回调
.onStateChange((refreshStatus: RefreshStatus) => {
console.info('Refresh onStatueChange state is ' + refreshStatus)
this.refreshStatus = refreshStatus
})
// 进入刷新状态时触发回调
.onRefreshing(() => {
console.log('onRefreshing...')
setTimeout(() => {
this.isRefreshing = false
}, 2000)
})
@State isRefreshing: boolean = false
@State refreshStatus: number = 1
// 自定义刷新tips
@Builder customRefreshTips() {
Stack() {
Row() {
if(this.refreshStatus == 1) {
SymbolGlyph($r('sys.symbol.arrow_down')).fontSize(24)
}else if(this.refreshStatus == 2) {
SymbolGlyph($r('sys.symbol.arrow_up')).fontSize(24)
}else if(this.refreshStatus == 3) {
LoadingProgress().height(24)
}else if(this.refreshStatus == 4) {
SymbolGlyph($r('sys.symbol.checkmark')).fontSize(24)
}
Text(`${
this.refreshStatus == 1 ? '下拉刷新' :
this.refreshStatus == 2 ? '释放更新' :
this.refreshStatus == 3 ? '加载中...' :
this.refreshStatus == 4 ? '完成' : ''
}`).fontSize(16).margin({left:10})
}
.alignItems(VerticalAlign.Center)
}
.align(Alignment.Center)
.clip(true)
.constraintSize({minHeight:32})
.width('100%')
}
.bindContextMenu(this.customCtxMenu, ResponseType.LongPress)
// 自定义长按右键菜单
@Builder customCtxMenu() {
Menu() {
MenuItem({
content: '标为已读'
})
MenuItem({
content: '置顶该聊天'
})
MenuItem({
content: '不显示该聊天'
})
MenuItem({
content: '删除'
})
}
}
.bindMenu([ ... ])
Image($r('app.media.plus')).height(24).width(24)
.bindMenu([
{
icon: $r('app.media.message_on_message'),
value:'发起群聊',
action: () => {}
},
{
icon: $r('app.media.person_badge_plus'),
value:'添加朋友',
action: () => router.pushUrl({url: 'pages/views/friends/AddFriend'})
},
{
icon: $r('app.media.line_viewfinder'),
value:'扫一扫',
action: () => {}
},
{
icon: $r('app.media.touched'),
value:'收付款',
action: () => {}
}
])
// 标题(支持字符串|自定义组件)
@BuilderParam title: ResourceStr | CustomBuilder = BuilderFunction
// 内容(字符串或无状态组件内容)
@BuilderParam message: ResourceStr | CustomBuilder = BuilderFunction
// 响应式组件内容(自定义@Builder组件是@State动态内容)
@BuilderParam content: () => void = BuilderFunction
// 弹窗类型(android | ios | actionSheet)
@Prop type: string
// 是否显示关闭图标
@Prop closable: boolean
// 关闭图标颜色
@Prop closeColor: ResourceColor
// 是否自定义内容
@Prop custom: boolean
// 自定义操作按钮
@BuilderParam buttons: Array<ActionItem> | CustomBuilder = BuilderFunction
调用方式如下:
// 自定义退出弹窗
logoutController: CustomDialogController = new CustomDialogController({
builder: HMPopup({
type: 'android',
title: '提示',
message: '确定要退出当前登录吗?',
buttons: [
{
text: '取消',
color: '#999'
},
{
text: '退出',
color: '#fa2a2d',
action: () => {
router.replaceUrl({url: 'pages/views/auth/Login'})
}
}
]
}),
maskColor: '#99000000',
cornerRadius: 12,
width: '75%'
})
整个HarmonyOS聊天项目涉及到的知识点非常多,进今就先分享到这里。希望对大家有所帮助。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。