简体   繁体   中英

Activity was restored twice when the orientation changes

I am having some problems with an activity of my Android aplication.

I have discovered that my app enters twice in 'onCreateView()' method of this activity when orientation changes, and it is causing me problems. When I click the corresponding button and this activity starts is all ok, but whithin this activity when the orientation changes I have some problems because enters twice, ie activity restarts twice ...

... Does anyone know the behaviour of an activity when orientation changes? Why does this happen?

Thanks so much.

Since onCreateView() is not part of the Activity lifecycle, but rather is part of the Fragment, I would assume you have a fragment somewhere in your activity. Also I would assume you add this fragment manually using FragmentManager and FragmentTransaction . Since Android keeps all the added fragments between orientation changes, it is quite possible that you don't check if your Fragment is already present in this activity, so you add it again which causes additional onCreateView to be called.

If this is the case - you need to check if your savedInstance is null within onCreate . If it is - you add fragment. Otherwise activity is getting restored, so fragment is already there.

A lot of assumptions for the answer, I know. But I'm still mastering my telepathy skills :)

When orientation changes onDestroy() is called, followed by onCreate(). For more : http://developer.android.com/guide/topics/resources/runtime-changes.html

Try to add this in AndroidMainfest.xml in your activity:

android:configChanges="orientation|screenSize|keyboardHidden"

This means not to recreate the activity when orientation changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM