无法从Android共享首选项中检索布尔值

时间:2014-11-19 10:26:10

标签: android boolean sharedpreferences

我正在尝试从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);
        }

    }

为什么会这样?我做错了什么?

2 个答案:

答案 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);