InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
// 隱藏與 editText 關聯的軟鍵盤
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
View currentFocus = getCurrentFocus();
if (currentFocus != null) {
imm.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if (v instanceof EditText) {
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int) ev.getRawX(), (int) ev.getRawY())) {
v.clearFocus(); // 失去焦點
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent(ev);
}
editText.requestFocus(); // 必須先獲取焦點
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
Android 無直接回調,常用方案:
| 場景 | 建議做法 |
|---|---|
| 進入頁面自動彈出鍵盤 | `getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)` 在 Manifest 或 `onCreate` 前設定 |
| 頁面關閉/跳轉前隱藏 | `onPause()` / `onStop()` 中呼叫 `hideSoftInputFromWindow` |
| 點擊空白處收起鍵盤 | 根佈局 `android:focusableInTouchMode="true"` + `dispatchTouchEvent` 判斷 |
| 彈出鍵盤不遮擋輸入框 | Manifest ` |
| 自定義鍵盤 (數字/表情) | `editText.setInputType(InputType.TYPE_NULL)` + 自定義 View 監聽點擊 |
InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD // 密碼
InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL // 數字(含小數)
InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS // Email
InputType.TYPE_NULL // 無系統鍵盤 (自定義鍵盤用)