Search code examples
androidandroid-fragmentsandroid-preferences

Preferences not showing summary in PreferencesFragment


I have a preferences screen (Fragment) that has some preferences set from an xml file. The only thing i call in the Fragment is addPreferencesFromResource(R.xml.pref_main); in the onCreate method.

Now, everything works well except for the "summary" section in my preferences, for instance if you have an EditTextPreference and you enter some text, that text should be visible under the preference in smaller letters.

I'm using a custom controll for a preference (but it also doesn't work for any of the official Preferences), that extends DialogPreference. If i set the summary like this:

@Override
protected void onDialogClosed(boolean positiveResult) {
    if (positiveResult) {
        setSummary("Some summary");
    }
}

It works but only as long as i dont leave the screen, when i return it's not there anymore. Any ideas?


Solution

  • The preference screen does not automatically display the summary data. You need to do it in code. Here is a code fragment you could use in your onCreate() method. Add it after the call to addPreferencesFromResource(R.xml.pref_main);

    for(int i = 0; i < getPreferenceScreen().getPreferenceCount(); i++) {
        initializeSummary(getPreferenceScreen().getPreference(i));
    }
    

    The initializeSummary() method is like this:

    private void initializeSummary(Preference p)
    {
        if(p instanceof ListPreference) {
            ListPreference listPref = (ListPreference)p;
            p.setSummary(listPref.getEntry());
        }
        if(p instanceof EditTextPreference) {
            EditTextPreference editTextPref = (EditTextPreference)p;
            p.setSummary(editTextPref.getText());
        }
    }