鸿蒙中如何获取键盘的高度?

鸿蒙中如何获取键盘的高度?

要实现类似微信聊天的信息,加号区和表情高度如果和键盘高度一致,则输入框不会出现上下跳动的问题,鸿蒙中有获取键盘高度的方法吗?

本文参与了思否 HarmonyOS 技术问答马拉松,欢迎正在阅读的你也加入。
阅读 1.6k
2 个回答

可参考如下示例:

import window from '@ohos.window';

@Entry
@Component
export default struct TestPage {
@State screenHeight: number = 0;

aboutToAppear() {
window.getLastWindow(getContext(this)).then(currentWindow =>{
let property = currentWindow.getWindowProperties();
let avoidArea = currentWindow.getWindowAvoidArea(window.AvoidAreaType.TYPE_KEYBOARD);
// 初始化显示区域高度
this.screenHeight = px2vp(property.windowRect.height - avoidArea.bottomRect.height);
// 监视软键盘的弹出和收起
currentWindow.on('avoidAreaChange', async data => {
if (data.type !== window.AvoidAreaType.TYPE_KEYBOARD) {
return;
}
this.screenHeight = px2vp(property.windowRect.height - data.area.bottomRect.height);
console.log(this.screenHeight.toString())//输出可以看到键盘的高度
})
})
}

build() {
Row() {
Column() {
Text('请输入短信验证码')
.fontSize(30)
.margin({
bottom:'50'
})
TextInput()
.width('70%')
.height('150px')
.margin({
bottom: '30'
})
Button('确定')
.width('70%')
.margin('20px')
}
.width('100%')
}
.width('100%').height(this.screenHeight)
}
}

楼主你好,看了你的问题,据我所知,鸿蒙OS获取键盘高度和其他移动端开发获取键盘高度的方式差不多,主要是具体的实现方式,最核心的步骤就是需要监听键盘的弹出事件,以及设置弹出区域的高度,通过获取和计算系统的高度,设置键盘弹出高度即可。

本文参与了思否 HarmonyOS 技术问答马拉松,欢迎正在阅读的你也加入。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题