Android 点击空白处自动隐藏输入法

来源:互联网 发布:golang生成密钥 编辑:程序博客网 时间:2024/04/29 15:39
方法1: 简单但有时会无效InputMethodManager manager= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);  @Override public boolean onTouchEvent(MotionEvent event) {   // TODO Auto-generated method stub   if(event.getAction() == MotionEvent.ACTION_DOWN){     if(getCurrentFocus()!=null && getCurrentFocus().getWindowToken()!=null){      manager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);     }   }   return super.onTouchEvent(event);  } 方法2: 完美适用activity与fragment // -------------------------------------隐藏输入法-----------------------------------------------------    // 获取点击事件    @Override    public boolean dispatchTouchEvent(MotionEvent ev) {        // TODO Auto-generated method stub        if (ev.getAction() == MotionEvent.ACTION_DOWN) {            View view = getCurrentFocus();            if (isHideInput(view, ev)) {                HideSoftInput(view.getWindowToken());            }        }        return super.dispatchTouchEvent(ev);    }    // 判定是否需要隐藏    private boolean isHideInput(View v, MotionEvent ev) {        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 (ev.getX() > left && ev.getX() < right && ev.getY() > top                    && ev.getY() < bottom) {                return false;            } else {                return true;            }        }        return false;    }    // 隐藏软键盘    private void HideSoftInput(IBinder token) {        if (token != null) {            InputMethodManager manager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);            manager.hideSoftInputFromWindow(token,                    InputMethodManager.HIDE_NOT_ALWAYS);        }    }

亲测,第一种方法,在项目中很少可以有效,大部分情况是无效的,但是选用第二种方法后,全部有效

0 0