@@ -30,6 +30,61 @@ public static void hideSoftInput(Context context, EditText edit) {
30
30
}
31
31
```
32
32
33
+ ### 点击屏幕空白区域隐藏软键盘
34
+ ``` java
35
+ // 方法1:在onTouch中处理,未获焦点则隐藏
36
+ /**
37
+ * 在onTouch中处理,未获焦点则隐藏
38
+ */
39
+ @Override
40
+ public boolean onTouchEvent(MotionEvent event) {
41
+ if (null != this . getCurrentFocus()) {
42
+ InputMethodManager mInputMethodManager = (InputMethodManager ) getSystemService(INPUT_METHOD_SERVICE );
43
+ return mInputMethodManager. hideSoftInputFromWindow(this . getCurrentFocus(). getWindowToken(), 0 );
44
+ }
45
+ return super . onTouchEvent(event);
46
+ }
47
+
48
+ // 方法2:根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘,需重写dispatchTouchEvent
49
+ @Override
50
+ public boolean dispatchTouchEvent(MotionEvent ev) {
51
+ if (ev. getAction() == MotionEvent . ACTION_DOWN ) {
52
+ View v = getCurrentFocus();
53
+ if (isShouldHideKeyboard(v, ev)) {
54
+ hideKeyboard(v. getWindowToken());
55
+ }
56
+ }
57
+ return super . dispatchTouchEvent(ev);
58
+ }
59
+
60
+ /**
61
+ * 根据EditText所在坐标和用户点击的坐标相对比,来判断是否隐藏键盘
62
+ */
63
+ private boolean isShouldHideKeyboard(View v, MotionEvent event) {
64
+ if (v != null && (v instanceof EditText )) {
65
+ int [] l = {0 , 0 };
66
+ v. getLocationInWindow(l);
67
+ int left = l[0 ],
68
+ top = l[1 ],
69
+ bottom = top + v. getHeight(),
70
+ right = left + v. getWidth();
71
+ return ! (event. getX() > left && event. getX() < right
72
+ && event. getY() > top && event. getY() < bottom);
73
+ }
74
+ return false ;
75
+ }
76
+
77
+ /**
78
+ * 获取InputMethodManager,隐藏软键盘
79
+ */
80
+ private void hideKeyboard(IBinder token) {
81
+ if (token != null ) {
82
+ InputMethodManager im = (InputMethodManager ) getSystemService(Context . INPUT_METHOD_SERVICE );
83
+ im. hideSoftInputFromWindow(token, InputMethodManager . HIDE_NOT_ALWAYS );
84
+ }
85
+ }
86
+ ```
87
+
33
88
### 动态显示软键盘
34
89
``` java
35
90
/**
0 commit comments