Based on the following code, can you tell me how to refresh the PreferenceActivity window to show changes in the settings immediately? For example: the user taps the master
If you're targeting API 11 and above, you can use invalidateHeaders
.
From the docs:
Call when you need to change the headers being displayed. Will result in onBuildHeaders() later being called to retrieve the new list.
After fighting this for a day, I figured out this.
This is for multiple levels of preferences.
parent is the preference screen that holds the preference you are trying to update.
Since the settings screen displays as a dialog, you can get the listview from the dialog, then tell it's adapter to update child.
PreferenceScreen parent // The screen holding the child
PreferenceScreen child // The entry changing
child.setSummary(isEnabled?"Enabled":"Not Enabled");
ListView v = (ListView)parent.getDialog().findViewById(android.R.id.list);
BaseAdapter ba = (BaseAdapter)v.getAdapter();
ba.notifyDataSetChanged();
I found R.id.list is not available on older phones but this works
ListAdapter adapter = parent.getRootAdapter();
if (adapter instanceof BaseAdapter) {
((BaseAdapter)adapter).notifyDataSetChanged();
}
Nikolay's answer is correct. I just want to add some code here to illustrate his point more clearly.
private CheckBoxPreference mOn15Past;
private CheckBoxPreference mOn30Past;
private CheckBoxPreference mOn45Past;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
mOn15Past = (CheckBoxPreference) findPreference("ChimeOn15Past");
mOn30Past = (CheckBoxPreference) findPreference("ChimeOn30Past");
mOn45Past = (CheckBoxPreference) findPreference("ChimeOn45Past");
final Preference chimeMaster = findPreference("ChimeMaster");
chimeMaster.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newVal) {
final boolean value = (Boolean) newVal;
mOn15Past.setChecked(value);
mOn30Past.setChecked(value);
mOn45Past.setChecked(value);
return true;
}
});
}
In short, PreferenceActivity
is not designed to refresh its values from the persistent storage once it is started. Instead of using SharedPreferences.Editor
to modify and commit additional changes like you did in your code, it is better to make the changes into the local PreferenceManager
object which will be committed by the PreferenceActivity
in its normal lifecycle.
You can simply call onCreate method. If you want you can call onStart and onResume methods.
onCreate(null);
I have solved my problem with this way.