【问题标题】:How to save your high-score [closed]如何保存你的高分[关闭]
【发布时间】:2013-02-04 18:05:57
【问题描述】:

我想保存我最好的,只有一个高分存档,然后如果游戏开启,则在菜单屏幕上显示它。

像这样:

最佳:积分。

我有我的积分,直到你死为止,但我不知道如何保存它们。我听说过共享偏好。但是有人可以给我举个例子,最好的方法。我有代码检查你的分数是否比最好的高分好,但不知道如何正确保存它们。任何建议或帮助表示赞赏!

【问题讨论】:

  • 如果您听说过 sharedpreferences,那么在这里询问真的比在 Google 上搜索更容易吗?第一页有半打教程。

标签: java android preferences shared save


【解决方案1】:

这是一个非常简单的示例,假设您想从 Activity 存储和加载您的首选项。

将您的值存储在首选项中:

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("best_score", numberOfPoints);
editor.commit();

要加载值:

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
if (sharedPreferences.contains("best_score")) {
    // we have a high score saved, load it...
    int numberOfPoints = sharedPreferences.getInt("best_score", -1);
    // here you'd like to do something with the value, for example display it.
} else {
    // there is no high score value - you should probably hide the "best score" TextView
}

"best_score" 只是您告诉 Android 在其下存储值的键 - 它可以是任何值,但重要的是每次您想要访问/操作相同的值时键都相同 - 在您的案例“最好成绩”。

【讨论】:

    【解决方案2】:

    这里有一篇关于不同存储选项的文章:http://developer.android.com/guide/topics/data/data-storage.html 它还详细描述了 SharedPreferences。

    【讨论】:

      【解决方案3】:

      理想情况下,您应该将高分存储在 SQLite 数据库中。但是 SharedPrefs 选项也是可行的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-11
        • 1970-01-01
        • 2015-12-22
        • 2020-06-07
        • 1970-01-01
        • 1970-01-01
        • 2021-09-14
        • 2012-07-15
        相关资源
        最近更新 更多