簡體   English   中英

在android中更改方向時實現數據持久性的最佳方法?

[英]Best to way to implement data persistence when orientation changes in android?

標題基本上是怎么說的。 目前,如果我的應用程序中的方向發生變化,則球會重置為游戲的頂部,但是我希望更改代碼,以便如果用戶更改設備的方向,則球和球拍將停留在同一位置。 我將如何實現? 我會把我的全部放在這兩種方法中嗎?

protected void onSaveInstanceState(Bundle outState) {

super.onSaveInstanceState(outState);
Log.v(TAG,  "onSaveInstanceState");
}

protected void onRestoreInstanceState(Bundle savedInstanceState) {

super.onRestoreInstanceState(savedInstanceState);
Log.v(TAG,  "onRestoreInstanceState");
}

(請注意,我已經在這里未看到的代碼中初始化了TAG的常量)。
(這也是一項活動)

您可以將球和球拍的位置保存在戶外狀態,因此在活動中:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    //If it is an integer
    outState.putInt(TAG, mBallPosition);

    //Or use a serializable if you wish to store an actual object
   outState.putSerializable(TAG, mBallPosition);
}

然后,在您的onCreate方法中,您可以還原狀態:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null) {
        int position = savedInstanceState.getInt(TAG,0);
        //set ball position

        //or get the object back using outstate.getSerializable(TAG) 

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM