2011-11-16 47 views
1

我寫了一個簡單PreferenceScreen,如下所示:的Android PreferenceScreen onChangeListener不調用

public class SettingsActivity extends PreferenceActivity implements OnPreferenceChangeListener { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    addPreferencesFromResource(R.xml.settings); 

    PreferenceScreen prefScreen = getPreferenceScreen(); 
    prefScreen.setOnPreferenceChangeListener(this); 

} 

@Override 
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { 
    if (preference.getTitle().equals(getString(R.string.settings_diverse_about))) { 
     // TODO open about dialog 
    } 

    return super.onPreferenceTreeClick(preferenceScreen, preference); 
} 

private static String PATTERN_EMAIL = "[A-Z0-9._%-][email protected][A-Z0-9.-]+\\.[A-Z]{2,4}"; 
private static String PATTERN_TWITTER = "[a-zA-Z0-9_-]+"; 

@Override 
public boolean onPreferenceChange(Preference preference, Object newValue) { 
    String prefTitle = preference.getTitle().toString(); 

    // phone will be fully handled by inputType 

    String newStr = newValue.toString(); 

    if (prefTitle.equals(getString(R.string.settings_contact_email))) { 
     return newStr.trim().matches(PATTERN_EMAIL); 
    } else if (prefTitle.equals(getString(R.string.settings_contact_twitter))) { 
     return newStr.trim().matches(PATTERN_TWITTER); 
    } 

    return true; 
} 

的問題是,該onPreferenceChange方法被調用永遠不會。此外,您如何看待驗證屬性的方式? 我認爲這不是最佳選擇。

preference.getTitle().equals(getString(R.string.settings_diverse_about)) 

回答

3

我有同樣的問題。我試圖設置一個onPreferenceChangeListener,但那是錯誤的。我真正需要的是一個onSharedPreferenceListener。您喜歡活動的

OnSharedPreferenceChangeListener listener; 

寫在OnCreate():

listener = new SharedPreferences.OnSharedPreferenceChangeListener() { 
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) { 
     // Here you can work. 
     // IMPORTANT: Beware that at this point the preference has already been changed! 
    } 
}; 

SharedPreferences prefs = getSharedPreferences(getPackageName() + "_preferences", MODE_PRIVATE); 
prefs.registerOnSharedPreferenceChangeListener(listener);