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);
}
}