Reputation: 42710
I have the following XML.
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="@string/preference_xxx_category">
<CheckBoxPreference
android:title="@string/preference_xxx_dual_mode_title"
android:summary="@string/preference_xxx_dual_mode_summary"
android:key="xxxDualModePreference" />
</PreferenceCategory>
</PreferenceScreen>
I use a GUI to load it as the following code
public class Preferences extends SherlockPreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
this.getPreferenceManager().findPreference("xxxDualModePreference").setDefaultValue(Utils.isDualCoreDevice());
this.getPreferenceManager().findPreference("xxxDualModePreference").setEnabled(Utils.isDualCoreDevice());
// Once the GUI is shown, I realize my preference UI check box is not being ticked.
The default value should depend on the number of device CPU core. That's why I cannot specific the default value in XML.
However, if I specific the default value in Java code, I realize the UI is not reflecting it, although this is the first time I start my application.
Is there any other steps I had missed out?
Thanks.
Upvotes: 2
Views: 1367
Reputation: 45493
I don't think you fully understood what I was trying to say in my comment, so I'll just give an example below. As already pointed out: calling setDefaultValue(...)
will not actually refresh/invalide/update the Preference
.
What (at least I think...) you really after is setting not only the 'enabled' state but also the 'checked' state. Basically you want to grab the value of that preference from the preferences, or use the result from Utils.isDualCoreDevice()
otherwise. That would simply look somewhat like this:
CheckBoxPreference dualCoreModePref = (CheckBoxPreference) getPreferenceManager().findPreference("xxxDualModePreference");
dualCoreModePref.setEnabled(Utils.isDualCoreDevice());
dualCoreModePref.setChecked(getPreferenceManager().getSharedPreferences().getBoolean(dualCoreModePref.getKey(), Utils.isDualCoreDevice()));
The magic is in the last line: retrieve the value for the preference and use the result from the utility method as default. After the initial launch, or if the user changes the setting, the boolean value will get added to the preferences, and thus the default value will not be used anymore.
All that remains is decide for yourself whether you want the checkmark to show up if the device is single-core. Currently it will.
Upvotes: 2