萬盛學電腦網

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

Android EditTextPreference 完整使用指南與最佳實踐

EditTextPreference 組件詳解

EditTextPreference 是 Android 偏好設定框架中常用的輸入型組件。當使用者點擊該偏好項目時,系統會彈出一個輸入對話框,讓使用者輸入文字內容。輸入完成後,資料會以字串形式自動儲存在 SharedPreferences 中,無需開發者手動處理儲存邏輯。

基本 XML 佈局範例

在 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>

核心屬性說明

  • android:key:唯一識別碼,用於在程式碼中讀取儲存值
  • android:title:偏好項目顯示的主標題
  • android:summary:副標題,通常用於提示輸入內容或顯示當前值
  • android:defaultValue:預設值,當使用者尚未輸入時顯示
  • android:dialogTitle:輸入對話框的標題
  • android:inputType:輸入類型(如 textEmailAddress、number、textPassword 等)
  • android:maxLines:最大行數,預設為單行

程式碼中讀取與監聽變更

// 在 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 以獲得更大靈活性。

copyright © 萬盛學電腦網 all rights reserved