我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
我的布局中有一个EditText和一个Button。
在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?
当前回答
简单的方法家伙:试试这个。。。
private void closeKeyboard(boolean b) {
View view = this.getCurrentFocus();
if(b) {
if (view != null) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
else {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(view, 0);
}
}
其他回答
隐藏软键盘也很有用:
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);
这可用于抑制软键盘,直到用户实际触摸editText View。
使用SearchView的另一种方法是使用以下代码:
searchView = (SearchView) searchItem.getActionView();
searchView.setOnQueryTextListener(new OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
InputMethodManager imm = (InputMethodManager)
getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(searchView.getApplicationWindowToken(), 0);
}
}
这是ActionBar中的一个SearchView搜索框,当提交查询中的文本时(用户按下Enter键或搜索按钮/图标),InputMethodManager代码将被激活并使软键盘关闭。此代码已放入我的onCreateOptionsMenu()中。searchItem来自MenuItem,它是onCreateOptionsmenu()默认代码的一部分。感谢@mckoss提供了大量的代码!
fun hideKeyboard(appCompatActivity: AppCompatActivity) {
val view = appCompatActivity.currentFocus
val imm = appCompatActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.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) {
}
}
在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甚至可以工作