github:
* Reference: Udacity Nanodegree Program- Become an Android Developer *
- Implement OnSharedPreferenceChangeListener.
- Create a setPreferenceSummary which takes a Preference and String value as parameters.
- In onCreatePreferences, get the preference screen, get the number of preferences and iterate through all of the preferences if it is not a checkbox preference, call the setSummary method passing in a preference and the value of the preference.
- Override onSharedPreferenceChanged and, if it is not a checkbox preference, call setPreferenceSummary on the changed preference.
- Register and unregister the OnSharedPreferenceChange listener, in onCreate and onDestroy respectively.
// TODO (1) Implement OnSharedPreferenceChangeListener public class SettingsFragment extends PreferenceFragmentCompat implements OnSharedPreferenceChangeListener
TODO (2) Create a setPreferenceSummary.
This method should check if the preference is a ListPreference and, if so, find the label associated with the value.
public void setPreferenceSummary(Preference preference, String value){
if(preference instanceof ListPreference){
ListPreference listPreference = (ListPreference)preference;
int prefIndex = listPreference.findIndexOfValue(value);
if(prefIndex >= 0){
listPreference.setSummary(listPreference.getEntries()[prefIndex]);
}
}
}
// TODO (3) Get the preference screen, get the number of preferences and iterate through
// all of the preferences if it is not a checkbox preference, call the setSummary method
// passing in a preference and the value of the preference
SharedPreferences sharedPreferences = getPreferenceScreen().getSharedPreferences();
PreferenceScreen preferenceScreen = getPreferenceScreen();
int count = preferenceScreen.getPreferenceCount();
for(int i=0 ; i< count; i++){
Preference preference = preferenceScreen.getPreference(i);
if(!(preference instanceof CheckBoxPreference)){
String value = sharedPreferences.getString(preference.getKey(),"");
setPreferenceSummary(preference, value);
}
}
// TODO (4) Override onSharedPreferenceChanged and, if it is not a checkbox preference,
// call setPreferenceSummary on the changed preference
@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
Preference preference = findPreference(key);
if(preference != null){
if(!(preference instanceof CheckBoxPreference)){
String value = sharedPreferences.getString(preference.getKey(), "");
setPreferenceSummary(preference, value);
}
}
}
// TODO (5) Register and unregister the OnSharedPreferenceChange listener (this class) in
// onCreate and onDestroy respectively.
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);
}
public void onDestroy(){
super.onDestroy();
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
}
