📌 场景介绍

在表单输入、评论回复、聊天输入等场景中,控制软键盘的行为能提升体验,例如:

  • 页面加载时自动弹出键盘

  • 提交表单后隐藏键盘

  • 手动调用显示/关闭键盘

本篇基于 @ohos.inputMethod 模块实现软键盘控制功能。


🧱 页面结构

/entry/src/main/ets
  └── pages/
       └── KeyboardControlDemo.ets      // 键盘控制页

🧩 KeyboardControlDemo.ets 示例页面

import inputMethod from '@ohos.inputMethod'

@Entry
@Component
struct KeyboardControlDemo {
  @State textValue: string = ''
  private textRef: TextInputController = new TextInputController()

  async aboutToAppear() {
    // 页面加载时 500ms 后自动弹出键盘
    setTimeout(() => {
      this.showKeyboard()
    }, 500)
  }

  private async showKeyboard() {
    try {
      await this.textRef.focus()
      await inputMethod.show()
    } catch (err) {
      console.error('打开键盘失败:', JSON.stringify(err))
    }
  }

  private async hideKeyboard() {
    try {
      await inputMethod.hide()
    } catch (err) {
      console.error('隐藏键盘失败:', JSON.stringify(err))
    }
  }

  build() {
    Column() {
      Text("🧾 请输入信息").fontSize(20).margin({ bottom: 10 })

      TextInput({
        controller: this.textRef,
        text: this.textValue,
        placeholder: "点击输入内容",
        onChange: val => this.textValue = val
      })
      .height(40)
      .border({ width: 1, color: '#aaa' })
      .padding({ left: 10, right: 10 })
      .margin({ bottom: 20 })

      Row() {
        Button("显示键盘").onClick(() => this.showKeyboard()).margin(10)
        Button("隐藏键盘").onClick(() => this.hideKeyboard()).margin(10)
      }
    }
    .padding(30)
    .height('100%')
  }
}

✅ 效果说明

  • 页面加载时自动弹出键盘并聚焦输入框

  • 用户可手动点击按钮打开/关闭软键盘

  • 保证键盘调用过程无报错,稳定兼容


🔧 拓展建议

  • 提交按钮后自动关闭键盘

  • 输入框失去焦点时自动隐藏键盘

  • 与弹窗、表单联动键盘行为(防止遮挡)

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐