2

Am trying to dynamically update a particular preference screen summary which nest sub options(This preference screen has it's own key name). My goal is that the preference screen summary should be updated by the state of a switch preference in it's sub or nested view. I tried using the guide here How to listen for preference changes within a PreferenceFragment? but this only shows how to dynamically update particular key references.

Any pointers to achieve this implementation for particular preference screen with key name?

Community
  • 1
  • 1
codeFreak
  • 353
  • 1
  • 3
  • 15

1 Answers1

1

You need to cast the newValue to a boolean and set summary as shown in code.

Preference pref = findPreference(getString(R.string.key_of_pref));
PreferenceScreen parent = (PreferenceScreen) sf.findPreference("prefs_root");
pref.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
   @Override
   public boolean onPreferenceChange(Preference preference, Object newValue) {
       boolean newValueBool = (Boolean) newValue;
       parent.setSummary(newValueBool ? "Summary is true" : "Summary is false");                                                  
       ((BaseAdapter) getPreferenceScreen().getRootAdapter()).notifyDataSetChanged();
       // true to update the state of the Preference with the new value
       // in case you want to disallow the change return false
       return true;
  }
});
Bojan Kseneman
  • 15,488
  • 2
  • 54
  • 59
  • It seems you didn't understand my question. Sorry it not clear. My problem is updating a preference screen summary using the state of a switch preference and not updating the switch preference summary @Bojan – codeFreak May 03 '15 at 20:40
  • I have added some code. Use this code inside the **onPreferenceChange** listener – Bojan Kseneman May 03 '15 at 20:47
  • There is no instance of `Parent.setSummary()` inside the `onPreferenceChangeListener` @bojan – codeFreak May 03 '15 at 21:34
  • You need to make a variable outside and then use it inside. `PreferenceScreen parent = (PreferenceScreen) sf.findPreference("prefs_root");` – Bojan Kseneman May 03 '15 at 21:38