首页 > 技术文章 > android收起软键盘

devli 2016-03-08 10:41 原文


InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if(imm != null){
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
}

扩展
点击文本区之外的地方取消软键盘

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if(ev.getAction() == MotionEvent.ACTION_DOWN){
View v = getCurrentFocus();
if(isShouldHideInput(v, ev)){
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if(imm != null){
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
}
}
return super.dispatchTouchEvent(ev);
}
//必不可少,否则所有的组件都不会有TouchEvent了
if(getWindow().superDispatchTouchEvent(ev)){
return true;
}
return onTouchEvent(ev);
}

//isShoudHideInput(View v,MotionEvent e)方法
public boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] leftTop = { 0, 0 };
//获取输入框当前的location位置
v.getLocationInWindow(leftTop);
int left = leftTop[0];
int top = leftTop[1];
int bottom = top + v.getHeight();
int right = left + v.getWidth();
if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
// 点击的是输入框区域,保留点击EditText的事件
return false;
} else {
return true;
}
}
return false;
}

推荐阅读