Android 强制软键盘关闭

  在Android开发过程中,有时候我们会有强制关闭软键盘的需求。比如说:现在有一个文本编辑框(testEt)和一个按钮(testBtn),我们现在点击文本编辑框testEd,这时会弹出软键盘,然后我们点击按钮testBtn,此时软键盘还是保持了打开的状态...问题来了,我们想要的结果是软键盘消失。(testBtn只是我随便举的一个例子,也可以使别的控件例如下拉框、可点击的图片、自定义空间等等)

  下面提供两种方法解决:

  一、这种方法只是关闭软键盘: 

  在按钮testBtn调用以下方法hideKeyboard():

  private void hideKeyboard() {
    InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm.isActive() && this.getCurrentFocus() != null) {
      if (this.getCurrentFocus().getWindowToken() != null) {
        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
      }
    }
  }

  二、这种方法会线判断软键盘的状态,如果时关闭状态则打开,如果是打开状态则关闭:

  在按钮testBtn调用以下方法hideKeyboard():

  private void hideKeyboard() {
    InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm.isActive()) {
      if (this.getCurrentFocus().getWindowToken() != null) {
        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
      }
    }
  }

 

  

posted @ 2015-06-08 17:34  灯-!等灯!等灯!  阅读(10014)  评论(0编辑  收藏  举报