我不明白为什么我的复选框首选项未保存或未正确读取。我在 AndroidManifest.xml 中有以下代码:
<activity android:name=".Preferences" />
然后在 res/xml/preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Preferences">
<CheckBoxPreference
android:title="Always Run"
android:key="@string/pref_always_run_key"
android:summary="Always run it" />
</PreferenceCategory>
在 res/values/strings.xml
<string name="pref_always_run_key">always_run_default</string>
然后我有一个 src/com.name/Preferences.java 文件
public class Preferences extends PreferenceActivity
{
private static final String LOG_TAG = Preferences.class.getSimpleName() + "_LOG";
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences); //5
//getPreferenceManager().setSharedPreferencesName();
CheckBoxPreference alwaysRunCheckBox = (CheckBoxPreference)findPreference(getString(R.string.pref_always_run_key));// 8
alwaysRunCheckBox.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener()
{
@Override
public boolean onPreferenceChange(Preference preference, Object newValue)
{
Log.d(LOG_TAG, "User set always run to " + newValue.toString().equals("true"));
return true;
}
});
}
}
然后我在 MainActivity.java 中有一个测试按钮
SharedPreferences prefs = MainActivity.this.getSharedPreferences("com.projname.Preferences", Context.MODE_PRIVATE);
String defaultAlwaysRunKey = MainActivity.this.getResources().getString(R.string.pref_always_run_key);
Log.d(LOG_TAG, "Always run key is " + defaultAlwaysRunKey);
boolean run = prefs.getBoolean(defaultAlwaysRunKey, false);
Log.d(LOG_TAG, "It contains the key: " + prefs.contains(defaultAlwaysRunKey));
Log.d(LOG_TAG, "Always run set to " + run);
Log.d(LOG_TAG, "All the preferences saved are: " + prefs.getAll().toString());
输出总是:
10-25 16:15:50.844: D/MainActivity_LOG(1219): Clicked on test...
10-25 16:15:50.844: D/MainActivity_LOG(1219): Always run key is always_run_default
10-25 16:15:50.844: D/MainActivity_LOG(1219): It contains the key: false
10-25 16:15:50.844: D/MainActivity_LOG(1219): Always run set to false
10-25 16:15:50.855: D/MainActivity_LOG(1219): All the preferences saved are: {}
不管复选框是否被选中。