如何在我的游戏中实现SharedPreferences

时间:2017-02-25 13:43:22

标签: java android sharedpreferences

在我的GamePanel.java类中,我有一个整数" best"这意味着记录游戏的最高分。但每次我关闭并重新打开我的游戏时,该值将重置为零。 我不知道如何在我的游戏中实现SharedPreferences。这是我的 GamePanel.Java的相关部分

public class GamePanel extends GLSurfaceView implements SurfaceHolder.Callback
{
private int best;

public void update() {

if(player.getScore()>best) {
        best = player.getScore();
    }
}
}
public void drawText(Canvas canvas)
{
    Paint paint = new Paint();
    paint.setColor(Color.rgb(255,211,38));
    paint.setTextSize(15);
    paint.setTypeface(Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD));
    canvas.drawText("FUEL: " + distance, 10, HEIGHT - 10, paint);
    canvas.drawText("BEST: " + best, WIDTH - 215, HEIGHT - 10, paint);
    canvas.drawText("SCORE: " + player.getScore(), 350, HEIGHT - 10, paint);

如何使用SharedPreferences保存int" best"?

2 个答案:

答案 0 :(得分:4)

您可以使用setBestScore()和getBestScore()分别保存并从共享偏好中获得最佳分数。

private void setBestScore(int bestScore) {
    SharedPreferences.Editor editor = getContext().getSharedPreferences("gamepanel", MODE_PRIVATE).edit();
    editor.putInt("bestScore", bestScore);
    editor.apply();
}

private int getBestScore() {
    SharedPreferences prefs = getContext().getSharedPreferences("gamepanel", MODE_PRIVATE);
    return prefs.getInt("bestScore", 0);
}

在update()

if(player.getScore() > getBestScore()) {
    setBestScore(player.getScore());
}

第一次玩游戏时,你必须保存最佳分数。

答案 1 :(得分:0)

在偏好设置中设置值:

public void update() 
{
    String MY_PREFS_NAME = "best_score";

    if(player.getScore()>best) 
    {
        best = player.getScore();

        SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
        editor.putString("best", ""+best);
        editor.apply();
    }
}

从偏好中检索数据:

public String getBestScore()
{
    String MY_PREFS_NAME = "best_score";

    SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
    String bestScore = prefs.getString("best", "");

    return bestScore;
}

更多信息:

<强> Using Shared Preferences

<强> Shared Preferences