I have a small activity with an EditText and an imageview and a button. When you press the button it launches camera for result, and when it returns it changes the imageview to the picture you’ve just taken.
But when the orientation changes, the imageview resets back to the default one on the layout.
What I tried doing was setting a boolean called custom, and when you take a picture it sets it to true. I overrid onConfigurationChanged() and if custom is set to true I restore the image.
My problem now is the EditText becomes erased — How can I restore the EditText after configuration change? My first attempt was storing it’s content into a String onPause() and then restoring it, but it always comes up blank.
Usually when UI view does not keep its state, first thing to check is that this UI view has id assigned. Without this id views cannot restore their state.
If this doesn’t help, you need to save and restore state yourself. Take a look at Handling Runtime Changes. It pretty much explains what you should do:
You should override
onSaveInstanceState()and save your Acitivity state when its called:And then restore state in
onCreate()oronRestoreInstanceState():If this is still not sufficient, you can override
onRetainNonConfigurationInstance()and return any custom Object that will be passed to new activity object, when its recreated. More details about how to use it can be found in Handling Runtime Changes. But this function is deprecated in Android 3.0+ (specifically forFragmentActivitywhere its final). So this cannot be used together with Fragments (which is fine, they have their mechanism to retain objects accross configuration changes).And final one – never use
android:configChanges. You must have very good reasons to use it, and usually these are performance reasons. It wasn’t meant to be abused the way it is now: just to prevent UI state reset. If this attribute is used, then yes, Activity UI will not be re-set on config change, but Activity state still will be reset when destroyed and re-created later.The documentation explains this option pretty well: