强制隐藏软键盘

开发中遇到的有些场景需要去判断软键盘是否显示去决定显示还是隐藏,下面提供一种强制隐藏软件盘的方式


首先在BaseActivity中重写dispatchTouchEvent()方法

1
2
3
4
5
6
7
8
9
10
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (isShouldHideInput(v, ev)) {
hideSoftInput(v.getWindowToken());
}
}
return super.dispatchTouchEvent(ev);
}

isShouldHideInput()方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private boolean isShouldHideInput(View v, MotionEvent event) {
if (v != null && (v instanceof EditText)) {
int[] l = {0, 0};
v.getLocationInWindow(l);
int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left
+ v.getWidth();
if (event.getX() > left && event.getX() < right
&& event.getY() > top && event.getY() < bottom) {

return false;
} else {
return true;
}
}
return false;
}

hideSoftInput()方法

1
2
3
4
5
6
7
private void hideSoftInput(IBinder token) {
if (token != null) {
InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(token,
InputMethodManager.HIDE_NOT_ALWAYS);
}
}