我正在编写一个程序,需要检查默认首选项设置并做出相应的响应。即使 R.xml.preferences 将 defaultValues 设置为 true,getBoolean 方法也始终返回 false。我测试过
preferences.contains(prefKey)
这已经返回 true。
@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) {
}
}
最佳答案
在设置默认值之前尝试清除您的首选项(在 onCreate 中):
PreferenceManager.getDefaultSharedPreferences(this).edit().clear().commit();
PreferenceManager.setDefaultValues(this, R.xml.preferences, true);
来自PreferenceManager.setDefaultValues()文档:
Note: this will NOT reset preferences back to their default values. For that functionality, use getDefaultSharedPreferences(Context) and clear it followed by a call to this method with this parameter set to true.
关于java - getBoolean 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30989680/