HarmonyOS7 软键盘事件实战:onNeedSoftkeyboard 与键盘接续(附完整案例)
前言
软键盘场景有个经典烦恼:输入框正打着字,用户点了旁边的工具按钮,键盘"啪"一下收起,再打字还得重新点输入框。聊天页的表情按钮、表单的清空按钮、笔记应用的加粗按钮,全都会踩中这个交互坑。
onNeedSoftkeyboard(API 24)就是为它准备的:以通用属性的形式挂在按钮上,回调返回一个布尔值------true 键盘保持弹出,false 键盘收起。它只决定键盘的去留,按钮自己的业务逻辑仍然写在 onClick 里,两者配合使用。
本篇做两个软键盘案例:
- 聊天栏的"键盘接续"对照实验:表情按钮绑回调、发送按钮故意不绑,Toggle 开关实时切换返回值;
- 表单的"清空不踢键盘 + requestFocus 跳焦":三行输入框,清空按钮返回
true,"一键跳到手机号"演示跨组件跳焦。
onNeedSoftkeyboard 是 API 24 才引入的能力,老工程要先升级 compileSdkVersion。全部代码在 HarmonyOS 7(API 26)、DevEco Studio 环境验证通过。
官方文档:onNeedSoftkeyboard 属于通用属性,可在华为开发者联盟「HarmonyOS 应用开发 → API 参考(ArkTS)」的「通用属性」章节检索"onNeedSoftkeyboard"条目。文中所有 API 签名与起始版本均与本地 SDK 类型定义核对过。
一、准备工程
新建一个 Empty Ability 工程即可,复用系列工程也行。在 entry/src/main/ets/pages/ 下新建 SoftKeyboardDemo.ets,再把它注册进 entry/src/main/resources/base/profile/main_pages.json:
json
{
"src": [
"pages/Index",
"pages/SoftKeyboardDemo"
]
}
记得把新页面注册进 main_pages.json,不然跳转白屏。
主页放一个入口按钮就够用:
ets
Button('软键盘')
.onClick(() => {
this.getUIContext().getRouter().pushUrl({ url: 'pages/SoftKeyboardDemo' });
})
版本门槛单独强调:onNeedSoftkeyboard 与回调类型 OnNeedSoftkeyboardCallback、KeyboardInfo 都是 API 24 引入,工程的 compileSdkVersion 不低于 API 24 才能编译通过。
二、把对象模型捋清楚
2.1 签名与语义
onNeedSoftkeyboard 以通用属性的形式挂在组件上:
ets
onNeedSoftkeyboard(onNeedSoftkeyboardCallback: OnNeedSoftkeyboardCallback | undefined): T
回调的返回值决定键盘去留,整个过程框架等你的返回值再动手:
#mermaid-svg-GWmeE7cNp4Ste6Jd{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;fill:#333;}@keyframes edge-animation-frame{from{stroke-dashoffset:0;}}@keyframes dash{to{stroke-dashoffset:0;}}#mermaid-svg-GWmeE7cNp4Ste6Jd .edge-animation-slow{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 50s linear infinite;stroke-linecap:round;}#mermaid-svg-GWmeE7cNp4Ste6Jd .edge-animation-fast{stroke-dasharray:9,5!important;stroke-dashoffset:900;animation:dash 20s linear infinite;stroke-linecap:round;}#mermaid-svg-GWmeE7cNp4Ste6Jd .error-icon{fill:#552222;}#mermaid-svg-GWmeE7cNp4Ste6Jd .error-text{fill:#552222;stroke:#552222;}#mermaid-svg-GWmeE7cNp4Ste6Jd .edge-thickness-normal{stroke-width:1px;}#mermaid-svg-GWmeE7cNp4Ste6Jd .edge-thickness-thick{stroke-width:3.5px;}#mermaid-svg-GWmeE7cNp4Ste6Jd .edge-pattern-solid{stroke-dasharray:0;}#mermaid-svg-GWmeE7cNp4Ste6Jd .edge-thickness-invisible{stroke-width:0;fill:none;}#mermaid-svg-GWmeE7cNp4Ste6Jd .edge-pattern-dashed{stroke-dasharray:3;}#mermaid-svg-GWmeE7cNp4Ste6Jd .edge-pattern-dotted{stroke-dasharray:2;}#mermaid-svg-GWmeE7cNp4Ste6Jd .marker{fill:#333333;stroke:#333333;}#mermaid-svg-GWmeE7cNp4Ste6Jd .marker.cross{stroke:#333333;}#mermaid-svg-GWmeE7cNp4Ste6Jd svg{font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:16px;}#mermaid-svg-GWmeE7cNp4Ste6Jd p{margin:0;}#mermaid-svg-GWmeE7cNp4Ste6Jd .label{font-family:"trebuchet ms",verdana,arial,sans-serif;color:#333;}#mermaid-svg-GWmeE7cNp4Ste6Jd .cluster-label text{fill:#333;}#mermaid-svg-GWmeE7cNp4Ste6Jd .cluster-label span{color:#333;}#mermaid-svg-GWmeE7cNp4Ste6Jd .cluster-label span p{background-color:transparent;}#mermaid-svg-GWmeE7cNp4Ste6Jd .label text,#mermaid-svg-GWmeE7cNp4Ste6Jd span{fill:#333;color:#333;}#mermaid-svg-GWmeE7cNp4Ste6Jd .node rect,#mermaid-svg-GWmeE7cNp4Ste6Jd .node circle,#mermaid-svg-GWmeE7cNp4Ste6Jd .node ellipse,#mermaid-svg-GWmeE7cNp4Ste6Jd .node polygon,#mermaid-svg-GWmeE7cNp4Ste6Jd .node path{fill:#ECECFF;stroke:#9370DB;stroke-width:1px;}#mermaid-svg-GWmeE7cNp4Ste6Jd .rough-node .label text,#mermaid-svg-GWmeE7cNp4Ste6Jd .node .label text,#mermaid-svg-GWmeE7cNp4Ste6Jd .image-shape .label,#mermaid-svg-GWmeE7cNp4Ste6Jd .icon-shape .label{text-anchor:middle;}#mermaid-svg-GWmeE7cNp4Ste6Jd .node .katex path{fill:#000;stroke:#000;stroke-width:1px;}#mermaid-svg-GWmeE7cNp4Ste6Jd .rough-node .label,#mermaid-svg-GWmeE7cNp4Ste6Jd .node .label,#mermaid-svg-GWmeE7cNp4Ste6Jd .image-shape .label,#mermaid-svg-GWmeE7cNp4Ste6Jd .icon-shape .label{text-align:center;}#mermaid-svg-GWmeE7cNp4Ste6Jd .node.clickable{cursor:pointer;}#mermaid-svg-GWmeE7cNp4Ste6Jd .root .anchor path{fill:#333333!important;stroke-width:0;stroke:#333333;}#mermaid-svg-GWmeE7cNp4Ste6Jd .arrowheadPath{fill:#333333;}#mermaid-svg-GWmeE7cNp4Ste6Jd .edgePath .path{stroke:#333333;stroke-width:2.0px;}#mermaid-svg-GWmeE7cNp4Ste6Jd .flowchart-link{stroke:#333333;fill:none;}#mermaid-svg-GWmeE7cNp4Ste6Jd .edgeLabel{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-GWmeE7cNp4Ste6Jd .edgeLabel p{background-color:rgba(232,232,232, 0.8);}#mermaid-svg-GWmeE7cNp4Ste6Jd .edgeLabel rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-GWmeE7cNp4Ste6Jd .labelBkg{background-color:rgba(232, 232, 232, 0.5);}#mermaid-svg-GWmeE7cNp4Ste6Jd .cluster rect{fill:#ffffde;stroke:#aaaa33;stroke-width:1px;}#mermaid-svg-GWmeE7cNp4Ste6Jd .cluster text{fill:#333;}#mermaid-svg-GWmeE7cNp4Ste6Jd .cluster span{color:#333;}#mermaid-svg-GWmeE7cNp4Ste6Jd div.mermaidTooltip{position:absolute;text-align:center;max-width:200px;padding:2px;font-family:"trebuchet ms",verdana,arial,sans-serif;font-size:12px;background:hsl(80, 100%, 96.2745098039%);border:1px solid #aaaa33;border-radius:2px;pointer-events:none;z-index:100;}#mermaid-svg-GWmeE7cNp4Ste6Jd .flowchartTitleText{text-anchor:middle;font-size:18px;fill:#333;}#mermaid-svg-GWmeE7cNp4Ste6Jd rect.text{fill:none;stroke-width:0;}#mermaid-svg-GWmeE7cNp4Ste6Jd .icon-shape,#mermaid-svg-GWmeE7cNp4Ste6Jd .image-shape{background-color:rgba(232,232,232, 0.8);text-align:center;}#mermaid-svg-GWmeE7cNp4Ste6Jd .icon-shape p,#mermaid-svg-GWmeE7cNp4Ste6Jd .image-shape p{background-color:rgba(232,232,232, 0.8);padding:2px;}#mermaid-svg-GWmeE7cNp4Ste6Jd .icon-shape .label rect,#mermaid-svg-GWmeE7cNp4Ste6Jd .image-shape .label rect{opacity:0.5;background-color:rgba(232,232,232, 0.8);fill:rgba(232,232,232, 0.8);}#mermaid-svg-GWmeE7cNp4Ste6Jd .label-icon{display:inline-block;height:1em;overflow:visible;vertical-align:-0.125em;}#mermaid-svg-GWmeE7cNp4Ste6Jd .node .label-icon path{fill:currentColor;stroke:revert;stroke-width:revert;}#mermaid-svg-GWmeE7cNp4Ste6Jd :root{--mermaid-font-family:"trebuchet ms",verdana,arial,sans-serif;} 没绑
绑了
return true
return false
输入框聚焦,软键盘弹出
用户点击旁边的按钮
按钮绑了 onNeedSoftkeyboard?
焦点离开输入框,键盘收起
回调触发,框架等返回值
键盘保持弹出,继续输入
键盘收起
2.2 配套能力:focusOnTouch 与 requestFocus
单靠 onNeedSoftkeyboard 还不够,两个配套能力经常一起出现:
.focusOnTouch(true):让按钮在触摸时先接管焦点,这是onNeedSoftkeyboard回调被触发的前提,别漏了;requestFocus(key):给目标输入框设.key('xxx'),再通过this.getUIContext().getFocusController().requestFocus('xxx')把焦点直接送过去,输入框获焦时软键盘自动跟着弹出。配合.type(InputType.PhoneNumber)还能让手机号框弹数字键盘。
三、动手写:SoftKeyboardDemo
先看文件头部:
ets
interface ChatMsgItem {
msgSeq: number;
msgFrom: string;
msgText: string;
}
function chatBubbleBg(from: string): string {
if (from === 'me') {
return '#FF7A45';
}
return '#F0F2F5';
}
function chatBubbleText(from: string): ResourceColor {
if (from === 'me') {
return Color.White;
}
return '#3D4450';
}
function chatBubbleAlign(from: string): FlexAlign {
if (from === 'me') {
return FlexAlign.End;
}
return FlexAlign.Start;
}
@Entry
@Component
struct SoftKeyboardDemo {
build() {
Scroll() {
Column({ space: 14 }) {
Text('软键盘事件(onNeedSoftkeyboard)案例')
.fontSize(22)
.fontWeight(FontWeight.Bold)
Text('演示键盘接续:表情按钮不踢键盘、清空后继续输入、requestFocus 跳转焦点(API 24+)')
.fontSize(14)
.fontColor(Color.Gray)
SoftChatBoard()
SoftFormBoard()
}
.width('100%')
.padding(16)
.alignItems(HorizontalAlign.Start)
}
.width('100%')
.height('100%')
.backgroundColor('#F1F3F5')
.scrollBar(BarState.Off)
}
}
三个气泡样式函数按 msgFrom('me' / 'other')输出背景色、文字色和对齐方式------自己的消息橙色靠右,对方灰色靠左,经典的聊天布局,全部由状态驱动。
案例一:聊天栏的键盘接续
ets
@Component
struct SoftChatBoard {
@State chatMsgs: Array<ChatMsgItem> = [
{ msgSeq: 1, msgFrom: 'other', msgText: '周末去爬山吗?' },
{ msgSeq: 2, msgFrom: 'me', msgText: '好啊,我来订票' }
];
@State draftText: string = '';
@State keepKeyboard: boolean = true;
@State keepCount: number = 0;
@State lastReply: string = '正在输入时点表情按钮试试';
private msgSeq: number = 2;
private sendMsg(): void {
if (this.draftText.length === 0) {
this.getUIContext().getPromptAction().showToast({ message: '先输入内容', duration: 1200 });
return;
}
this.msgSeq += 1;
const msg: ChatMsgItem = { msgSeq: this.msgSeq, msgFrom: 'me', msgText: this.draftText };
this.chatMsgs.splice(0, 0, msg);
if (this.chatMsgs.length > 6) {
this.chatMsgs.splice(6, this.chatMsgs.length - 6);
}
this.draftText = '';
}
build() {
Column({ space: 10 }) {
Text('1. 聊天栏(返回 true 键盘接续)')
.fontSize(17)
.fontWeight(FontWeight.Bold)
Column({ space: 8 }) {
ForEach(this.chatMsgs, (msgItem: ChatMsgItem) => {
Row() {
Text(msgItem.msgText)
.fontSize(14)
.fontColor(chatBubbleText(msgItem.msgFrom))
.padding({ left: 12, right: 12, top: 8, bottom: 8 })
.constraintSize({ maxWidth: '75%' })
.backgroundColor(chatBubbleBg(msgItem.msgFrom))
.borderRadius(12)
}
.width('100%')
.justifyContent(chatBubbleAlign(msgItem.msgFrom))
}, (msgItem: ChatMsgItem) => msgItem.msgSeq.toString())
}
.width('100%')
.padding(10)
.backgroundColor('#FAFBFC')
.borderRadius(12)
.constraintSize({ maxHeight: 190 })
Row({ space: 8 }) {
TextInput({ text: this.draftText, placeholder: '输入消息...' })
.height(40)
.layoutWeight(1)
.backgroundColor(Color.White)
.onChange((value: string) => {
this.draftText = value;
})
Button('发送')
.fontSize(14)
.height(40)
.padding({ left: 14, right: 14 })
.onClick(() => {
this.sendMsg();
})
}
.width('100%')
Row({ space: 10 }) {
Button('😀 表情')
.fontSize(14)
.height(36)
.padding({ left: 12, right: 12 })
.focusOnTouch(true)
.onNeedSoftkeyboard(() => {
this.keepCount += 1;
this.lastReply = this.keepKeyboard ? '刚才返回 true:键盘留在原地,可以继续打字' : '刚才返回 false:键盘收起了';
return this.keepKeyboard;
})
.onClick(() => {
this.draftText = this.draftText + '😀';
})
Toggle({ type: ToggleType.Switch, isOn: this.keepKeyboard })
.onChange((isOn: boolean) => {
this.keepKeyboard = isOn;
})
Text('接续开关')
.fontSize(13)
.fontColor(Color.Gray)
}
.width('100%')
Text('回调已触发 ' + this.keepCount + ' 次 · ' + this.lastReply)
.fontSize(13)
.fontColor('#0A5F38')
Text('打字时点表情按钮:开关开着键盘不收、光标还在;发送按钮没绑回调,点它键盘直接收起')
.fontSize(13)
.fontColor(Color.Gray)
}
.width('100%')
.padding(14)
.backgroundColor(Color.White)
.borderRadius(16)
}
}
这个案例是一组对照实验,三个角色:

- "😀 表情"按钮绑了
onNeedSoftkeyboard:回调里更新计数和说明文字,最后return this.keepKeyboard------返回值由 Toggle 开关实时控制。开关打开时点表情,键盘留在原地、光标还在输入框里,onClick顺手往草稿里追加一个表情,打字节奏完全不断;开关关掉再点,返回 false,键盘应声收起。 - "发送"按钮故意不绑 :点它键盘直接收起------这是"没绑回调"的默认行为,正好做反面参照。什么按钮该接续键盘、什么按钮该收起键盘,产品语义自己定,
onNeedSoftkeyboard给的就是这个选择权。 .focusOnTouch(true)让按钮在触摸时先接管焦点,这是onNeedSoftkeyboard回调被触发的前提,别漏了。
消息列表照旧是头插 + 封顶 6 条 + msgSeq 做键值,constraintSize({ maxHeight: 190 }) 控制聊天窗高度。
案例二:表单------清空不踢键盘,requestFocus 跳焦
ets
@Component
struct SoftFormBoard {
@State nameText: string = '';
@State phoneText: string = '';
@State cityText: string = '';
@State formKeepCount: number = 0;
@State focusAction: string = '还没跳转过焦点';
build() {
Column({ space: 10 }) {
Text('2. 表单(清空不踢键盘 + requestFocus 跳焦)')
.fontSize(17)
.fontWeight(FontWeight.Bold)
Row({ space: 8 }) {
Text('姓名')
.fontSize(14)
.width(36)
TextInput({ text: this.nameText, placeholder: '请输入姓名' })
.height(40)
.layoutWeight(1)
.backgroundColor(Color.White)
.key('soft_form_name')
.onChange((value: string) => {
this.nameText = value;
})
Button('清空')
.fontSize(12)
.height(32)
.padding({ left: 10, right: 10 })
.focusOnTouch(true)
.onNeedSoftkeyboard(() => {
this.formKeepCount += 1;
return true;
})
.onClick(() => {
this.nameText = '';
})
}
.width('100%')
.alignItems(VerticalAlign.Center)
Row({ space: 8 }) {
Text('手机')
.fontSize(14)
.width(36)
TextInput({ text: this.phoneText, placeholder: '请输入手机号' })
.height(40)
.layoutWeight(1)
.backgroundColor(Color.White)
.key('soft_form_phone')
.type(InputType.PhoneNumber)
.onChange((value: string) => {
this.phoneText = value;
})
Button('清空')
.fontSize(12)
.height(32)
.padding({ left: 10, right: 10 })
.focusOnTouch(true)
.onNeedSoftkeyboard(() => {
this.formKeepCount += 1;
return true;
})
.onClick(() => {
this.phoneText = '';
})
}
.width('100%')
.alignItems(VerticalAlign.Center)
Row({ space: 8 }) {
Text('城市')
.fontSize(14)
.width(36)
TextInput({ text: this.cityText, placeholder: '请输入城市' })
.height(40)
.layoutWeight(1)
.backgroundColor(Color.White)
.key('soft_form_city')
.onChange((value: string) => {
this.cityText = value;
})
Button('清空')
.fontSize(12)
.height(32)
.padding({ left: 10, right: 10 })
.focusOnTouch(true)
.onNeedSoftkeyboard(() => {
this.formKeepCount += 1;
return true;
})
.onClick(() => {
this.cityText = '';
})
}
.width('100%')
.alignItems(VerticalAlign.Center)
Button('一键跳到手机号')
.fontSize(14)
.height(38)
.padding({ left: 16, right: 16 })
.backgroundColor('#6B4FBB')
.onClick(() => {
this.getUIContext().getFocusController().requestFocus('soft_form_phone');
this.focusAction = '已请求焦点到手机号输入框,键盘会跟着弹出';
})
Text('清空按钮回调已触发 ' + this.formKeepCount + ' 次 · ' + this.focusAction)
.fontSize(13)
.fontColor('#0A5F38')
Text('清空按钮返回 true:清掉内容键盘不收;requestFocus 用组件的 key 直接跳焦,不用一个个 Tab')
.fontSize(13)
.fontColor(Color.Gray)
}
.width('100%')
.padding(14)
.backgroundColor(Color.White)
.borderRadius(16)
}
}
三行表单,每行一个"清空"按钮,全部 .focusOnTouch(true) + onNeedSoftkeyboard 返回 true:点"清空"时内容清了、键盘不收,用户紧接着就能重新输入。这是"返回 true 固定写死"的简单场景,不需要像聊天栏那样用开关做实验。

"一键跳到手机号"按钮演示跨组件跳焦:
- 三个
TextInput都用.key('soft_form_xxx')登记了唯一标识; - 点击按钮执行
this.getUIContext().getFocusController().requestFocus('soft_form_phone'),焦点直接落到手机号输入框上,软键盘自动跟着弹出; .type(InputType.PhoneNumber)让手机号框弹数字键盘。
多字段表单里"填完上一项引导到下一项"不用让用户手动点,requestFocus + key 一行搞定。
四、跑起来看效果
DevEco Studio 直接 Run 即可,模拟器不需要签名。
本页的验证要点与硬件条件:
| 演示动作 | 预期效果 | 所需硬件 |
|---|---|---|
| 输入中点"😀 表情"(开关开) | 键盘留在原地,表情追加进草稿 | 触屏软键盘 |
| 关闭开关再点表情 | 键盘收起 | 触屏软键盘 |
| 点"发送" | 键盘直接收起(未绑回调的默认行为) | 触屏软键盘 |
| 点姓名行的"清空" | 内容清空,键盘不收,继续输入 | 触屏软键盘 |
| 点"一键跳到手机号" | 焦点跳到手机号框,弹出数字键盘 | 触屏软键盘 |
设备提醒:本页验证需要触屏软键盘 ,2in1 的物理键盘环境体验不到"键盘收起"的对比。手机、平板模拟器都行。

五、几个容易踩的点
1. API 24 门槛。 onNeedSoftkeyboard、OnNeedSoftkeyboardCallback、KeyboardInfo 都是 API 24 引入,compileSdkVersion 低于 24 的工程编译不过。老工程先升级 SDK 再迁移代码。
2. .focusOnTouch(true) 是回调触发的前提。 按钮不在触摸时接管焦点,onNeedSoftkeyboard 不会被调用。给"接续键盘"的按钮统一加上这条属性。
3. 回调只管键盘去留,业务逻辑写在 onClick。 返回 true 只是"键盘别收",点按钮该干的事(追加表情、清空输入)仍然在 onClick 里,两处别混。
4. key 属性的信息级警告不影响构建。 给 TextInput 设 .key('xxx') 时,ArkTS 检查器提示 'key' can only be used for testing directories------信息级别,不影响编译构建,requestFocus 就是要靠它定位组件,放心用。
5. main_pages.json 漏注册不报编译错误。 新建页面忘了登记,编译照过、跳转白屏。每次加页面,第一步就把它写进 src 数组。
总结
onNeedSoftkeyboard(API 24)以通用属性形式挂按钮,回调返回布尔值:true键盘保持弹出、false收起,框架等返回值再动手;- 没绑回调的按钮走默认行为------焦点离开输入框,键盘收起;
- 触发前提是
.focusOnTouch(true),业务逻辑与键盘去留分家:onClick干活,回调只表态; - 跨输入框引导用
requestFocus(key)+.key(),输入框获焦软键盘自动弹出,InputType.PhoneNumber还能指定数字键盘; - API 24 是硬门槛,老工程先升级
compileSdkVersion。
六类通用事件到这里全部实战完毕。它们如何在同一批组件上叠加共存,看汇合篇《HarmonyOS7 通用事件实战博客》的融合案例"桌面小组件工坊"。
参考资料
- onNeedSoftkeyboard(通用属性):可在华为开发者联盟「HarmonyOS 应用开发 → API 参考(ArkTS)」的「通用属性」章节检索"onNeedSoftkeyboard"条目;本地 SDK 类型定义位于
sdk\default\openharmony\ets\component\common.d.ts(onNeedSoftkeyboard、OnNeedSoftkeyboardCallback、KeyboardInfo均可在该文件检索),本文所有 API 签名与起始版本均以该文件核对。 - 系列其他篇:《HarmonyOS7 通用事件实战博客》(六类事件汇合篇)、《HarmonyOS7 点击事件实战博客》《HarmonyOS7 拖拽事件实战博客》《HarmonyOS7 焦点事件实战博客》《HarmonyOS7 悬停事件实战博客》《HarmonyOS7 快捷键事件实战博客》。
