CheckBoxPreference - onSharedPreferenceChanged method not getting called

删除回忆录丶 提交于 2019-12-24 06:49:09

问题


I have a couple of CheckBoxPreferences set up, my preference class extends PreferenceActivity and implements OnSharedPreferenceChangeListener This is what I'm using to respond to people checking/unchecking the CheckBoxPreferences:

public void onSharedPreferenceChanged(SharedPreferences P, String K) {
    if (K.equals(CheckBoxPref_KEY_HERE)) {
        MyClass.BooleanVariable = P.getBoolean("CheckBoxPref_KEY_HERE", true);
    }
}

As far as I can tell, the onSharedPreferenceChanged method above is never even getting called?


回答1:


checkBoxPreference = (CheckBoxPreference) this.findPreference("CheckBoxPref_KEY_HERE");

checkBoxPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
    @Override
    public boolean onPreferenceChange(Preference preference, Object newValue) {
            // do your work here
            return true;
        }
    });



回答2:


Here is the soln if you want to do something on all the preferences:

Create a class member:

SharedPreferences settings;

in your onCreate method:

settings = getSharedPreferences(<your_pref_name>, 0);
settings.registerOnSharedPreferenceChangeListener(new SharedPreferences.OnSharedPreferenceChangeListener() {
  @Override
  public void onSharedPreferenceChanged (SharedPreferences sharedPreferences, String key) {
    // Do whatever
  }
});


来源:https://stackoverflow.com/questions/8373131/checkboxpreference-onsharedpreferencechanged-method-not-getting-called

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