Search code examples
androidstateondestroyandroid-bundle

Android save state on orientation change


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.


Solution

  • Add android:configChanges in the Manifest file

    <activity 
              name= ".MainActivity" 
              android:configChanges="orientation|screenSize"/>
    

    By default, changing the orientation doesn't work because it makes the onCreate method run again, which redraws the view.

    But if you include this parameter, the framework will keep the screen or layout the same when the orientation changes.

    Refer following official documentation for more info:

    Activity Lifecycle

    Handling configuration changes