我正在尝试从SharedPreferences
检索布尔值,但布尔值始终为false。
代码:
SharedPreferences prefs;
boolean crosshairIsShown;
...
prefs = getSharedPreferences("Weapon1", MODE_PRIVATE);
crosshairIsShown = prefs.getBoolean("crosshairIsShown", false);
crosshair();
..
crosshair.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (crosshairIsShown == false) {
crosshairIsShown = true;
crosshair1.setVisibility(View.VISIBLE);
crosshair2.setVisibility(View.VISIBLE);
crosshair.setImageResource(R.drawable.crosshair_enabled);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("crosshairIsShown", true);
editor.commit();
} else {
crosshairIsShown = false;
crosshair1.setVisibility(View.INVISIBLE);
crosshair2.setVisibility(View.INVISIBLE);
crosshair.setImageResource(R.drawable.crosshair_disabled);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("crosshairIsShown", false);
editor.commit();
}
}
});
...
private void crosshair() {
if (crosshairIsShown == false) {
crosshair1.setVisibility(View.VISIBLE);
crosshair2.setVisibility(View.VISIBLE);
crosshair.setImageResource(R.drawable.crosshair_enabled);
} else {
crosshair1.setVisibility(View.INVISIBLE);
crosshair2.setVisibility(View.INVISIBLE);
crosshair.setImageResource(R.drawable.crosshair_disabled);
}
}
为什么会这样?我做错了什么?
答案 0 :(得分:1)
使用以下方法:
@Override
public boolean getBooleanValuesFromPreferences(String key) {
boolean data = getPreferences().getBoolean(key, false);
return data;
}
答案 1 :(得分:0)
对此pas“key”和“false”使用getBoolean
boolean flag = getPreferences()。getBoolean(key,false);