Question

Even if device is rotated, I want my activity to maintain the orientation it was started in, whether it was portrait or landscape. API level 18 introduced android:screenOrientation=”locked” that should do the job: Locks the orientation to its current rotation, whatever that is.

However, I want to support also older OS versions. How can I achieve this?

I'm aware of Lock screen orientation (Android) that discusses locking activity to landscape mode, How do I disable orientation change on Android? that discusses locking activity in portrait mode (that did not work for me at all on Samsung Galaxy S, OS 2.3.3). I'm also aware of advice recommending not to do this.

Was it helpful?

Solution

MainActivity.java:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getResources().getConfiguration().orientation == Configuration. ORIENTATION_LANDSCAPE)
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    else
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // ...
}

I have also modified the manifest file. However, I'm not sure if these changes are needed, at least android:screenOrientation="unspecified" is the default screenOrientation value anyway. AndroidManifest.xml:

<activity android:name="MainActivity"
    android:configChanges="keyboardHidden|orientation|screenSize"
    android:screenOrientation="unspecified" />
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top