关闭/隐藏Android的软键盘键盘、Android

2023-09-11 10:17:41 作者:留点自尊给我

我在我的布局的EditText 按钮。写在编辑栏,并点击按钮后,我想隐藏虚拟键盘。我认为有一个简单,一两班轮做到这一点。我在哪里可以找到它的一个例子吗?

I have an EditText and a Button in my layout. After writing in the edit field and clicking on the Button, I want to hide the virtual keyboard. I assume that there's a simple, one- or two-liner to make this happen. Where can I find an example of it?

推荐答案

您可以强制使用Android的隐藏虚拟键盘的InputMethodManager,调用hideSoftInputFromWindow,传递包含您的集中视图窗口的记号。

You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your focused view.

// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {  
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

这将迫使键盘被隐藏于所有情况。在某些情况下,你将要在 InputMethodManager.HIDE_IMPLICIT_ONLY 传递的第二个参数,以确保您只隐藏键盘,当用户没有明确强制其出庭(通过持有下拉菜单)。

This will force the keyboard to be hidden in all situations. In some cases you will want to pass in InputMethodManager.HIDE_IMPLICIT_ONLY as the second parameter to ensure you only hide the keyboard when the user didn't explicitly force it to appear (by holding down menu).