user3290180
user3290180

Reputation: 4410

Android: How to initialize all summaries in a PreferenceFragment

public class SettingsActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    getFragmentManager().beginTransaction()
            .add(R.id.settingsContainer, new SettingsFragment())
            .commit();
}

public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);
    }

    @Override
    public void onResume() {
        super.onResume();
        getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
    }

    @Override
    public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
        if (key.equals("aKey") {
            Preference pref = findPreference(key);
            pref.setSummary(sharedPreferences.getString(key, ""));
        }
    }
}
}

When the user changes his preferences they are stored and showed by the listener. When the activity is restarted I lost all the summaries, but values are correctly stored because they are retrieved if I click on each preference. I'd like to show what was done before, not default values.

Upvotes: 1

Views: 349

Answers (2)

Oliver Kranz
Oliver Kranz

Reputation: 3841

In your onResume() method after registering the listener just call the listener with every preference key.

 @Override
public void onResume() {
    super.onResume();
    getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
    onSharedPreferenceChanged(getPreferenceScreen().getSharedPreferences(), "your_key");
}

Upvotes: 1

secret08
secret08

Reputation: 48

when the Fragment was created, you call the following method:

addPreferencesFromResource(R.xml.preferences)

the if the xml file preferences content is stationary, and you change another preference file when accept onSharedPreferenceChanged. May you can get values with method getActivity().getSharedPreferences().

Upvotes: 0

Related Questions