HarmonyOS Next 聊天会话列表组件开发实践(二)

115 阅读1分钟
3. 会话列表展示与交互

使用 ListForEach 展示会话列表,每个会话项使用 ConversationItem 组件,并支持点击跳转和滑动删除。

@Builder
ListComponent(callBack: Function) {
  Flex({ direction: FlexDirection.Column }) {
    HomeTopSearch({ title: HomeConstants.CONVERSATION_TITLE })
      .height(new BreakPointType({
        sm: '11%',
        md: '11%',
        lg: '10%'
      }).getValue(this.currentBreakpoint))
    List() {
      ForEach(this.conversations, (item: ConversationDataInterface, index: number) => {
        ListItem() {
          ConversationItem(item)
            .onClick(() => {
              const name = getContext(this).resourceManager.getStringSync(item.name.id)
              callBack(name)
              this.currentIndex = index;
            })
            .backgroundColor(this.currentIndex === index ? $r('app.color.conversation_clicked_bg_color') : Color.White)
        }
        .height(new BreakPointType({
          sm: '11%',
          md: '11%',
          lg: '10%'
        }).getValue(this.currentBreakpoint))
        .swipeAction({ end: this.ItemDelete(item) })
      }, (item: ConversationDataInterface, index: number) => index + JSON.stringify(item))
    }
    .padding({
      bottom: deviceInfo.deviceType !== StyleConstants.DEVICE_2IN1 &&
        this.currentBreakpoint === BreakpointConstants.BREAKPOINT_LG ?
      $r('app.float.tab_content_pb') : $r('app.float.zero')
    })
    .width(StyleConstants.FULL_WIDTH)
    .height(StyleConstants.FULL_HEIGHT)
  }
  .padding({top: AppStorage.get<string>('topAvoid') || 0})
  .height(StyleConstants.FULL_HEIGHT)
  .width(StyleConstants.FULL_WIDTH)
}
4. 会话删除功能实现

通过 swipeAction 实现滑动删除会话的功能,点击删除按钮时从会话列表中移除相应的会话。

@Builder
ItemDelete(data: ConversationDataInterface) {
  Flex({
    direction: FlexDirection.Column,
    justifyContent: FlexAlign.Center,
    alignItems: ItemAlign.End
  }) {
    Column() {
      Text($r('app.string.delete'))
        .fontSize($r('app.float.small_font_size'))
        .fontColor(Color.White)
    }
    .padding({ right: $r('app.float.vp_twenty') })
  }
  .onClick(() => {
    if (this.conversations.indexOf(data) > -1) {
      this.conversations.splice(this.conversations.indexOf(data), 1)
    }
  })
  .width(80)
  .backgroundColor($r('app.color.focus_color'))
  .margin({ left: -24 })
}

总结

通过上述代码实现,我们在 HarmonyOS Next 中完成了一个聊天会话列表组件的开发。该组件具备响应式布局,能够根据不同的屏幕尺寸展示不同的布局效果。同时,支持会话的展示、点击跳转详情页和滑动删除功能。开发者可以根据实际需求对代码进行扩展和优化,以满足不同应用场景的需求。