隐藏软键盘的方法:
- 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) {
-
- 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);
- }
当然还有其他比较笨的方法,比如在屏幕上覆盖一层透明的view,设置其点击事件,但是并不可取,而且使用此方法更加有利于你对view的事件分发机制的了解。
还是那句话,欢迎各位大侠批评指正。