我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
Kotlin版本:
fun showKeyboard(mEtSearch: EditText, context: Context) {
mEtSearch.requestFocus()
val imm: InputMethodManager =
context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.showSoftInput(mEtSearch, 0)
}
其他回答
如果您的应用程序以API Level 21或更高为目标,则可以使用默认方法:
editTextObj.setShowSoftInputOnFocus(false);
确保在EditText XML标记中设置了以下代码。
<EditText
....
android:enabled="true"
android:focusable="true" />
如果你使用Kotlin开发你的应用程序,这真的很容易做到。
添加此扩展功能:
对于活动:
fun Activity.hideKeyboard() {
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val view = currentFocus
if (view != null) {
inputManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
对于片段:
fun Fragment.hideKeyboard() {
activity?.let {
val inputManager = it.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val view = it.currentFocus
if (view != null) {
inputManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}
}
}
现在,您可以简单地调用片段或活动:
hideKeyboard()
对于科特林爱好者。我创建了两个扩展函数。为了隐藏键盘的乐趣,您可以将edittext的实例作为视图传递。
fun Context.hideKeyboard(view: View) {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.apply {
hideSoftInputFromWindow(view.windowToken, 0)
}
}
fun Context.showKeyboard() {
(getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.apply {
toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)
}
}
这对我很有用
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isActive())
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
对于那些寻找喷气背包的人来说,写下答案。
val keyboardController = LocalSoftwareKeyboardController.current
//for showing the keyboard
keyboardController?.show()
//for hiding the keyboard
keyboardController?.hide()