HarmonyOS 鸿蒙Next中软键盘避让
HarmonyOS 鸿蒙Next中软键盘避让
// EntryAbility.ets
onWindowStageCreate(windowStage: window.WindowStage): void {
windowStage.getMainWindow((err, windowClass) => {
if (!err.code) {
try {
windowClass.on('keyboardHeightChange', (data) => {AppStorage.setOrCreate('keyboardHeight', data)});
AppStorage.setOrCreate('bottomHeight', windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR).bottomRect.height);
} catch (exception) {
console.error('获取软键盘高度和安全区底部高度失败: ' + JSON.stringify(exception));
}
}
})
}
// Index.ets
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
@StorageLink('keyboardHeight') keyboardHeight: number = 0;
@StorageLink('bottomHeight') bottomHeight: number = 0;
controller: TextInputController = new TextInputController();
build() {
Column() {
Row() {
}.height(100).width("100%").backgroundColor("#1F1")
Column() {
}.width("100%").backgroundColor("#16F").layoutWeight(1)
TextInput({controller: this.controller}).width("50%")
}.height('100%').width('100%').padding({bottom:(px2vp(this.keyboardHeight) - px2vp(this.bottomHeight))}).expandSafeArea([SafeAreaType.KEYBOARD])
}
}
更多关于HarmonyOS 鸿蒙Next中软键盘避让的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
在HarmonyOS Next中,软键盘避让可通过配置窗口的softInputMode
实现。常见模式包括:
SOFT_INPUT_ADJUST_RESIZE
:自动调整窗口大小SOFT_INPUT_ADJUST_PAN
:平移窗口内容SOFT_INPUT_ADJUST_NOTHING
:不调整
在ability的config.json
中设置:
"window": {
"softInputMode": "SOFT_INPUT_ADJUST_RESIZE"
}
对于ArkUI组件,可通过position
属性和margin
参数确保关键内容不被键盘遮挡。Scroll容器会自动处理内容滚动避让。
更多关于HarmonyOS 鸿蒙Next中软键盘避让的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS Next中处理软键盘避让的正确方式如下:
-
你的代码基本正确,但需要注意以下几点优化:
-
在EntryAbility.ets中:
- 建议添加对键盘高度变化的初始值处理
- 安全区获取可以放在windowStage.loadContent之前
- 在Index.ets中:
- 使用expandSafeArea([SafeAreaType.KEYBOARD])是正确的
- 但padding计算可以简化为:
.padding({bottom: Math.max(0, px2vp(this.keyboardHeight) - px2vp(this.bottomHeight))})
- 注意事项:
- 确保在manifest.json中声明了"ohos.permission.GET_WINDOW_INFO"权限
- 对于复杂布局,建议使用Scroll组件配合键盘事件实现更好的用户体验
- 替代方案: 也可以考虑使用windowClass.setWindowLayoutFullScreen(true)来让系统自动处理键盘避让
这种实现方式在HarmonyOS Next上是推荐的做法,能正确处理键盘弹出时的布局调整。