HarmonyOS 如何实现点击按钮收起键盘(键盘收起同时TextInput失去焦点)

1、inputMethod.getController().stopInputSession()

2.TextInputController的stopEditing

上面2种方式只会收起键盘,但是不会让TextInput失去焦点,如果收起键盘之后弹出一个CustomDialog,关闭Dialog之后,TextInput又自动获得了焦点,键盘再次弹起来了。

3.通过控制TextInput的Focusable方法来收起键盘。

hideKeyboard() { 
  this.phoneInputCanFocus = false 
  this.codeInputCanFocus = false 
  setTimeout(() => { 
    this.phoneInputCanFocus = true 
    this.codeInputCanFocus = true 
  }, 500) 
}

但是这种代码写起来不太优雅。

请问还有其它关闭键盘的方式吗?

HarmonyOS
2024-09-03 09:49:12
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zbw_apple

可以参考以下代码:

import promptAction from '@ohos.promptAction' 
@Entry 
@Component 
struct TextInputExample { 
  @State text: string = '' 
  controller: TextInputController = new TextInputController() 
  build() { 
    Column() { 
      TextInput({ text: this.text, placeholder: '请输入用户名', controller: this.controller }) 
        .height(40) 
        .margin(20) 
        .fontSize(14) 
        .width('90%') 
      Button('弹出toast') 
        .onClick(() => { 
          // 焦点转移到button上 
          focusControl.requestFocus('button') 
          promptAction.showToast({ 
            message: '我是toast', 
            duration: 2000 
          }) 
        }).width('30%').key('button') 
    } 
    .width('100%') 
    .height('100%') 
  } 
}
分享
微博
QQ
微信
回复
2024-09-03 17:35:23
相关问题
HarmonyOS如何收起键盘
153浏览 • 1回复 待解决
HarmonyOS如何代码收起键盘
186浏览 • 1回复 待解决
如何实现文本展开收起功能
448浏览 • 1回复 待解决
HarmonyOS TextInput键盘相关问题咨询
218浏览 • 1回复 待解决
HarmonyOS TextInput自定义键盘问题
156浏览 • 1回复 待解决
HarmonyOS TextInput绑定自定义键盘问题
146浏览 • 1回复 待解决
如何实现键盘避让机制
2263浏览 • 1回复 待解决