Android: manual screen orientation without restarting the activity?

tim picture tim · Mar 26, 2013 · Viewed 10.4k times · Source

I need to make an app playing video with a button for full-screen on the video. The button is used to manually switch between landscape and portrait of the video display. We don't want the auto rotation detect. So the Manifest file is set as below.

<activity
    android:name=".VideoActivity"
    android:screenOrientation="portrait"
    android:configChanges="keyboardHidden"/>

I used

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); or setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);

to manually set the orientation. It works but it restarts the activity - the onCreate() was found called. So the video playback restarts from the beginning unexpectedly. I cannot make it smooth as like as using onConfigurationChanged() - the auto rotation detect method.

So how to make manual screen orientation change without restarting the activity?

Thank you.

Answer

tim picture tim · May 29, 2013

For manaul orientation change:

<activity
    android:name=".VideoDetails"
    android:configChanges="orientation"/>

public class VideoDetails extends Activity {
    ...
    onStart() {
        setRequestedOrientation(orientation);
    }
    onConfigurationChanged(Configuration newConfig){
        // do stuff for orientation change.
    }
    onClick() {
        setRequestedOrientation(orientation);
    }
}

For auto-orientation detect:

<activity
    android:name=".VideoDetails"
    android:configChanges="orientation"/>

public class VideoDetails extends Activity {
    ...
    onConfigurationChanged(Configuration newConfig){
        // do stuff for orientation change.
    }
}