繁体   English   中英

在重置之前如何保留变量的值?

[英]How to keep thee value of a variable until I reset it?

在我的游戏中,我有4个益智游戏,子游戏。 为每个用户赚取一些积分。 在game1结束后,我将获得的积分设置为public static int pointsGame1变量。 等等其他游戏。 我的主菜单我有一个应该显示总分的方框。 我做这样的事情:

boxTotalPoints.setText("" + pointsGame1 + pointsGame2 + pointsGame3 + pointsGame4);

问题是,当我开始该活动时,我得到0000,导致所有变量的起始值为0。

我遇到的第二个问题是当我完成我的game1时,我将这些点添加到我的totalPoints变量,也就是public static int,如下所示:

Menu.totalPoints =+ pointsGame1;

但是当我玩第二场比赛时,它应该总计我所有的分数并将其显示在mu total box中,但我只能从上次比赛中获得积分。 此外,如果我在第一场比赛中获得60分,它将显示00060。

如何解决这两件事?

在您的活动中使用SharedPreferences

确切地说:使用来自不同活动/服务/意图/ ...的共享首选项,您应该使用模式MODE_MULTI_PROCESS(常量值int = 4)。 如果没有,文件被锁定,只有一个进程可以立即写入!

SharedPreferences preferences = getSharedPreferences("myapp",4);
SharedPreferences.Editor editor = preferences.edit();
int points= pointsGame1 + pointsGame2 + pointsGame3 + pointsGame4;
editor.putInteger("points", points);
editor.commit();

SharedPreferences preferences = getSharedPreferences("myapp",4);
points= preferences.getInteger("points", 0);
points= point+pointsGame1;
SharedPreferences.Editor editor = preferences.edit();
editor.putInteger("points", points);
editor.commit();

任何时候你需要在活动中保持点数使用上面的代码。


然后,当您需要从任何活动/流程中检索点数时:

SharedPreferences preferences = getSharedPreferences("myapp", 4);
points= preferences.getInteger("points", 0);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM