2015-05-06 45 views
-1

我已經將共享偏好保存爲高分,我想要在主菜單上顯示高分,並讓它保持在那裏,即使關閉了應用並重新打開它。setText保存的偏好

我已經得到它的工作,以便它在單擊加載高分時將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); 


    } 
+0

只需在'onCreate()'中加載它。你在哪裏初始化'settings'? –

回答

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); 
} 
+0

當我運行與該代碼的應用程序,我不幸的是遊戲開始已停止。 – TheKaiser4

+0

您必須先初始化設置。我編輯了代碼 – RafaelC

+0

以'GameActivity'中的方式初始化'settings'。 – RafaelC