android判斷點選鍵盤外就關閉
阿新 • • 發佈:2020-12-21
宣告Utils類中的方法
public static void hideKeyboard(MotionEvent event, View view, Activity activity) { try { if (view != null && view instanceof EditText) { int[] location = {0, 0}; view.getLocationInWindow(location);int left = location[0], top = location[1], right = left + view.getWidth(), bootom = top + view.getHeight(); // 判斷焦點位置座標是否在空間內,如果位置在控制元件外,則隱藏鍵盤 if (event.getRawX() < left || event.getRawX() > right || event.getY() < top || event.getRawY() > bootom) {// 隱藏鍵盤 IBinder token = view.getWindowToken(); InputMethodManager inputMethodManager = (InputMethodManager) activity .getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS); } } }catch (Exception e) { e.printStackTrace(); } }
實現類中寫明
@Override public boolean dispatchTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: View view = getCurrentFocus(); Utils.hideKeyboard(ev, view, MessageBoardActivity.this);//呼叫方法判斷是否需要隱藏鍵盤 break; default: break; } return super.dispatchTouchEvent(ev); }