在我的新應用中,點擊按鈕時計數器增加。我想用sharedPreferences保存高分,所以分數會保存下來並在下次啓動時顯示。問題是,即使有其他回答的問題,我也沒有真正做到。android - 用sharedPreferences保存int
package com.example.test;
public class MainActivity extends ActionBarActivity {
public int score = 0;
public int highscore = 0;
TextView tvscore;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tvhighscore= (TextView) findViewById(R.id.highscore);
tvscore = (TextView) findViewById(R.id.score);
Button count = (Button) findViewById(R.id.button1);
tvhighscore.setText(String.valueOf(highscore));
SharedPreferences prefs = this.getSharedPreferences("score", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt("score", 0);
editor.commit();
}
public void onClick (View view) {
score++;
tvscore.setText(String.valueOf(score));
SharedPreferences prefs = this.getSharedPreferences("myPrefsKey", Context.MODE_PRIVATE);
int highscore = prefs.getInt("score", 0);
}
}
需要在'SharedPreferences'中點擊按鈕保存評分 –
@яятьянаякомпанияK是正確的。另外請確保您使用共享首選項文件的相同名稱。 –
我是不是使用同一個名字'「得分」'? –