HarmonyOS Next 聊天页面底部输入组件开发(一).md

93 阅读1分钟

HarmonyOS Next 聊天页面底部输入组件开发

概述

在 HarmonyOS Next 应用开发里,聊天页面底部输入组件的开发是社交类应用的关键部分。它需要具备文字输入、语音输入以及其他功能的触发能力。下面将介绍如何构建一个具备文字输入、语音输入切换和添加功能触发的聊天页面底部输入组件。

核心代码功能及对应代码段

1. 组件状态管理

使用 @State 装饰器管理组件的状态,包括输入的文字、语音识别引擎、语音识别结果显示、语音录制状态等。

@Component
export struct ConversationDetailBottom {
  @State text: string = ''
  @State asrEngine: speechRecognizer.SpeechRecognitionEngine | undefined = undefined
  @State show: boolean = false
  @State voiceText: string = ''
  @State recordVoice: boolean = false
  // ...
}
2. 界面布局构建

使用 FlexColumn 进行布局,包含语音/文字输入切换按钮、输入框和添加功能按钮。

build() {
  Flex({ alignItems: ItemAlign.Center }) {
    Column() {
      StandardIcon({ icon: this.recordVoice ? $r('app.media.ic_keyboard') : $r('app.media.ic_public_voice') })
    }
    .flexBasis(HomeConstants.FLEX_BASIS_AUTO)
    .padding({
      right: $r('app.float.conversation_detail_bottom_padding'),
      left: $r('app.float.conversation_detail_bottom_padding'),
    })
    .onClick(()=> this.recordVoice = !this.recordVoice)

    Column() {
      if (this.recordVoice) {
        VoiceComponent({onSend: this.onSend.bind(this)})
      } else {
        TextArea({ text: this.text })
          .placeholderColor($r('app.color.text_input_default_color'))
          .caretColor($r('app.color.text_input_default_care_color'))
          .backgroundColor($r('app.color.text_input_default_background_color'))
          .borderRadius(HomeConstants.CONVERSATION_DETAIL_BOTTOM_TEXT_RADIUS)
          .flexGrow(StyleConstants.FLEX_GROW_ONE)
          .padding({ right: $r('app.float.conversation_detail_bottom_text_padding') })
          .backgroundColor(Color.White)
          .enableKeyboardOnFocus(false)
          .enterKeyType(EnterKeyType.Send)
          .onChange((value: string) => {
            this.text = value
          })
          .onSubmit(() => {
            this.onSend(this.text, 0)
            this.text = ''
          })
      }
    }

    Column() {
      StandardIcon({ icon: $r('app.media.ic_public_add_norm') })
    }
    .padding({
      right: $r('app.float.conversation_detail_bottom_padding'),
      left: $r('app.float.conversation_detail_bottom_padding'),
    })
    .onClick(() => {
      this.onOpenAddDlg()
    })
  }
  .width(StyleConstants.FULL_WIDTH)
  .height($r('app.float.conversation_detail_bottom_height'))
}
- ```