2015-06-03 172 views
-5

我看到这个堆栈Need to save a high score for an Android game保存int的共享首选项?

这就是它告诉我

//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 

我在想,应该“键”可以在字符串,其中高分所在?这是否与我命名我的首选项密钥有关? 谢谢你的时间。

+0

是的,关键必须是字符串,名称并不重要 – 3xplore

回答

1

Android Developers文档是一个很好的开始这样的问题的地方。 SharedPreferences可以在这里找到。 SharedPreferences是一个简单的键值对存储,所以如果你把一个int作为你的共享偏好和关键“高分”一样,那么在将来如果你想得到那个int,你需要使用prefs.getInt("high score")。不管你命名什么是你的密钥,但通常使用私有静态最终字符串变量来存储你定期使用的密钥是一种很好的做法。

1

无论你喜欢什么,你都可以命名该字符串。点击here获取文档。你可以将它命名为“foo”到“bar”。