隱藏軟鍵盤的方法:
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的點擊事件的分發(fā)方法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);
}