2017-04-19 46 views
1

我正在開發一個由MainActivity和GameActivity組成的簡單Android遊戲。在MainActivity用戶可以選擇一些選項,然後開始遊戲使用這些選項/變量(即遊戲模式,遊戲難度等)Android:使用對象來存儲遊戲變量

Intent gameIntent = new Intent(this, GameActivity.class); 
gameIntent.putExtra("gameMode", 3); 
startActivity(gameIntent); 

因爲我有好幾個變量來存儲(26是精確的),並從Java是面向對象的我想過用我自己的遊戲類來存儲和檢索這樣的所有變量:

public class Game implements Parcelable { 

    private int gameMode; 
    private int gameDifficulty; 

    // Constructor 
    public Game(int gameMode, int gameDifficulty) { 
     this.gameMode = gameMode; 
     this.gameDifficulty = gameDifficulty; 
    } 

    // getters and setters here 

} 

,並把這個作爲Parcelable到我的意圖:

Game myGame = new Game(gameMode, gameDifficulty); 
Intent gameIntent = new Intent(this, GameActivity.class); 
gameIntent.putExtra("game", myGame); 
startActivity(gameIntent); 

我的問題是:是使用對象來存儲和傳遞遊戲變量方便還是超過頂部?什麼是最好的方法?我錯過了什麼嗎?先謝謝你!

+1

你還會怎麼做?當然你會使用一個對象。 –

+1

您錯過了Parcel文檔的一部分,它告訴它不是用於持久性存儲......在活動之間傳遞 - 確定,但如果您使用某個持久性存儲,則不能使用Parcel/Parcelable – Selvin

回答

2

當然,在對象中保存設置是很好的方法。如果您有多個依賴於該對象的活動,那麼您應該考慮使用單例緩存它,並將其保存到內部存儲。 如果你有一個活動依賴於設置(就像你的情況那樣),可以使用實現Parcelable的類並通過Intent將該類的實例傳遞給GameActivity。