Android save state on orientation change Android save state on orientation change android android

Android save state on orientation change


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


To save your variable or values you should use onSaveInstanceState(Bundle); and when orientation changes then should recover values should use onRestoreInstanceState() as well, but not very common. (onRestoreInstanceState() is called after onStart(), whereas onCreate() is called before onStart().Use the put methods to store values in onSaveInstanceState()

protected void onSaveInstanceState(Bundle icicle) {  super.onSaveInstanceState(icicle);  icicle.putLong("param", value);}

And restore the values in onCreate():

public void onCreate(Bundle icicle) {  if (icicle != null){    value = icicle.getLong("param");  }}