關於Android旋轉螢幕遺失資料的新讀

來源:互聯網
上載者:User

標籤:des   android   style   http   io   ar   color   os   使用   

    根據之前的經驗,一直以為當Android旋轉螢幕的時候會重新調用onCreate(),從而導致介面上所有的資料都會被重設,需要在Manifest中對Activity設定一個屬性才能讓他不重新走onCreate方法。或者很麻煩的需要在 onSaveInstanceState()方法中儲存介面所有資料,然後在onRestoreInstanceState()方法中還原資料才行。

    直到今天看到這樣一句話:

“By default, the system uses the Bundle instance state to save information about each View object in your activity layout (such as the text value entered into an EditText object). So, if your activity instance is destroyed and recreated, the state of the layout is restored to its previous state with no code required by you. However, your activity might have more state information that you‘d like to restore, such as member variables that track the user‘s progress in the activity.”

    預設情況下,系統會使用Bundle來儲存布局中每一個View對象的執行個體狀態(例如寫進EditText中的文字)。因此當你的Activity被銷毀並重建之後,你不需要寫任何代碼就可以實現布局狀態的還原了。然而你的Activity可能有一些其他你需要儲存的資訊,例如儲存使用者當前進度的成員變數值。


    看到這段我感覺很奇怪,與我的經驗不符,而且新寫了一個只有EditText的Demo旋轉螢幕測試了一下,EditText中的文字確實會因為旋轉螢幕而丟失。百思不得其解之下又看到了這句話:

    “Note: In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.“

    Android系統儲存和還原View的狀態必須有一個唯一的ID


    給EditText設定id之後,果然在旋轉螢幕之後資料被自動還原了。

關於Android旋轉螢幕遺失資料的新讀

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.