主要原理:在baseactivity中重写dispatchTouchEvent时间,拦截用户点击区域,获取当前焦点所在控件,如果该控件是edittextview并且,点击点在该控件区域外,就隐藏掉键盘,提升用户体验
@Override public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideInput(v, ev)) {
InputMethodManager imm =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
return super.dispatchTouchEvent(ev);
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
public boolean isShouldHideInput(View view, MotionEvent event) {
if ((view instanceof EditText)) {
int[] leftTop = { 0, 0 };
view.getLocationInWindow(leftTop);
int left = leftTop[