Permalink
Browse files

Done T06.08_PreferenceSummary

  • Loading branch information...
GinaHsu committed Aug 15, 2017
1 parent 9ec0c8c commit d2cfdb60b0d3c83ef600843b9ee0d4cf9095a12b
@@ -28,7 +28,7 @@
import android.widget.Toast;

// TODO (1) Implement OnSharedPreferenceChangeListener
public class SettingsFragment extends PreferenceFragmentCompat {
public class SettingsFragment extends PreferenceFragmentCompat implements OnSharedPreferenceChangeListener {

@Override
public void onCreatePreferences(Bundle bundle, String s) {
@@ -39,18 +39,62 @@ public void onCreatePreferences(Bundle bundle, String s) {
// 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 (2) Create a setPreferenceSummary which takes a Preference and String value as parameters.
// This method should check if the preference is a ListPreference and, if so, find the label
// associated with the value. You can do this by using the findIndexOfValue and getEntries methods
// of Preference.
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 (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);
}



0 comments on commit d2cfdb6

Please sign in to comment.