未调用Android PreferenceScreen onChangeListener

时间:2011-11-16 19:06:55

标签: android events preferencescreen

我写了一个简单的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))

1 个答案:

答案 0 :(得分: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);