我正在編寫一個程序,需要檢查默認的首選項設置並作出相應的響應。儘管R.xml.preferences的defaultValues設置爲true,但getBoolean方法始終返回false。我已經測試了 preferences.contains(prefKey)
並且這已經返回true。getBoolean返回false
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fullscreen);
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
populate();
}
public void populate() {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
try {
for (int x = 0; x < 9; x++) {
if (preferences.getBoolean(prefKey, false)){
for (int max = 0; max < 20; max++) {
System.out.println("this ran"+ max + "times at" + i);
}
} else {
for (int max = 0; max < 20; max++) {
System.out.println("this Skipped"+ max + "times at" + i);
}
}
}
} catch (IOException ioe) {
}
}
這工作,任何機會,你可以解釋這背後的推理?以及將readAgain設置爲true? – shores
@shores,我無法爲任何設計此類/方法的人說話,但我的猜測是它與初始化默認值(第一次)和重置默認值(隨後)有關。此外,似乎與默認值是否應覆蓋現有或簡單地「填充」空鍵有關。無論哪種方式,文檔都說這樣做,所以我們只需要遵循他們所說的話。另外,如果我的答案有效,請投票並接受爲正確的答案。 – hungryghost