每次在名为 GameActivity 的类中重新创建 Activity 时,我都会尝试存储一个值来记录分数。我将以下代码放入我的 onCreate()
方法中:
SharedPreferences settings = getSharedPreferences("Score", 0);
int lastscore = settings.getInt("Score", 0 );
score=lastscore;
mScoreView.setText("Score: "+ score);
mScoreView
是一个 TextView 对象,每次重新创建 Activity 时都会使用当前分数进行更新,score
是一个实例变量。我有一个在每个游戏结束时弹出的按钮,让用户可以通过重新创建 Activity 来继续玩游戏。这是该按钮的点击监听器:
private class MyButtonListener2 implements OnClickListener {
public void onClick(View v) {
State player = mGameView.getCurrentPlayer();
Bundle myBundle=new Bundle();
firstGame=false;
if (player == State.WIN) {
if(player==State.WIN){
SharedPreferences scoreSaved = getSharedPreferences("Score",0);
SharedPreferences.Editor edit = scoreSaved.edit();
edit.putInt("Score", score++);
edit.commit();
//onCreate(myBundle);
}
else{
myBundle.putInt("score1", 0);
//onCreate(myBundle);
}
GameActivity.this.recreate();
onCreate(myBundle);
}}
每当游戏以人类玩家获胜(State.WIN)结束时,分数就会增加一分。但是,分数无法正确更新。我无法捕获错误
最佳答案
使用:
edit.putInt("Score", ++score);
或
edit.putInt("Score", score + 1);
关于java - SharedPreferences 变量无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11705752/