1 /**
2 * 利用android的事件分发机制,用户在点击除EditText...之外的控件隐藏软键盘输入窗口。
3 */
4 @Override
5 public boolean dispatchTouchEvent(MotionEvent ev)
6 {
7 if(ev.getAction() == MotionEvent.ACTION_DOWN)
8 {
9 View v = getCurrentFocus();
10 if(isShouldHideInput(v,ev)){
11 hideSoftInput(v.getWindowToken());
12 }
13 }
14 return super.dispatchTouchEvent(ev);
15 }
16
17 private boolean isShouldHideInput(View v, MotionEvent ev)
18 {
19 if(v != null && (v instanceof EditText))
20 {
21 int[] l = {0, 0};
22 v.getLocationInWindow(l);
23 int left = l[0], top = l[1], right = left + v.getWidth(), bottom = top + v.getHeight();
24 if(ev.getX() > left && ev.getX() < right && ev.getY() > top && ev.getY() < bottom)
25 {
26 return false;// 忽略
27 }
28 else
29 return true;
30 }
31 return false;
32 }
33 private void hideSoftInput(IBinder token){
34 if(token !=null){
35 InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
36 imm.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
37 }
38 }