鸿蒙如何监听键盘高度变化


HarmonyOS
2025-03-26 17:04:05
浏览
收藏 0
回答 2
待解决
回答 2
按赞同
/
按时间
程序员一鸣
1

可通过对keyboardHeightChange进行监听:



官网文档:​​https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-window​

分享
微博
QQ
微信
回复
2025-03-26 17:21:52
愚人ovo

解决方案:

  1. 通过display.getAllDisplays方式,获取屏幕高度。
let screenHeight: number = 0;
display.getAllDisplays((err, data) => {
  screenHeight = data[0].height
  console.log('height---', screenHeight)
})
  1. 方案一:​​getLastWindow​​,获取当前应用内最上层显示的子窗口,进而获取键盘高度。
let keyboardHeight: number = 0;
window.getLastWindow(getContext(this)).then(currentWindow {
  currentWindow.on('keyboardHeightChange', (data: number) => {
    keyboardHeight = px2vp(data);
    console.log('keyboardHeight----', keyboardHeight)
    this.sHeight = keyboardHeight / screenHeight * 100 // 转换为百分比形式
    console.log('sHeight----', this.sHeight)
  });
});
  1. 方案二:​​getMainWindow​​,获取该WindowStage实例下的主窗口,进而获取键盘高度。
await WindowManager.getWindowStage().getMainWindow().then(currentWindow {
  currentWindow.on('keyboardHeightChange', (data) => {
    this.keyboardHeight = px2vp(data);
    console.log('keyboardHeight----', this.keyboardHeight)
  })
})

完整参考案例如下:

import { display, window } from '@kit.ArkUI'

@Entry
@Component
struct ScrollCeiling1 {
  @State screenHeight: number = 1; // 屏幕高度
  @State keyboardHeight: number = 0; // 键盘高度
  @State sHeight: number = 0;

  build() {
    Column() {
      TextInput()
      Text(this.sHeight.toString() + '%') // 显示键盘高度占比
        .fontSize(18)
        .onAppear(() => {
          display.getAllDisplays((err, data) => {
            this.screenHeight = data[0].height
            console.log('height---', this.screenHeight)
          })
          window.getLastWindow(getContext(this)).then(currentWindow {
            currentWindow.on('keyboardHeightChange', (data: number) => {
              this.keyboardHeight = data;
              console.log('keyboardHeight----', this.keyboardHeight)
              this.sHeight = this.keyboardHeight / this.screenHeight * 100
              console.log('sHeight----', this.sHeight)
            });
          });
        })
    }
  }
}


分享
微博
QQ
微信
回复
1h前
相关问题
HarmonyOS 如何监听键盘弹出收回?
2552浏览 • 2回复 待解决
HarmonyOS page如何监听数据变化
1038浏览 • 1回复 待解决
如何监听window大小的变化
1589浏览 • 1回复 待解决
如何监听窗口大小的变化
3930浏览 • 1回复 待解决
HarmonyOS 如何监听系统主题变化
1171浏览 • 1回复 待解决
HarmonyOS 如何获取软键盘高度?
2836浏览 • 1回复 待解决
HarmonyOS 如何监听键盘抬起落下
1224浏览 • 1回复 待解决
HarmonyOS 如何监听组件自身尺寸变化
996浏览 • 1回复 待解决
HarmonyOS 如何监听某个变量是否变化
1170浏览 • 1回复 待解决
如何监听数组内对象属性变化
3452浏览 • 1回复 待解决
HarmonyOS 控件高度随滚动变化
1219浏览 • 1回复 待解决
HarmonyOS 网络变化监听失效
1092浏览 • 1回复 待解决
HarmonyOS onMemoryLevel监听内存变化
926浏览 • 1回复 待解决