上代码
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
try {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideInput(v, ev) && !isTouchPointInView(clickView, (int) ev.getX(), (int) ev.getY())) {
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;
}
} catch (Exception e) {
e.printStackTrace();
}
return onTouchEvent(ev);
}
public static boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
try {
int[] leftTop = {0, 0};
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) {
return false;
} else {
return true;
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
return false;
}
public static boolean isTouchPointInView(View targetView, int currentX, int currentY) {
try {
if (targetView == null) {
return false;
}
int[] localtion = new int[2];
targetView.getLocationOnScreen(localtion);
int left = localtion[0];
int top = localtion[1];
int right = left + targetView.getMeasuredWidth();
int bottom = top + targetView.getMeasuredHeight();
if (currentY >= top && currentY <= bottom && currentX >= left
&& currentX <= right) {
return true;
}
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}