Saving the activity state when rotating the screen

android, java, rotation

Solution

Firstly, you have to override `onConfigurationChanged(Configuration)` within your Activity.

 public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
  }

You also have to edit the appropriate element in your manifest file to include the android:configChanges Just see the code below:

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

I also like Marko's idea but it's simply not efficient. This way, we don't have to call onCreate/onStartup/etc. all the time we do a simple rotate. There is no need to "rebuild" the infrastructure from scratch (e.g. getting Views,..)

Problem

I'm working on an android app, right now I limited the user to only use horizontal view for all activities. I want to be able to give the user the option to rotate the screen, but when I do that, the activity starts from the beginning instead of just staying the same. Any idea how to save the state when rotating the screen?

Original source

Related problems