我正在开发一个游戏,我编写了所有代码,包括确保更新highscore int的代码。现在我想知道如何用SharedPreferences保存这个int。我是一名初学程序员,所以你能给我一些我必须做的步骤吗?
变量highscore在MainView中,我开始明白你必须在MainActivity中保存带有共享首选项的东西。
答案 0 :(得分:2)
我喜欢创建一个简单的帮助器类来处理值的保存和加载。这样你就可以把所有的钥匙放在一个地方。
public class PreferencesHelper {
private SharedPreferences prefs;
private static final String FILE_NAME = "file_name";
public static final String KEY_HIGH_SCORE = "high_score";
public PreferencesHelper(Context context) {
prefs = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
}
/**
* Save the specified value to the shared preferences
*
* @param key
* The key of the value you wish to load
* @param defValue
* The value to store
*/
public void save(String key, int value) {
prefs.edit().putInt(key, value).commit();
}
/**
* Load the specified value from the shared preferences
*
* @param key
* The key of the value you wish to load
* @param defValue
* The default value that will be returned if nothing is found
*/
public int loadInt(String key, int defValue) {
return prefs.getInt(key, defValue);
}
}
然后,在您的活动中,您只需写下:
PreferencesHelper prefs = new PreferencesHelper(this);
// Save
prefs.save(PreferencesHelper.KEY_HIGH_SCORE, 25000);
//Load
prefs.loadInt(PreferencesHelper.KEY_HIGH_SCORE, 0);