回答

收藏

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

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

我的布局之一EditText和一个Button。/ T5 h8 \; U3 h% C, V# G) F
在编辑字段中写入并单击 Button,我想在触摸键盘外部时隐藏虚拟键盘。我认为这是一个简单的代码,但我在哪里可以找到它的例子呢?
# o  H+ k6 _! Y# i* b7 O" A: d. K                                                               
) @8 A# d# F$ |. l; \9 Q6 h7 `    解决方案:                                                                : L: g: d- y9 A
                                                                您可以使用InputMethodManager强制 Android 隐藏虚拟键盘,调用hideSoftInputFromWindow,标记包含焦点视图的窗口。
8 _9 [+ [7 |8 G* L2 |

    / _8 Y2 j2 |0 z# X% P
  • // 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输入作为第二个参数,以确保键盘只隐藏在用户没有明确强制显示键盘时(按菜单)。
    ) x! m) r+ G% P; }+ T
  • 注意:假如你想在 Kotlin 请使用此操作: context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    + J) g+ F6 X  B" d
  • 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)}
    - d3 P0 K- {1 }
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则