I've got an Android application which maintains state regarding distance traveled, time elapsed, etc. This state I can conveniently store in an object and store a reference to that object in the Bundle when Android calls onDestroy() when the user changes the screen orientation, then restore the state in onCreate(Bundle savedBundle). However, I also have some state in the Buttons and EditText objects on the screen that I want to persist through screen orientations. For example, in onStart(Bundle savedBundle) I call:
_timerButton.setBackgroundColor(Color.GREEN);
_pauseButton.setBackgroundColor(Color.YELLOW);
_pauseButton.setEnabled(false);
Then throughout the operation of my app, the colors/enabled status of these buttons will be changed. Is there a more convenient way to persist the state of user interface items (EditText, Button objects, etc) without having to manually save/restore each attribute for each button? It feels really clumsy to have to manually manage this type of state in between screen orientations.
Thanks for any help.
Have you tried using: its work through
<activity name= ".YourActivity" android:configChanges="orientation|screenSize"/>
in Manifest file?
It does not work by default because , when you change the orientation onCreate
will be called again and it redraws your view.
If you write this parameter no need to handle in Activity , the framework will take care of rest of things. It will retain the state of the screen or layout if orientation is changed.
NOTE If you are using a different layout for landscape mode , by adding these parameters the layout for landscape mode will not be called.
Other way and Another way