我的布局中有一个EditText和一个Button。

在编辑字段中写入并单击按钮后,我想在触摸键盘外部时隐藏虚拟键盘。我假设这是一段简单的代码,但我在哪里可以找到它的示例?


当前回答

用try-catch包围它,这样键盘就已经关闭,应用程序就不会崩溃:

try{

View view = this.getCurrentFocus();
if (view != null) {  
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}catch (Exception e)
{
  e.printStackTrace();
}

其他回答

在Kotlin试试这个

 private fun hideKeyboard(){
    val imm = activity!!.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(activity!!.currentFocus!!.windowToken, 0)
}

在Java中尝试

 private void hideKeyboard(){
  InputMethodManager imm =(InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}

作为这一全面解决方案的替代方案,如果您想从任何地方关闭软键盘,而没有对用于打开键盘的(EditText)字段的引用,但仍然希望在该字段被聚焦时进行此操作,则可以使用(从“活动”):

if (getCurrentFocus() != null) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}

Kotlin版本

val imm: InputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
//Hide:
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
//Show
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

如果您想在单元或功能测试期间关闭软键盘,可以通过单击测试中的“后退按钮”来完成:

// Close the soft keyboard from a Test
getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);

我将“后退按钮”放在引号中,因为上面的内容不会触发所讨论的活动的onBackPressed()。它只是关闭键盘。

在继续之前,请确保暂停一段时间,因为关闭后退按钮需要一段时间。因此,在短暂暂停后(1秒足够长),才能注册随后的视图等单击。

试试这个

简单,您可以在活动中调用


 public static void hideKeyboardwithoutPopulate(Activity activity) {
    InputMethodManager inputMethodManager =
            (InputMethodManager) activity.getSystemService(
                    Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(
            activity.getCurrentFocus().getWindowToken(), 0);
}

在您的主活动中调用


 hideKeyboardwithoutPopulate(MainActivity.this);