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

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


当前回答

对于kotlin用户,这里有一个kotlin扩展方法,它适用于我的用例:

fun View.hideKeyboard() {
    val imm = this.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)
}

将其放在名为ViewExtensions的文件中(或其他文件),并像普通方法一样在视图中调用它。

其他回答

现在,将近12年后,我们终于有了一种官方的、向后兼容的方式来实现AndroidX Core 1.5+:

fun View.hideKeyboard() = ViewCompat.getWindowInsetsController(this)
    ?.hide(WindowInsetsCompat.Type.ime())

或特别针对片段:

fun Fragment.hideKeyboard() = ViewCompat.getWindowInsetsController(requireView())
    ?.hide(WindowInsetsCompat.Type.ime())

如果您需要在片段中隐藏键盘,则此方法有效。

public static void hideSoftKeyboard(Context context, View view) {
    if (context != null && view != null) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

对于视图,只需传入

getView() method

有时你只需要按回车键来折叠键盘在“编辑文本”框中指定属性

 android:imeOptions="actionDone" 

这将将Enter按钮更改为Done按钮,该按钮将关闭键盘。

每次都像魔术般

private void closeKeyboard() {
    InputMethodManager inputManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

}

private void openKeyboard() {
    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    if(imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }
}

在阅读了上面和另一篇文章中的所有答案后,我仍然没有成功地让键盘自动打开。

在我的项目中,我动态地创建了一个对话框(AlertDialog)(通过不使用或使用最少的XML对其进行编程)。

所以我在做一些事情,比如:

    dialogBuilder = new AlertDialog.Builder(activity);

    if(dialogBuilder==null)
        return false; //error

    inflater      = activity.getLayoutInflater();
    dialogView    = inflater.inflate(layout, null);
    ...

在完成所有视图(TextView、ImageView、EditText等)的设置后,我做到了:

        alertDialog = dialogBuilder.create();

        alertDialog.show();

在玩转了所有答案后,我发现如果你知道把请求放在哪里,大多数答案都有效。。。这是一切的关键。

所以,诀窍是在创建对话框之前使用它:alertDialog.show()。在我的例子中,这就像魅力一样:

        alertDialog = dialogBuilder.create();           
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        //And only when everything is finished - let's bring up the window - 
        alertDialog.show();

        //Viola... keyboard is waiting for you open and ready...
        //Just don't forget to request focus for the needed view (i.e. EditText..)

我很确定这一原则在所有窗口中都是一样的,所以请注意“showKeyboard”代码的位置——它应该在窗口启动之前。

来自Android SDK开发团队的一个小请求:

我认为所有这些都是不必要的,因为你可以看到来自世界各地的数千名程序员正在处理这个荒谬而琐碎的问题,而其解决方案应该是干净而简单的:IMHO如果我将requestFocus()获取到面向输入的视图(如EditText),键盘应该自动打开,除非用户要求不打开,因此,我认为requestFocus方法是这里的关键,应该接受默认值为true的布尔showSoftKeyboard:view.requestFocus(布尔showSoftKeyboard);

希望这能帮助像我这样的人。