How to set the "summary" attribute of a Preference from its persistent value in Android

0

I am developing the preferences for an Android application, for this I have created the file "preferences.xml" where I set the preferences and its summary from the default value.

<EditTextPreference
    android:key="pref_ciudad"
    android:title="Ciudad"
    android:summary="Cáceres"
    android:selectAllOnFocus="true"
    android:singleLine="true"
    android:defaultValue="Caceres" />

In the fragment of preferences, I have declared a listener that detects that the preference has been changed, updating the summary field and making it persistent.

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key ) {

    if (key.equals(KEY_PREF_CIUDAD)){
        Preference ciudadPref = findPreference( key );
        ciudadPref.setSummary(sharedPreferences.getString(key, ""));
        ciudadPref.setPersistent( true );
    } 
}

The problem arises when returning to the fragment of preferences, which re-executes the onCreate method and fixes the summary with the default value, therefore, it does not correspond to the content of the preference at that moment.

Thank you very much!

    
asked by Juan 20.06.2018 в 19:29
source

1 answer

0

In your onCreate () method of the SettingsFragment class, you need to get a reference to your SharedPreferences and then execute the onSharedPreferenceChanged () method. Your onCreate () should look like this:

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Carga las preferencias desde un XML resource
addPreferencesFromResource(R.xml.preferences);

//si estas usando shared preferences por defecto
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getContext());

onSharedPreferenceChanged(sharedPrefs, getString(R.string.llave1));
onSharedPreferenceChanged(sharedPrefs, getString(R.string.llave2));

}

Where key1 and key 2 are your preference keys (example_text and example_text1 where appropriate) stored in your string file. I had a problem doing this without string references, so I recommend extracting them. I hope it serves you

    
answered by 21.06.2018 / 14:49
source