Android的onConfigurationChanged

來源:互聯網
上載者:User

在Android開發中,如果某些事件觸發(例如:旋屏事件),則Activity會重新調用onCreate方法,對Activity重新初始化,這樣不僅效率低,而且會造成資料丟失,解決辦法是重寫onConfigurationChanged方法,並在AndroidManifest.xml中對Activity聲明configChanges,這樣特定事件觸發就會調用onConfigurationChanged方法,而不是onCreate方法重新初始化。


通常在AndroidManifest.xml中指定Activity添加以下代碼:

android:configChanges="orientation|keyboard|keyboardHidden"
這句代碼錶示,當裝置旋轉、顯示鍵盤、隱藏鍵盤時調用Activity的onConfigurationChanged方法,如果這句話不聲明,特定事件觸發的時候則會調用onCreate方法。


下面是一個Demo,測試旋屏的時候資料的變化,用data類比資料。

public class MainActivity extends Activity {private static final String TAG = "TEST";private int data;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Log.i(TAG, "onCreate");}@Overrideprotected void onStart() {// TODO Auto-generated method stubsuper.onStart();data = (int) (Math.random() * 100);Log.i(TAG, "onStart : " + data);}@Overridepublic void onConfigurationChanged(Configuration newConfig) {// TODO Auto-generated method stubsuper.onConfigurationChanged(newConfig);Log.i(TAG, "onConfigurationChanged : " + data);}}


旋屏三次效果:


可見旋屏三次都沒有進入onCreate方法,資料得以保留。

另外需要注意的是onConfigurationChanged()方法中的:super.onConfigurationChanged(newConfig);一定不能省去,否則將引發:android.app.SuperNotCalledException 異常。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.