回答

收藏

如何以编程方式关闭/隐藏 Android 软键盘?

技术问答 技术问答 308 人阅读 | 0 人回复 | 2023-09-11

我的布局之一EditText和一个Button。
- _! @  U9 R. f; e在编辑字段中写入并单击 Button,我想在触摸键盘外部时隐藏虚拟键盘。我认为这是一个简单的代码,但我在哪里可以找到它的例子呢?$ \- I9 N; W: U5 W
                                                                , l& m* K! D) G6 i2 ~0 q
    解决方案:                                                               
8 m! d" ]$ f. c! I  j7 ~                                                                您可以使用InputMethodManager强制 Android 隐藏虚拟键盘,调用hideSoftInputFromWindow,标记包含焦点视图的窗口。
- e1 O7 q6 A0 L8 T* C1 u  s* F
    . G& ^. ~" h+ B9 \8 F
  • // Check if no view has focus:View view = this.getCurrentFocus();if (view != null) {       InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);    imm.hideSoftInputFromWindow(view.getWindowToken(),0);code]在所有情况下,这将被迫隐藏键盘。在某些情况下,你会希望的InputMethodManager.HIDE_IMPLICIT_ONLY输入作为第二个参数,以确保键盘只隐藏在用户没有明确强制显示键盘时(按菜单)。8 S9 p1 ~( }6 G7 r# g
  • 注意:假如你想在 Kotlin 请使用此操作: context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    ; j  m6 M) M& \9 {: ?
  • Kotlin 语法[code]// Only runs if there is a view that is currently focusedthis.currentFocus?.let { view ->    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager    imm?.hideSoftInputFromWindow(view.windowToken,0)}
    8 @/ n9 u% Q/ r
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则