- 一般直接使用如下方式即可
Java代码
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN &&
getCurrentFocus()!=null &&
getCurrentFocus().getWindowToken()!=null ){
InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
return super.onTouchEvent(event);
}
- 如果第一种方法没效果,可以在activity中加入(上面的就不要了)
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN &&
getCurrentFocus()!=null &&
getCurrentFocus().getWindowToken()!=null) {
View v = getCurrentFocus();
if (isShouldHideKeyboard(v, event)) {
hideKeyboard(v.getWindowToken());
}
}
return super.dispatchTouchEvent(event);
}
/**
* 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘,因为当用户点击EditText时则不能隐藏
*/
private boolean isShouldHideKeyboard(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] l = {0, 0};
v.getLocationOnScreen(l);
int left = l[0],
top = l[1],
bottom = top + v.getHeight(),
right = left + v.getWidth();
if (event.getRawX() > left && event.getRawX() < right
&& event.getRawY() > top && event.getRawY() < bottom) {
return false;
} else {
return true;
}
}
return false;
}
/**
* 获取InputMethodManager,隐藏软键盘
*/
private void hideKeyboard(IBinder token) {
if (token != null) {
InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
mInputMethodManager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
}
}