隐藏软键盘的方法:
public static Boolean hideInputMethod(Context context, View v) {
InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
return imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
return false;
}
判断当前点击屏幕的地方是否是软键盘:
public static boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] leftTop = { 0, 0 };
v.getLocationInWindow(leftTop);
int left = leftTop[0], top = leftTop[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;
}
}
return false;
}
覆写activity的点击事件的分发方法dispatchTouchEvent:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideInput(v, ev)) {
if(hideInputMethod(this, v)) {
return true; //隐藏键盘时,其他控件不响应点击事件==》注释则不拦截点击事件
}
}
}
return super.dispatchTouchEvent(ev);
}