2013-08-20 19 views
0

这是怎么回事我正在开发Android游戏,我有一个问题,我没有在互联网上找到我想要保存高分与共享喜好,那就是代码:Android保存得分

Play Class : 
     SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE); 
     Editor edit = prefs.edit(); 
     edit.putInt("key", score); 
     edit.commit(); 
     Toast.makeText(getApplicationContext(), "SAVED", Toast.LENGTH_LONG).show(); 

     Intent it = new Intent(getApplicationContext(),HighScore.class); 
     startActivity(it); 

这是高分榜代码:

highscore = (TextView) findViewById(R.id.highscore_int); 
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", 
                Context.MODE_PRIVATE); 
int score = prefs.getInt("key", 0); //0 is the default value 
highscore.setText(""+score); 

这工作不错,但它保存了所有的分数,甚至它比以前的要小。只有比以前更大的分数才能保存分数。我怎样才能做到这一点? PS:对不起,我的英语,我不知道如何突出代码:(

+2

你跑,你不能在互联网上发现一个问题 - 你尝试搜索“如何确定哪个数字是两者中较大的一个?”,因为这就是你需要做的事情,请检查当前分数与共享偏好分数之间的差距,然后选择较大的分数 – Shark

+0

是的,但是如何检查以前的数字I用一个名字保存分数 – Developer

+1

首先比较分数如果新分数大于保存的分数,则更改它;否则什么都不做 – Tugrul

回答

8
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE); 
int oldScore = prefs.getInt("key", 0); 
if(newScore > oldScore){ 
    Editor edit = prefs.edit(); 
    edit.putInt("key", newScore); 
    edit.commit(); 
} 

看到

+0

作品很好,非常感谢你 – Developer