Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to listen for preference changes within a PreferenceFragment?
    text
    copied!<p>As described <a href="http://developer.android.com/guide/topics/ui/settings.html#Fragment" rel="noreferrer">here</a>, I am subclassing PreferenceFragment and displaying it inside an Activity. That document explains how to listen for preference changes <a href="http://developer.android.com/guide/topics/ui/settings.html#Listening" rel="noreferrer">here</a>, but only if you subclass PreferenceActivity. Since I'm not doing that, how do I listen for preference changes?</p> <p>I've tried implementing OnSharedPreferenceChangeListener in my PreferenceFragment but it does not seem to work (<code>onSharedPreferenceChanged</code> never seems to get called).</p> <p>This is my code so far:</p> <p><strong>SettingsActivity.java</strong></p> <pre><code>public class SettingsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Display the fragment as the main content. getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit(); } } </code></pre> <p><strong>SettingsFragment.java</strong></p> <pre><code>public class SettingsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener { public static final String KEY_PREF_EXERCISES = "pref_number_of_exercises"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.preferences); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { //IT NEVER GETS IN HERE! if (key.equals(KEY_PREF_EXERCISES)) { // Set summary to be the user-description for the selected value Preference exercisesPref = findPreference(key); exercisesPref.setSummary(sharedPreferences.getString(key, "")); } } } </code></pre> <p><strong>preferences.xml</strong></p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" &gt; &lt;EditTextPreference android:defaultValue="15" android:enabled="true" android:key="pref_number_of_exercises" android:numeric="integer" android:title="Number of exercises" /&gt; &lt;/PreferenceScreen&gt; </code></pre> <p>Also, is the PreferenceFragment even the right place to listen for preference changes or should I do it within the Activity?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload