HarmonyOS鸿蒙Next中在TextInput组件获取焦点时,如何解决点击组件外软键盘无法收起的问题

HarmonyOS鸿蒙Next中在TextInput组件获取焦点时,如何解决点击组件外软键盘无法收起的问题

【问题现象】

在TextInput获取焦点时,点击组件外软键盘无法收起。

【定位思路】

  1. 给外层空白区域添加点击事件,调用this.controller.stopEditing()收起键盘。
  2. 当界面上元素比较多,不适合为每个组件分别都搞个controller,这时可以通过输入法服务InputMethodControllerstopInputSession接口,然后来控制点击空白区域是否收起键盘。参考链接:@ohos.inputMethod (输入法框架)

【解决方案】

使用@ohos.inputMethod (输入法框架),通过输入法服务InputMethodControllerstopInputSession接口控制点击空白区域是否收起键盘。

示例代码如下:

import { inputMethod } from '@kit.IMEKit';

@Entry
@Component
struct LeftRightTest {
  @State a: boolean = true;
  controller: TextInputController = new TextInputController()

  build() {
    Column() {
      TextInput({ placeholder: '请输入内容' })
        .backgroundColor(Color.Orange)
        .onTouch(() => {
          this.a = true;
        })
      Button('点我')
      TextInput({ placeholder: '请输入内容' })
        .backgroundColor(Color.Orange)
        .onTouch(() => {
          this.a = true;
        })
    }
    .height('100%')
    .width('100%')
    .onTouch(() => {
      if (this.a != true) {
        // 收起键盘
        let inputMethodController = inputMethod.getController();
        inputMethodController.stopInputSession()
      }
      this.a = false
    })
  }
}

更多关于HarmonyOS鸿蒙Next中在TextInput组件获取焦点时,如何解决点击组件外软键盘无法收起的问题的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中在TextInput组件获取焦点时,如何解决点击组件外软键盘无法收起的问题的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


使用@ohos.inputMethod (输入法框架)

通过输入法服务 InputMethodControllerstopInputSession 接口控制点击空白区域是否收起键盘。示例代码如下:

import { inputMethod } from '@kit.IMEKit';

@Entry
@Component
struct LeftRightTest {
  @State a: boolean = true;
  controller: TextInputController = new TextInputController()

  build() {
    Column() {
      TextInput({ placeholder: '请输入内容' })
        .backgroundColor(Color.Orange)
        .onTouch(() => {
          this.a = true;
        })
      Button('点我')
      TextInput({ placeholder: '请输入内容' })
        .backgroundColor(Color.Orange)
        .onTouch(() => {
          this.a = true;
        })
    }
    .height('100%')
    .width('100%')
    .onTouch(() => {
      if (this.a != true) {
        let inputMethodController = inputMethod.getController();
        inputMethodController.stopInputSession()
      }
      this.a = false
    })
  }
}
回到顶部