一、功能简介
本篇将模拟一个 AI 问答助手对话界面,支持用户提问后助手“节奏响应”、滑入式对话气泡展示,常用于 ChatBot 界面、AI助手、语义搜索等场景。
二、关键技术点
能力 | 实现方式 |
---|---|
对话气泡滑入 | .translateY() + .opacity() + .animate() |
节奏控制 | setTimeout() 控制回答延迟与节奏感 |
多轮问答 | 使用数组追加问答记录,支持多轮互动 |
结构区分 | 用户问题靠右,AI回答靠左,区分身份与结构 |
三、页面结构
entry/src/main/ets/pages/AIQAFlowSlideDemo.ets
四、ArkTS 实战代码(AIQAFlowSlideDemo.ets)
@Entry
@Component
struct AIQAFlowSlideDemo {
@State qaList: { from: 'user' | 'ai'; text: string }[] = []
@State inputText: string = ''
@State animateIndexes: number[] = []
handleAsk() {
if (!this.inputText.trim()) return
const question = this.inputText.trim()
this.inputText = ''
// 添加用户问题
this.qaList.push({ from: 'user', text: question })
// 模拟 AI 回答延迟
setTimeout(() => {
const answer = '这是 AI 回答:' + question
const index = this.qaList.length
this.qaList.push({ from: 'ai', text: answer })
setTimeout(() => this.animateIndexes.push(index), 50)
}, 600)
}
buildMessageItem(item: { from: string; text: string }, i: number): void {
const isAI = item.from === 'ai'
const isAnimated = this.animateIndexes.includes(i)
Row() {
If(isAI, () => {
Image($r('app.media.ai_avatar'))
.width(32).height(32).borderRadius(16).margin({ right: 8 })
})
Text(item.text)
.fontSize(15)
.padding(10)
.borderRadius(10)
.maxWidth('70%')
.backgroundColor(isAI ? '#f1f1f1' : '#007DFF')
.fontColor(isAI ? '#000' : '#fff')
If(!isAI, () => {
Image($r('app.media.user_avatar'))
.width(32).height(32).borderRadius(16).margin({ left: 8 })
})
}
.justifyContent(isAI ? FlexAlign.Start : FlexAlign.End)
.translate({ y: isAnimated ? 0 : 20 })
.opacity(isAnimated ? 1 : 0)
.animate({ duration: 300 })
.margin({ bottom: 12 })
}
build() {
Column() {
Text('HarmonyOS 5.0.0 或以上')
.fontSize(20).margin({ bottom: 16 })
Column() {
ForEach(this.qaList, (item, i) => this.buildMessageItem(item, i), (_, i) => i)
}
.margin({ bottom: 16 })
// 输入框
Row() {
TextInput({ placeholder: '请输入你的问题', text: this.inputText, onChange: v => this.inputText = v })
.border('1px solid #ccc').height(42).padding(8).borderRadius(8).width('80%')
Button('发送').margin({ left: 8 }).onClick(() => this.handleAsk())
}
}
.padding(20)
.backgroundColor('#f6f6f6')
.width('100%').height('100%')
}
}
五、运行效果说明
-
用户输入问题点击发送;
-
问题立即展示在右侧对话气泡中;
-
AI 回答在 600ms 后自动添加,并以滑入动效渐现;
-
多轮问答自动记录,体验自然流畅。
六、常见问题与优化建议
问题 | 原因 | 建议 |
---|---|---|
回答无动效 | 未将 index 加入 animateIndexes | 回答添加后 setTimeout 添加索引触发动画 |
滑动突兀 | 只加 .opacity() | 建议配合 translateY 实现自然滑入感 |
回答时间不合理 | AI延迟过长或太短 | 建议 300~800ms 为模拟节奏感最佳时间窗 |
七、拓展建议
-
接入真实 LLM 接口进行回答;
-
支持语音输入 + 语音播放;
-
滑入可改为“打字式打印”动画(参考第20篇);
-
封装为
<QAChatBox />
支持场景内嵌; -
加入消息时间戳、滚动到底、加载历史记录等特性。
下一篇为第34篇:
《HarmonyOS 5.0.0 或以上:实现弹窗组合动画与多步骤表单流程指引》