解決onConfigurationChanged不被呼叫

銳湃發表於2015-11-14

onConfigurationChanged 最近一直遇到一個很奇怪的問題。那就是我在AndroidManifest.xml的確設定了android:configChanges="orientation“,在我的Activity裡也重寫了onConfigurationChanged。但是同樣的程式碼 在Android 4.0.3的手機裡就不執行onConfigurationChanged。在Android 2.3裡的手機執行一切正常。好幾次去找原因,都因為自己不夠耐心和仔細,而無功而退。直到今天決定慢悠悠地找,終於在這裡找到了答案。


英文原文如下:


Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must decalare android:configChanges="orientation|screenSize". However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).

(From http://developer.android.com/guide/topics/resources/runtime-changes.html)

TL;DR: add "|screenSize" to configChanges when targeting API level 13+


 

我的翻譯:

 

自從Android 3.2(API 13),screen size也開始跟著裝置的橫豎切換而改變。所以,在AndroidManifest.xml裡設定的MiniSdkVersion和TargetSdkVersion屬性大於等於13的情況下,如果你想阻止程式在執行時重新載入Activity,除了設定”orientation“,你還必須設定"ScreenSize",就像這樣子,android:configChanges="orientation|screenSize"。但是呢,如果你的Target API 級別小於13,你的Activity自己會自動處理這種ScreenSize的變化。如果你的TargetSdkVersion小於13,即使你在Android 3.2或者更高階別的機器上執行程式,它還是會自己去處理ScreenSize的。

更多請參考http://developer.android.com/guide/topics/resources/runtime-changes.html


我的備註:可能翻譯的不好,反正意思就是,如果你的TargetSdk超過12,然後你想在安裝了Android API level 超過12的裝置上使用onConfigurationChanged,你就必須再對應的Activity里加上對應的screenSize。 一句話答案,把

android:configChanges="orientation" 改成android:configChanges="orientation|screenSize" 就OK了。

另外,StackOverFlow真是一個神奇的網站。


轉自:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2012/1106/516.html

相關文章