共享首选项保存一个 int?

Shared Preferences saving an int?

我在堆栈上看到了这个 Need to save a high score for an Android game

这是它告诉我的

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

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

我在想,"key"应该是highscore所在的字符串吗?并且我命名我的首选项键有什么关系。 谢谢你的时间。

Android 开发人员文档是解决此类问题的绝佳起点。 SharedPreferences 可以在这里找到。 SharedPreferences是一个简单的Key-Value对存储,所以如果你像key"high score"一样把一个int放到你的shared preferences中,那么以后,如果你想得到那个int,你需要使用 prefs.getInt("high score")。为密钥命名并不重要,但使用私有静态最终字符串变量来存储您将定期使用的密钥通常是一种很好的做法。

您可以随意命名字符串。单击 here 获取文档。您可以将其命名为 "foo" 到 "bar" 之间的任何名称。