我的布局中有一个 EditText
和一个 Button
。
在编辑字段中写入并单击按钮
后,我想在触摸键盘外时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
最佳答案
您可以使用 InputMethodManager 强制 Android 隐藏虚拟键盘, 调用 hideSoftInputFromWindow
,传入包含焦点 View 的窗口的标记。
// 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);
}
这将强制键盘在所有情况下都隐藏。在某些情况下,您需要传入 InputMethodManager.HIDE_IMPLICIT_ONLY
作为第二个参数,以确保仅在用户没有明确强制它出现时(通过按住菜单)隐藏键盘。
注意:如果您想在 Kotlin 中执行此操作,请使用:
context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
Kotlin 语法
// Only runs if there is a view that is currently focused
this.currentFocus?.let { view ->
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
imm?.hideSoftInputFromWindow(view.windowToken, 0)
}
https://stackoverflow.com/questions/1109022/
相关文章:
android - 如何在 TextView 中水平和垂直居中文本?
android - 如何使用保存实例状态保存 Activity 状态?
android - match_parent 和 fill_parent 有什么区别?
android - 当 Activity 在 Android 中启动时,如何阻止 EditText
android - Eclipse Android 插件中的 "Debug certificate
android - 为什么安卓模拟器这么慢?我们如何加快Android模拟器的速度?
android - Android 上的 'Context' 是什么?
android - 如何在Android中将屏幕尺寸作为像素获取