萬盛學電腦網

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

Android 監聽鍵盤「完成」鍵:OnEditorActionListener 實作

EditText 輸入法右下角「完成/搜尋/前往」等動作鍵,需透過 OnEditorActionListener 攔截處理。

標準實作

editText.setOnEditorActionListener((v, actionId, event) -> {
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        hideSoftInput(); // 隱藏鍵盤
        // 執行業務邏輯:搜尋、提交表單等
        return true; // 表示已消費事件
    }
    return false; // 未處理,傳遞給系統
});

關鍵配置

XML 中為 EditText 設定 imeOptions 指定動作鍵類型:

<EditText
    android:imeOptions="actionDone"        <!-- 顯示「完成」 -->
    android:singleLine="true"
    android:inputType="text" />

常見 imeOptions 值:

  • actionDone:完成
  • actionGo:前往
  • actionSearch:搜尋
  • actionNext:下一個(移至下一個輸入框)
  • actionSend:發送

隱藏鍵盤工具方法

private void hideSoftInput() {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm != null) {
        imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    }
}
copyright © 萬盛學電腦網 all rights reserved