我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
在Kotlin中,只需使用这两种方法来显示和隐藏键盘。
fun showKeyboard() =
(context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as? InputMethodManager)!!
.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
fun hideKeyboard(view: View) =
(context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as? InputMethodManager)!!
.hideSoftInputFromWindow(view.windowToken, 0)
这里的视图是您当前的视图,
其他回答
只需调用下面的方法,如果键盘显示,它将隐藏键盘。
public void hideKeyboard() {
try {
InputMethodManager inputmanager = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputmanager != null) {
inputmanager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
}
} catch (Exception var2) {
}
}
这是我的工作。这是在Kotlin隐藏键盘。
private fun hideKeyboard() {
val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
val focusedView = activity?.currentFocus
if (focusedView != null) {
inputManager.hideSoftInputFromWindow(focusedView.windowToken,
InputMethodManager.HIDE_NOT_ALWAYS)
}
}
以下是最佳解决方案
解决方案1)将inputType设置为“text”
<EditText
android:id="@+id/my_edit_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Tap here to type"
android:inputType="text" />
这也可以通过编程实现。方法setInputType()(从TextView继承)。
EditText editText = (EditText) findViewById(R.id.my_edit_text);
editText.setRawInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_NORMAL);
解决方案2)使用InputMethodManager.hideSoftInputFromWindow()
InputMethodManager imm =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
or
InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
在Android中,要通过InputMethodManage隐藏Vkeyboard,您可以通过传递包含焦点视图的窗口的标记来隐藏SoftInputFromWindow。
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager im =
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
通过调用editText.clearFocus(),然后调用InputMethodManager.HIDE_IMPLICIT_ONLY甚至可以工作
这个对我有用,你只需要传递里面的元素。
InputMethodManager imm=(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(AutocompleteviewDoctorState.getWindowToken(), 0);