问题
I'm relatively new to Android but have made quite a few apps over the past year so forgive me.
I know that when you are running an app on a device and change the screen orientation by turning the device the activity that is showing is completely recreated. I go to the youtube app (I am using Nexus 7 w/ Android 4.2.2) and play some video and then flip the screen to change orientation. The video keeps playing and everything is re-sized accordingly... How is this possible if the activity is completely recreated?
Thank you.
回答1:
In your AndroidManifest.xml add, android:configChanges and this would avoid the activity being re-created on orientation change. I hope your landscape and portrait mode has the same layout.
<activity android:label="Your Activity Name"
android:configChanges="keyboardHidden|orientation|screenSize"
android:name="com.yourpackage">
To add more to this, i would suggest you to look at the onPause()
and onResume()
methods and if you are playing with Fragments then have a watch on onSaveInstanceState
and onRetainInstanceState
rather than applying the xml changes as "Activity is destroyed by design."
http://developer.android.com/training/basics/activity-lifecycle/index.html
回答2:
If you are worried about losing the value of local variables within your activity... You could use Singleton Pattern for some of those variables. This not a beautiful solution, but could work.
来源:https://stackoverflow.com/questions/15858027/on-change-screen-orientation-new-activity-created