Android 隐藏软键盘

275 阅读1分钟
    public void hideSoftInput(EditText etLabelno) {
        if (android.os.Build.VERSION.SDK_INT <= 10) {
            etLabelno.setInputType(InputType.TYPE_NULL);
        } else {
            BaseActivity.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            try {
                Class<EditText> cls = EditText.class;
                Method setSoftInputShownOnFocus;
                setSoftInputShownOnFocus = cls.getMethod("setShowSoftInputOnFocus", boolean.class);
                setSoftInputShownOnFocus.setAccessible(true);
                setSoftInputShownOnFocus.invoke(etLabelno, false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
  /**
   * 点击软键盘外面的区域关闭软键盘
   *
   * @param ev
   * @return
   */
  @Override
  public boolean dispatchTouchEvent(MotionEvent ev) {
      if (ev.getAction() == MotionEvent.ACTION_DOWN) {
          // 获得当前得到焦点的View,一般情况下就是EditText(特殊情况就是轨迹求或者实体案件会移动焦点)
          View v = getCurrentFocus();
          if (isShouldHideInput(v, ev)) {
              hideKeyboard(v.getWindowToken());
          }
      }
      return super.dispatchTouchEvent(ev);
  }

  /**
   * 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘,因为当用户点击EditText时没必要隐藏
   *
   * @param v
   * @param event
   * @return
   */
  private boolean isShouldHideInput(View v, MotionEvent event) {
      if (v != null && (v instanceof EditText)) {
          int[] l = {0, 0};
          v.getLocationInWindow(l);
          int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
                  + v.getWidth();
          if (event.getX() > left && event.getX() < right
                  && event.getY() > top && event.getY() < bottom) {
              // 点击EditText的事件,忽略它。
              return false;
          } else {
              return true;
          }
      }
      // 如果焦点不是EditText则忽略,这个发生在视图刚绘制完,第一个焦点不在EditView上,和用户用轨迹球选择其他的焦点
      return false;
  }

  /**
   * 获取InputMethodManager,隐藏软键盘
   *
   * @param token
   */
  private void hideKeyboard(IBinder token) {
      if (token != null) {
          InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
          im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
      }
  }