如何通过编程方式关闭Android Soft KeyBoard?

Mak*_*Mak 50 android android-softkeyboard

我目前正在使用以下代码显示软键盘

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput (InputMethodManager.SHOW_FORCED, InputMethodManager.RESULT_HIDDEN);
Run Code Online (Sandbox Code Playgroud)

在这里我没有用Edittext绑定软键盘,因为我使用了上面的代码.

现在我想关闭SoftKeyboard,所以我目前正在使用下面的代码,但它无法正常工作.

imm.toggleSoftInput (InputMethodManager.SHOW_FORCED, InputMethodManager.RESULT_HIDDEN);
Run Code Online (Sandbox Code Playgroud)

任何人都可以建议我使用什么来关闭softKeyboard?


基于下面的答案,我想让你清楚我没有使用EditText,我使用Layout来显示键盘和隐藏键盘.我想将键盘键事件发送到我没有使用editText的远程区域bcoz.

小智 94

我已经测试过,这是有效的:

...
//to show soft keyboard
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

//to hide it, call the method again
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
Run Code Online (Sandbox Code Playgroud)

顺便说一句,你的代码的第二个参数是不对的,请看这里.

  • 根据http://stackoverflow.com/q/3568919/3990767和http://stackoverflow.com/q/4745988/3990767,检查键盘是否显示非常困难,因此切换可能不是一个好主意如果您不知道它是否已经显示. (5认同)
  • 为什么使用相同的代码行进行显示和隐藏? (4认同)

Jan*_*ana 40

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

  • @Mak然后使用:getCurrentFocus().getWindowToken() (9认同)
  • 我没有使用EditText. (4认同)

小智 32

使用此工作代码:

InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
Run Code Online (Sandbox Code Playgroud)


小智 9

如果需要,您可以使用整个类并在以下任何地方调用KeyboardUtil.hideKeyBoard(context)方法:

public class KeyboardUtil
{
public static void hideKeyboard(Activity activity)
    {
        try
        {
            InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
         }
        catch (Exception e)
        {
            // Ignore exceptions if any
                Log.e("KeyBoardUtil", e.toString(), e);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 总是有效的解决方案并发送标志"HIDE_NOT_ALWAYS",好笑:) (3认同)

Ash*_*ava 5

关闭/隐藏 Android 软键盘

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

it's working for me i hope it's work for you..
Run Code Online (Sandbox Code Playgroud)

打开安卓软键盘

 InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputMethodManager != null) {
            inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
        }
Run Code Online (Sandbox Code Playgroud)