需要为Android游戏保存高分

Ziz*_*o47 15 java android

这很简单,我需要做的就是为游戏保存一个高分(整数).我假设最简单的方法是将它存储在一个文本文件中,但我真的不知道如何去做.

dym*_*meh 40

如果你只需要存储一个整数,那么SharedPreferences最适合你使用:

//setting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt("key", score);
editor.commit();
Run Code Online (Sandbox Code Playgroud)

要获得偏好:

//getting preferences
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int score = prefs.getInt("key", 0); //0 is the default value
Run Code Online (Sandbox Code Playgroud)

当然,用"key"你的高分值的关键替换"myPrefsKey"你的偏好键(这些可以是任何东西.将它们设置为可识别和独特的东西是好的).

  • 是的,此数据在您的应用运行之间仍然存在.只需确保调用commit(); 在编辑器上为他们保存! (2认同)