1

所以我试图用 sharedPreferences 保存最高分,但我遇到了麻烦。我不知道如何将其设置为只取最高分并显示它。

我现在所拥有的只会显示玩家收到的当前分数。这是我到目前为止不起作用的内容:

public class GameOptions extends Activity {
int theScore;
TextView highScore;
public static String filename = "MyHighScore";
SharedPreferences spHighScore;
int dataReturned;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.in_game_menu);
    TextView tvTheScore = (TextView) findViewById(R.id.textView2);
    TextView highScore = (TextView) findViewById(R.id.high_score);
    Bundle gotScore = getIntent().getExtras();
    theScore = gotScore.getInt("scoreKey"); 
    //String thisIsTheScoreToDisplay = theScore.toString();
    tvTheScore.setText("SCORE: "+theScore);

    spHighScore = getSharedPreferences(filename, 0);
    SharedPreferences.Editor editor = spHighScore.edit();

    editor.putInt("highScoreKey", theScore);
    editor.commit();

    int dataReturned = spHighScore.getInt("highScoreKey", 0);
    highScore.setText("" + dataReturned);
4

2 回答 2

3

通过这个你可以保存你的分数

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
    SharedPreferences.Editor prefsEditor = myPrefs.edit();
    prefsEditor.putString(MY_SCORE_KEY, HIGHEST_SCORE);
    prefsEditor.commit();

像这样

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
    String highestScore = myPrefs.getString(MY_SCORE_KEY, "nothing");

我希望这能帮到您..

于 2012-03-17T04:14:21.353 回答
2

在保存高分之前,获取保存在首选项中的当前高分并检查它是否低于高分。如果它较少,则将新的保存到共享首选项中,否则将过去的保留为最高。

于 2012-03-17T04:17:06.357 回答