3

我写了一个简单的 PreferenceScreen,如下所示:

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._%-]+@[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))
4

1 回答 1

4

我有同样的问题。我试图设置一个 onPreferenceChangeListener 但那是错误的。我真正需要的是一个 onSharedPreferenceListener。

OnSharedPreferenceChangeListener listener;

在 Preference 活动的 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);
于 2012-09-07T21:42:25.367 回答