Android关闭键盘

按下按钮时如何关闭键盘?

你想禁用或解雇一个虚拟键盘?

如果你只想解雇它,你可以在按钮的点击事件中使用下面的代码行

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0); 

上面的解决方案不适用于所有设备,而且它使用EditText作为参数。 这是我的解决方案,只需调用这个简单的方法:

 private void hideSoftKeyBoard() { InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); if(imm.isAcceptingText()) { // verify if the soft keyboard is open imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } } 

这是我的解决方案

 public static void hideKeyboard(Activity activity) { View v = activity.getWindow().getCurrentFocus(); if (v != null) { InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(v.getWindowToken(), 0); } } 

您也可以在按钮单击事件上使用此代码

 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); 

与InputMethodManager的第一个解决方案就像我的冠军,getWindow()。setSoftInputMode方法没有在Android 4.0.3宏达惊奇。

@艾伦,我不需要编辑文本的最后。 也许你正在使用一个EditText内部类来声明包含方法? 您可以使EditText成为Activity的类变量。 或者只是在内部类/方法内部声明一个新的EditText,并再次使用findViewById()。 另外,我没有发现我需要知道表单中哪个EditText有焦点。 我可以任意挑一个并使用它。 像这样:

  EditText myEditText= (EditText) findViewById(R.id.anyEditTextInForm); InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0); 
  public static void hideSoftInput(Activity activity) { try { if (activity == null || activity.isFinishing()) return; Window window = activity.getWindow(); if (window == null) return; View view = window.getCurrentFocus(); if (view == null) return; InputMethodManager imm = (InputMethodManager) activity.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE); if (imm == null || !imm.isActive()) return; imm.hideSoftInputFromWindow(view.getWindowToken(), 0); } catch (Throwable e) { e.printStackTrace(); } } 

这里有一个Kotlin解决方案(在线程中混合各种答案)

创建一个扩展函数(可能在一个普通的ViewHelpers类中)

 fun Activity.dismissKeyboard() { val inputMethodManager = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager if( inputMethodManager.isAcceptingText ) inputMethodManager.hideSoftInputFromWindow( this.currentFocus.windowToken, /*flags:*/ 0) } 

然后简单地使用:

 // from activity this.dismissKeyboard() // from fragment activity.dismissKeyboard()