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

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


当前回答

在我的案例中,我使用的是操作栏中的SearchView。用户执行搜索后,键盘将再次弹出。

使用InputMethodManager未关闭键盘。我必须清除Focus并将搜索视图的可聚焦设置为false:

mSearchView.clearFocus();
mSearchView.setFocusable(false);

其他回答

Android 11中有一个名为WindowInsetsController的新API,应用程序可以从任何视图访问控制器,通过它我们可以使用hide()和show()方法

val controller = view.windowInsetsController

// Show the keyboard (IME)
controller.show(Type.ime())

// Hide the keyboard
controller.hide(Type.ime())

看见https://developer.android.com/reference/android/view/WindowInsetsController

试试这个

public void disableSoftKeyboard(final EditText v) {
    if (Build.VERSION.SDK_INT >= 11) {
        v.setRawInputType(InputType.TYPE_CLASS_TEXT);
        v.setTextIsSelectable(true);
    } else {
        v.setRawInputType(InputType.TYPE_NULL);
        v.setFocusable(true);
    }
}

隐藏软键盘也很有用:

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

这可用于抑制软键盘,直到用户实际触摸editText View。

只需在活动中使用此优化代码:

if (this.getCurrentFocus() != null) {
    InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

这是工作。。

只需在函数中传递当前活动实例

 public void isKeyBoardShow(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    if (imm.isActive()) {
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // hide
    } else {
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
    }
}