2014-12-22 87 views
0

當方向更改時,我需要停止Activity一次又一次地通過onCreate()爲什麼onCreate方法在每次方向更改時都會運行

添加以下代碼在我AndroidManifest.xml

android:configChanges="orientation|keyboardHidden|screenSize" 

,並添加了方法將Activity,但它仍然通過onCreate()方法每個方向更改時間的推移...

+0

就你而言,你爲什麼需要停止重新創建活動? – hmartinezd

+0

'android:configChanges =「orientation | keyboardHidden | screenSize'這是一個討厭的黑客,請按照下面給出的建議。 – Simon

回答

5

這是正常/正確的行爲。

方向改變您的Activity的佈局,所以它會通過onCreate()再次(實際上是讓你適應你的用戶界面到新的配置 - 肖像是不是風景可言UI/UX明智的)。

儘量不要使用android:configChanges(來自Android Dev Guide);這隻能避免這個問題,是一種壞習慣。

注意:應該避免使用(android:configChanges),並且只能用作最後的手段。請閱讀處理運行時更改以獲取有關如何正確處理由於配置更改而導致的重新啓動的更多信息。

瞭解Android lifecycles and how to save its states(以後恢復它的課程),通過處理runtime changes的正確途徑。

0
One of to stop an Activity from going through onCreate() over and over again when orientation changes, is to set Activity's Orientation 
in AndroidManifest.xml to say, "portrait" using below code. 



<activity 
       android:name="com.example.YourActivity" 
       android:screenOrientation="portrait" 
       android:label="@string/app_name" > 
       <intent-filter> 
        <action android:name="android.intent.action.MAIN" /> 
        <category android:name="android.intent.category.LAUNCHER" /> 
       </intent-filter> 
</activity> 

但是這意味着,您僅限於活動用戶界面僅支持肖像模式,這不是用戶可能會期望的。

如果我們試圖用機器人:configChanges = 「方向|屏幕尺寸」,系統不應該重新創建活動,不包括keyboardHidden

假設您正在開發此應用程序的目標API級別爲13或更高(由minSdkVersion和targetSdkVersion屬性聲明),那麼您還應該聲明「screenSize」配置。

相關問題