萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android EditText 顯示/隱藏軟鍵盤:InputMethodManager 完整控制指南

核心類:InputMethodManager

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

隱藏軟鍵盤

方式一:針對特定 View (推薦)

// 隱藏與 editText 關聯的軟鍵盤
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

方式二:全域隱藏 (當前 Activity 焦點 View)

View currentFocus = getCurrentFocus();
if (currentFocus != null) {
    imm.hideSoftInputFromWindow(currentFocus.getWindowToken(), 0);
}

方式三:觸摸非輸入區域自動隱藏 (DispatchTouchEvent)

@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

editText.requestFocus(); // 必須先獲取焦點
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);

方式二:切換顯示狀態 (Toggle)

imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

監聽軟鍵盤狀態變化

Android 無直接回調,常用方案:

  • WindowInsetsListener (API 20+):`ViewCompat.setOnApplyWindowInsetsListener(root, (v, insets) -> { imeHeight = insets.getSystemWindowInsetBottom(); ... });`
  • 監聽根佈局高度變化:`rootView.getViewTreeObserver().addOnGlobalLayoutListener(() -> { ... })` 比較高度差。
  • 第三方庫:`net.yslibrary.keyboardvisibilityevent:keyboardvisibilityevent`。

常見場景最佳實踐

場景建議做法
進入頁面自動彈出鍵盤`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 常用常數

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                                                         // 無系統鍵盤 (自定義鍵盤用)
copyright © 萬盛學電腦網 all rights reserved