最近我正在开发一款简单的安卓游戏。对于得分部分,我在许多网站上共享偏好最好保存高分。现在,如果我需要在游戏中保存不同级别的高分怎么办?我希望为每个级别保存前三名得分手......
答案 0 :(得分:3)
要保存您的分数,您可以执行以下操作:
// prepare the data: put the String values of the scores of the first 3 users
// in one String array for each level
String[] firstLevelHighscores = new String[] {
firstUserLevel1Score, secondUserLevel1Score, thirdUserLevel1Score
};
String[] secondLevelHighscores = new String[] {
firstUserLevel2Score, secondUserLevel2Score, thirdUserLevel2Score
};
String[] thirdLevelHighscores = new String[] {
firstUserLevel3Score, secondUserLevel3Score, thirdUserLevel3Score
};
// now save them in SharedPreferences
SharedPreferences sharedPref = getSharedPreferences("LevelScores",
Context.MODE_PRIVATE);
Editor editor = sharedPref.edit();
editor.putStringSet("level1", firstLevelHighscores);
editor.putStringSet("level2", secondLevelHighscores);
editor.putStringSet("level3", thirdLevelHighscores);
请注意,您可以将更多用户的分数放入String数组中。如果您需要为更多级别保存分数,只需创建更多数组。
要从SharedPreferences中检索已保存的数据,请按以下方式执行:
SharedPreferences sharedPref = getSharedPreferences("LevelScores",
Context.MODE_PRIVATE);
String[] firstLevelHighscores = sharedPref.getStringSet("level1", null);
String[] secondLevelHighscores = sharedPref.getStringSet("level2", null);
String[] thirdLevelHighscores = sharedPref.getStringSet("level3", null);
我假设您可以将int
转换为String
,反之亦然。希望它能以这种方式为你服务。
答案 1 :(得分:1)
有很多方法可以将分数保存到SharedPreference
。一切都取决于你的实施方式。
你可以简单地使用putStringSet(key, String[])
,因为键是关卡,而String []是第1,第2和第3位。
答案 2 :(得分:-1)
得分设置
static final String[] LEVEL = {"level1","level2","level3"};
int bestScore1 = 100;
int bestScore2 = 90;
int bestScore3 = 80;
SharedPreferences sp = getSharedPreferences(LEVEL[0],Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("First", bestScore1);
editor.putInt("Second", bestScore2);
editor.putInt("Third", bestScore3);
editor.commit();
但你需要计算LEVEL的索引
得分SharedPreferences sp = getSharedPreferences(LEVEL[0], Activity.MODE_PRIVATE);
bestScore1 = sp.getInt("First", 0);
bestScore2 = sp.getInt("Second", 0);
bestScore3 = sp.getInt("Third", 0);
嗯..但我认为这不是你问题的最佳方式:<