需要知道如何使用布尔值来使用SharedPreferences保存和加载可见性

时间:2016-12-16 16:17:41

标签: java android boolean sharedpreferences

我的文字游戏中的代码示例。可选的单选按钮数量随每个选项的变化而变化,如下所示。

然后我展示了游戏保护程序和游戏加载程序。

if (rb1.isChecked() && (x == 1)) {
    t.setText("Inside the toolbox you find a small key and 8 inch metal file with a rounded point "
            + "at the end."
            + "What should I take?");
    rb1.setText("Take the key");
    rb2.setText("Take the file");
    rb3.setText("Take both");
    rb4.setText("Take nothing");
    rb5.setVisibility(View.INVISIBLE);

    SharedPreferences sharedpreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
    SharedPreferences.Editor SharedPreferences sharedpreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
    String name = sharedpreferences.getString("name1", DEFAULT);
    String name2 = sharedpreferences.getString("name2", DEFAULT);
    String name3 = sharedpreferences.getString("name3", DEFAULT);
    String name4 = sharedpreferences.getString("name4", DEFAULT);
    String name5 = sharedpreferences.getString("name5", DEFAULT);

    if (name.equals(DEFAULT)) {
        Toast.makeText(this, "No data was found", Toast.LENGTH_LONG).show();
    } else {
        rb1.setText(name);
        rb2.setText(name2);
        rb3.setText(name3);
        rb4.setText(name4);
        rb5.setText(name5);

    }
    editor sharedpreferences.edit();
    editor.putString("name1", rb1.getText().toString());
    editor.putString("name2", rb2.getText().toString());
    editor.putString("name3", rb3.getText().toString());
    editor.putString("name4", rb4.getText().toString());
    editor.putString("name5", rb5.getText().toString());
    editor.commit();

    SharedPreferences sharedpreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
    String name = sharedpreferences.getString("name1", DEFAULT);
    String name2 = sharedpreferences.getString("name2", DEFAULT);
    String name3 = sharedpreferences.getString("name3", DEFAULT);
    String name4 = sharedpreferences.getString("name4", DEFAULT);
    String name5 = sharedpreferences.getString("name5", DEFAULT);

    if (name.equals(DEFAULT)) {
        Toast.makeText(this, "No data was found", Toast.LENGTH_LONG).show();
    } else {
        rb1.setText(name);
        rb2.setText(name2);
        rb3.setText(name3);
        rb4.setText(name4);
        rb5.setText(name5);

    }
}

1 个答案:

答案 0 :(得分:0)

//set the bool
UserDefaults.standard.set(true, forKey: "visibility")
UserDefaults.standard.synchronize()

//retrieve the bool
if let myBool = UserDefaults.standard.object(forKey: "visibility") as? Bool {
    print(myBool)
}