自研聊天App鸿蒙Next版|HarmonyOS5.0聊天室|arkts聊天朋友圈

1,336 阅读4分钟

经过一个多月爆肝开发,首款HarmonyOS 5.0重磅新作harmony-chat聊天App正式完结啦。

未标题-7.png

Harmony-Chat是一个基于原生鸿蒙HarmonyOS Next5.0 API12实战开发的聊天APP应用程序,提供了包括聊天、通讯录、我、朋友圈等模块。

p1.gif

版本框架

构建版本:DevEco Studio 5.0.3.906
鸿蒙版本:HarmonyOS 5.0.0 API12 Release SDK
命令行工具:commandline-tools-windows-x64-5.0.3.906

p4.gif

项目框架结构

HarmonyOS-Chat项目的框架结构是基于DevEco Studio 5.0.3.906编辑器构建项目模板。

360截图20241118124214399.png

ArkUI和ArkTS

ArkUI是华为鸿蒙操作系统提供的方舟UI框架,它允许开发者创建丰富的用户界面。ArkTS则是鸿蒙操作系统的一种脚本语言,类似于JavaScript,用于编写ArkUI的应用程序逻辑。

f06d237ca238efb854979b678bac2e8f_1289798-20241119101035867-2063279756.png

p3.gif

想要快速入门到进阶开发HarmonyOS应用的同学,建议先撸一遍上面官方文档,然后找一个实战项目再撸一遍快速练习。鸿蒙官网提供的HarmonyOS开发设计规范和ArkUI方舟UI框架的相关资料,这些都是极佳的开发资源。

p3-2.gif

页面路由JSON文件

1289798-20241119111326298-202389965.png

Harmony ArkUI自定义封装加强版导航条

harmony-chat项目所有顶部导航标题栏都是使用arktsarkui自定义组件实现功能效果。

360截图20241120075707445.png

之前有过一篇文章介绍如何通过arkui实现一个多功能标题栏导航组件,感兴趣的可以去看看下面这篇分享文章。

ffc096406a1fdfa2b1743de6d0217661_1289798-20241119103438252-506834007.png

juejin.cn/post/743180…

鸿蒙Arkui实现登录模板|60s验证码倒计时

p0.gif

/**
 * 登录模板
 * @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])
  }
}

image.png

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()
    })
}

点击获取验证码,开始60s倒计时。

// 验证码参数
@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)
  }
}

鸿蒙arkui实现下拉刷新/九宫格图/长按下拉菜单

00cf7d864fd4985c00ce2972a2daee85_1289798-20241119115109602-1001433050.png

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%')
}

长按聊天消息实现类似微信操作菜单。

53ed82dfd0d8bc4bdfb0d5f84848ac41_1289798-20241119115230213-1785508169.png

.bindContextMenu(this.customCtxMenu, ResponseType.LongPress)

// 自定义长按右键菜单
@Builder customCtxMenu() {
  Menu() {
    MenuItem({
      content: '标为已读'
    })
    MenuItem({
      content: '置顶该聊天'
    })
    MenuItem({
      content: '不显示该聊天'
    })
    MenuItem({
      content: '删除'
    })
  }
}

下拉菜单功能。

40bf4bafa8a5de2cbd5880f81356e67e_1289798-20241119115302037-837203237.png

.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: () => {}
    }
  ])

ArkUI实现自定义弹框功能。

image.png

image.png

003360截图20241118101810742.png

c831af8821f0fd1a261f869c0bb30b2f_1289798-20241119120902286-248268836.png

支持如下参数自定义配置:

// 标题(支持字符串|自定义组件)
@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%'
})

// 自定义组件内容弹窗
@Builder customQRContent() {
  Column({space: 15}) {
    Image('pages/assets/images/qrcode.png').height(150).objectFit(ImageFit.Contain)
    Text('扫一扫,加我公众号').fontSize(14).opacity(.5)
  }
}
qrController: CustomDialogController = new CustomDialogController({
  builder: HMPopup({
    message: this.customQRContent,
    closable: true
  }),
  cornerRadius: 12,
  width: '70%'
})

聊天功能模块

p4-1.gif

聊天区域结构如下:

Stack() {
  /**
   * 聊天主体(消息区/底部操作区)
   */
  Column() {
    /* 导航条 */
    HMNavBar({
      title: 'HarmonyOS Next 5.0',
      bgLinearGradient: { angle: 135, colors: [['#cc07c160', 0.2], ['#cc0a59f7', 1]] },
      fontColor: '#fff',
      actions: [
        {
          icon: $r('sys.symbol.more'),
          action: () => router.pushUrl({url: 'pages/views/chat/GroupInfo'})
        }
      ]
    })

    /* 渲染聊天消息 */
    Scroll(this.scroller) {
      Column({space: 15}) {
        ForEach(this.chatList, (item: ChatArray) => {
          // ...
        }, (item: ChatArray) => item.id)
      }
      // 倒叙显示
      .reverse(true)
      // .padding(15)
      .constraintSize({minHeight: '100%'})
      .width('100%')
    }
    // 聊天区翻转
    .rotate({angle: 180})
    .direction(Direction.Rtl)
    .padding(15)
    .width('100%')
    .layoutWeight(1)
    .scrollBar(BarState.On)
    .edgeEffect(EdgeEffect.Spring)
    .onScrollEdge((side: Edge) => {
      if(side === 0) {
        console.info('To the bottom edge')
      }else if(side === 2) {
        console.info('To the top edge')
      }
    })
    .onTouch(() => {
      this.handleChatAreaTouched()
    })

    /* 底部操作栏 */
    Row() {
      // ....
    }
    .width('100%')
    .backgroundColor('#f8f8f8')
  }
  .height('100%')
  .width('100%')
  .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])

  /**
   * 录音主体(按住说话)
   */
  Column() {
    Stack({alignContent: Alignment.Bottom}) {
      // ...
    }
    .height('100%')
    .width('100%')
  }
  .visibility(this.voicePanelEnable ? Visibility.Visible : Visibility.None)
  .height('100%')
  .width('100%')
  .backgroundColor('#99000000')
  .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
}
.height('100%')
.width('100%')
.backgroundColor($r('sys.color.background_secondary'))
.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])

未标题-5.png

聊天底部操作区域模板。

/* 底部操作栏 */
Row() {
  Column() {
    // 输入框模块
    Row({space: 10}) {
      Row() {
        SymbolGlyph($r('sys.symbol.mic_circle')).fontSize(24)
          .visibility(this.voiceEnable ? Visibility.None : Visibility.Visible)
        SymbolGlyph($r('sys.symbol.keyboard_circle')).fontSize(24)
          .visibility(!this.voiceEnable ? Visibility.None : Visibility.Visible)
      }
      .onClick(() => {
        this.voiceEnable = !this.voiceEnable
        this.footBarEnable = false
      })
      Row() {
        // 编辑器
        RichEditor({controller: this.richEditorController}).backgroundColor('#fff').borderRadius(4).caretColor('#0a59f7')
          .visibility(this.voiceEnable ? Visibility.None : Visibility.Visible)
        // 按住说话
        // 通过item[key]取到值的时候会报错,Indexed access is not supported for fields
        // 解决办法Object(item)[key]
        Text(`${Object(this.voiceTypeMap)[this.voiceType]}`).backgroundColor('#fff').borderRadius(4).fontSize(15).height(34).width('100%').textAlign(TextAlign.Center)
          .visibility(!this.voiceEnable ? Visibility.None : Visibility.Visible)
          .onTouch((event: TouchEvent) => {
            if(event) {
              if(event.type === TouchType.Down) {
                this.voiceType = 1
                this.voicePanelEnable = true
              }
              if(event.type === TouchType.Move) {
                ...

                // 触摸判断
                if(pos.y >= panY) {
                  this.voiceType = 1 // 松开发送
                }else if(pos.y < panY && pos.x < panX) {
                  this.voiceType = 2 // 左滑取消发送
                }else if(pos.y < panY && pos.x >= panX) {
                  this.voiceType = 3 // 右滑语音转文字
                }
              }
              if(event.type === TouchType.Up || event.type === TouchType.Cancel) {
                switch (this.voiceType) {
                  ...
                }
                this.voiceType = 0
              }
            }
          })
      }
      .layoutWeight(1)
      SymbolGlyph($r('sys.symbol.capture_smiles')).fontSize(24)
        .onClick(() => {
          this.handleEmoChooseState(0)
        })
      SymbolGlyph($r('sys.symbol.plus')).fontSize(24)
        .onClick(() => {
          this.handleEmoChooseState(1)
        })
      SymbolGlyph($r('sys.symbol.paperplane')).fontSize(24).fontColor(['#0a59f7'])
        .onClick(() => {
          this.handleSubmit()
        })
    }
    .padding(10)
    .alignItems(VerticalAlign.Center)

    // 表情/选择模块
    Column() {
      if(this.footBarIndex == 0) {
        // 表情区域
        this.renderEmoWidget()
      }else {
        // 选择区域
        this.renderChooseWidget()
      }
    }
    .height(308)
    .width('100%')
    .visibility(this.footBarEnable ? Visibility.Visible : Visibility.None)
  }
}
.width('100%')
.backgroundColor('#f8f8f8')

综上就是HarmonyOS Next 5.0开发聊天app的一些知识分享,希望能带给大家一些些帮助!

juejin.cn/post/741066…

juejin.cn/post/741924…

juejin.cn/post/742565…

a8a5dc63jw1falkc05snfg206q046gli.gif