在首选项中存储布尔值

Storing booleans in Preferences

我正在努力掌握如何从 LIBGDX 中的首选项中 store/read 布尔值。我使用它们的目的是,如果用户购买了一件商品,那么布尔值应该变为真并存储为真,直到另一个布尔值变为真,然后第一个布尔值将变为假。希望我以一种可以理解的方式表达自己。

这就是我所做的:

他们进行购买并按下按钮进行更改的屏幕:

PurcScreen implements Screen {
changeStone1.addListener(new ChangeListener() {

        @Override
        public void changed(ChangeEvent event, Actor actor) {
            ss.prefs.getBoolean("stone1", true);
            game.setScreen(ss);
        }

    });

这是根据布尔值是否为 true/false:

绘制他们购买的对象的屏幕
MainScreen implements Screen {
public boolean stone1, stone2
public MainScreen {
stone1 = prefs.getBoolean("stone1");
stone2 = prefs.getBoolean("stone2");
if(stone1){
    setStone1();

    }
    if(stone2){
        setStone2();
    }
show() {
if(stone1) {
        setStone2();
        prefs.putBoolean("stone1", true);
        prefs.putBoolean("stone2", false);
}
if(stone2) {
        setStone2();
        prefs.putBoolean("stone1", false);
        prefs.putBoolean("stone2", true);
}
btnSave.addListener(new ChangeListener() {
@override
public void changed(ChangeEvent event, Actor actor) {
prefs.putBoolean("stone1", stone1);
prefs.putBoolean("stone2", stone2);
prefs.flush();
}

使用此代码,不会存储布尔值。 stone2 的 image/object 被绘制。但是当我点击保存按钮并重新进入屏幕时,原来的 stone1 对象又被绘制了。

首先,确保您导入了正确的 .flush 依赖项,Android 和 Java 中都有一个。

尝试 .apply() 而不是 .flush()

文档 here

As SharedPreferences instances are singletons within a process, it's safe to replace any instance of commit() with apply() if you were already ignoring the return value.

Further Reading

从框架中获取你的preferences对象(确保读写时获取相同的名字)

Preferences prefs = Gdx.app.getPreferences("My Preferences");

将布尔值保存到 prefs 对象:

prefs.putBoolean("soundOn", true);
prefs.flush();

从 prefs 对象中读取布尔值:

prefs.getBoolean("soundOn");

参考维基:

https://github.com/libgdx/libgdx/wiki/Preferences