Android解雇键盘

Man*_*dan 143 android

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

DeR*_*gan 321

您想要禁用或关闭虚拟键盘?

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

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
Run Code Online (Sandbox Code Playgroud)

  • 对于在这里偶然发现的其他人,你可以使用活动的(你所在的活动或片段`getActivity()`)`getCurrentFocus().getWindowToken()`为第一个arg到`hideSoftInputFromWindow()`.另外,如果你试图在改变活动时让它消失,那么在`onPause()`而不是`onStop()`中做. (75认同)
  • 关闭键盘是多么丑陋、丑陋的方法。我希望将来有一种更清洁的方法来做这么简单的事情。 (8认同)
  • 这个答案加上这里的评论,完全解决了我的问题! (2认同)

use*_*877 68

上面的解决方案不适用于所有设备,而且它使用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • `isAcceptingText()`使这个答案比其他答案更好 (3认同)

RPM*_*RPM 28

这是我的解决方案

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


Kan*_*dha 15

您也可以在按钮点击事件中使用此代码

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
Run Code Online (Sandbox Code Playgroud)


Mar*_*chy 9

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

创建扩展函数(可能在常见的ViewHelpers类中)

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

然后简单地使用:

// from activity
this.dismissKeyboard()

// from fragment
activity.dismissKeyboard()
Run Code Online (Sandbox Code Playgroud)


小智 5

第一个使用InputMethodManager的解决方案对我来说就像一个冠军,getWindow().setSoftInputMode方法不适用于android 4.0.3 HTC Amaze.

@Ethan Allen,我不需要让编辑文本最终成功.也许您正在使用您声明包含方法的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);
Run Code Online (Sandbox Code Playgroud)

  • 欢迎来到Stack Overflow!这真是一个评论,而不是答案.有了更多的代表,[你将能够发表评论](http://stackoverflow.com/privileges/comment). (3认同)