我不明白爲什麼我的複選框首選項未保存或未正確讀取。我有下面的代碼在AndroidManifest.xml:SharedPreferences不保存/持續
<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 /價值/ 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: {}
不管複選框是否被選中與否。
太好了。非常感謝@yoah。非常簡單明確的答案。儘管com.projname.Preferences這個名稱不會讀取同一個首選項文件有點奇怪...... – Chris