setText为已保存的首选项

时间:2015-05-06 22:21:55

标签: java android sharedpreferences textview

我已经将高分记录保存到共享首选项,我想在主菜单上显示高分并让它保持在那里,即使您关闭应用程序并重新打开它。

我已经让它工作,以便当你点击加载高分时它将textview更改为高分,但我希望它自动完成。

//saving the highscore
public static final String PREFS_NAME = "MyPrefsFile";
    static SharedPreferences settings;
    static SharedPreferences.Editor editor;

// When 'back' button is pressed save the highscore to settings

            editor = settings.edit();// Create a new editor
            editor.putInt("highscore", HighScore); // Storing integer       
            editor.commit();

// When 'Show' button is pressed
    public void showPreferences(View v) {
        int highscore = GameActivity.settings.getInt("highscore", 0);
        Toast.makeText( MainMenu.this,
                    "Your Highscore is: " + highscore,
                Toast.LENGTH_LONG).show();
        tvScore.setText(Integer.toString(highscore));

    }


//current on create

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.game_start);
        tvScore= (TextView) findViewById(R.id.tvGuessGame);


    }

1 个答案:

答案 0 :(得分:1)

onCreate()中,在您定义TextView后,请使用SharedPreferences中的值设置文字。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.game_start);
    tvScore= (TextView) findViewById(R.id.tvGuessGame);
    SharedPreferences settings = getSharedPreferences(....); //
    int highscore = settings.getInt("highscore", 0);
    tvScore.setText(""+highscore);
}