EditTextPreference 是 Android 偏好設定框架中常用的輸入型組件。當使用者點擊該偏好項目時,系統會彈出一個輸入對話框,讓使用者輸入文字內容。輸入完成後,資料會以字串形式自動儲存在 SharedPreferences 中,無需開發者手動處理儲存邏輯。
在 res/xml/preferences.xml 中定義偏好設定畫面:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="https://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="使用者資訊設定">
<EditTextPreference
android:key="edit_user_name"
android:title="顯示名稱"
android:summary="請輸入您的顯示名稱"
android:defaultValue="未設定"
android:dialogTitle="設定顯示名稱" />
<EditTextPreference
android:key="edit_user_email"
android:title="電子郵件"
android:summary="請輸入您的聯絡信箱"
android:defaultValue=""
android:dialogTitle="設定電子郵件"
android:inputType="textEmailAddress" />
</PreferenceCategory>
</PreferenceScreen>
// 在 Activity 或 Fragment 中讀取值
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String userName = prefs.getString("edit_user_name", "預設值");
// 監聽偏好變更
prefs.registerOnSharedPreferenceChangeListener((sharedPreferences, key) -> {
if ("edit_user_name".equals(key)) {
String newValue = sharedPreferences.getString(key, "");
// 處理變更邏輯,如更新 UI 或同步至伺服器
}
});
若需在使用者輸入時即時驗證或更新摘要,可繼承 EditTextPreference 並覆寫 onBindDialogView() 方法:
public class ValidatedEditTextPreference extends EditTextPreference {
public ValidatedEditTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onBindDialogView(View view) {
super.onBindDialogView(view);
EditText editText = view.findViewById(android.R.id.edit);
if (editText != null) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// 即時驗證邏輯,如啟用/停用確定按鈕
getDialog().getButton(AlertDialog.BUTTON_POSITIVE)
.setEnabled(s.length() >= 3);
}
// 實作 beforeTextChanged, afterTextChanged
});
}
}
}
android:inputType 設定正確,或在 onBindDialogView 中呼叫 editText.requestFocus() 並顯示鍵盤SharedPreferences 使用 XML 格式儲存,特殊字元會自動轉義,讀取時會自動還原android:defaultValue 為字串型別,且未在程式碼中以不同預設值呼叫 getString()EditTextPreference 為簡單文字輸入需求提供了開箱即用的解決方案。搭配 inputType、maxLines 等屬性可滿足大部分表單輸入場景。對於複雜驗證需求,建議自訂對話框或使用 PreferenceDialogFragmentCompat 以獲得更大靈活性。