Android Properties not updating after editing and committing
in the onCreate method of my PreferenceActivity i set some Properties like this:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("pref_mykey", true);
editor.commit();
It seems to work but the View is not updating so when i open the properties the onCreate runs and changes the values. I will then see the "old" values on the Screen until i close and reopen the 开发者_Go百科prefs screen, then i do see the new properties.
I already tried this after the commit:
((BaseAdapter) getPreferenceScreen().getRootAdapter()).notifyDataSetChanged();
But without any effect. I still see the "old" Prefs until i close and reopen the PreferenceActivity .
What am i doing wrong? How can i refresh the PreferenceActivity after setting values in the onCreate method?
Thanks a lot for your help.
This was buggin me all day but finally found a solution.
((ListPreference)getPreferenceScreen().findPreference("key_of_preference_in_xml_file")).setValue(code);
Your example is with a boolean so it'll have to change based on what kind of preference it is. IE: ((CheckBoxPreference)getPreferenceScreen().findPreference("key_of_preference_in_xml_file")).setChecked(true);
If you use a PreferenceFragment than you need to inject the PreferenceScreen in the activity.
public class SettingsActivity extends Activity implements ScanFragment.OnFragmentInteractionListener {
private PreferenceScreen prefScreen;
public void setPreferenceScreen(PreferenceScreen prefScreen){
this.prefScreen = prefScreen;
}
@Override
public void onFragmentInteraction(String scanContent) {
// commiting to editor retrieved from preference manager would not refresh view
EditTextPreference pref = (EditTextPreference)this.prefScreen.findPreference(getString(R.string.preference_url_key));
pref.setText(scanContent);
}
public static class SettingsFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
((SettingsActivity)this.getActivity()).setPreferenceScreen(this.getPreferenceScreen());
}
}
}
精彩评论