Android:点击按钮后隐藏键盘

Mar*_*nks 25 keyboard android hide

单击按钮后我需要隐藏android键盘.

我已经看过许多如何做到这一点的例子,但是,它们似乎都使用了特定的editText对象.

例如

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

我的问题是我正在动态构建屏幕,因此可能存在鬃毛编辑文本字段.有没有办法隐藏键盘而不必指定我隐藏它的editText对象.

bur*_*mat 47

您可以将其设置为您的布局,即:

LinearLayout mainLayout;

// Get your layout set up, this is just an example
mainLayout = (LinearLayout)findViewById(R.id.myLinearLayout);

// Then just use the following:
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(mainLayout.getWindowToken(), 0);
Run Code Online (Sandbox Code Playgroud)

这是一个示例,假设无论EditText放置多少个对象(或其他对象),都将创建布局.

编辑:另外,我发现非常有用的东西是确保在活动首次启动时隐藏键盘(即:如果EditText是第一个关注的事情).为此,我把它放在onCreate()Activity的方法中:

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

  • 请注意,它也适用于其他视图部分,例如 EditText :) 然后您将更改以下行:`imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);` (4认同)

Pra*_*dro 42

别忘了使用try catch blog,因为万一你的键盘没有打开,如果你使用键盘隐藏代码应用程序将崩溃

try {
    InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
} catch (Exception e) {
    // TODO: handle exception
}
Run Code Online (Sandbox Code Playgroud)

  • 迄今为止最简单优雅的解决方案 (3认同)

Int*_*iya 10

您可以使用以下代码隐藏键盘,可能在按钮单击事件上:

//================ Hide Virtual Key Board When  Clicking==================//

InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow("Your Button/EditText Object".getWindowToken(), InputMethodManager.RESULT_UNCHANGED_SHOWN);

//======== Hide Virtual Keyboard =====================//
Run Code Online (Sandbox Code Playgroud)


Mak*_*vin 9

edittext.onEditorAction(EditorInfo.IME_ACTION_DONE);
Run Code Online (Sandbox Code Playgroud)

  • 被低估的答案 (2认同)

小智 5

如果问题出在活动上,则只需执行以下操作:

    try {
        InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    } catch (Exception e) {
        // TODO: handle exception
    }
Run Code Online (Sandbox Code Playgroud)

否则,如果片段中需要代码,请执行以下操作

    try {
        InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
    } catch (Exception e) {
        // TODO: handle exception
    }
Run Code Online (Sandbox Code Playgroud)

当在事件块中编写按钮时,这将处理键盘单击或其他任何特定事件时键盘的隐藏。