添加首选项值

时间:2014-02-19 06:34:42

标签: android sharedpreferences

我想知道如何在Android中添加2个偏好值?即考虑一个有硬币获得生命的游戏,并说用户选择不使用该硬币再次开始游戏。现在让我说他还有更多所以我的问题是如何添加旧的非使用硬币+新获得的硬币?

2 个答案:

答案 0 :(得分:0)

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.edit().putInt("lifecoin", 5).commit();

让我们说用户在这里留下了5个硬币。现在你使用这样的while循环:

int leftovercoin = 0;
try
{
    leftovercoin = prefs.getInt("lifecoin", 0);
}
catch(Exception e)
{
    Log.e("Error while getting shared pref", "Error while getting shared pref", e);
}
//add your new level's coins(5 of them) to the leftovercoins from last stage
leftovercoin = leftovercoin + 5; //here leftovercoin would be 10 because the shared preference has given it a value of 5 at first
while(leftovercoin>0)
{
      //spawn your coins here
      leftovercoin--;
}

答案 1 :(得分:0)

您可以将SharedPreferences用作

要写入共享首选项,请使用:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();

要从共享首选项中阅读,请使用:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);