Android PreferenceScreen onChangeListener not invoked

佐手、 提交于 2019-12-24 10:55:15

问题


i wrote a simple PreferenceScreen, looks as follows:

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;
}

The problem is, the onPreferenceChange method gets never invoked. Furthermore, what do you think about the way of validating the attributes? I think it's not really optimal.

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

回答1:


I had the same problem. I tried to set up a onPreferenceChangeListener but that was wrong. What I really needed was an onSharedPreferenceListener.

OnSharedPreferenceChangeListener listener;

Write this in the onCreate() of your Preference activity:

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);


来源:https://stackoverflow.com/questions/8157217/android-preferencescreen-onchangelistener-not-invoked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!