Lock screen orientation (Android)

AndroidLayoutOrientation

Android Problem Overview


I'm writing an android application that uses tabs with different contents (activities). In one of these activities, I would like to lock the screen orientation to "Landscape"-mode, but in the other activities, I want the normal orientation (according to sensor).

What I'm doing now is that I'm calling

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

when I switch to the landscape mode activity, and

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

when I switch back to the other activities. However, this doesn't seem to work, the whole application locks up. What is the normal approach to this problem?

Android Solutions


Solution 1 - Android

In the Manifest, you can set the screenOrientation to landscape. It would look something like this in the XML:

<activity android:name="MyActivity"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize">
...
</activity>

Where MyActivity is the one you want to stay in landscape.

The android:configChanges=... line prevents onResume(), onPause() from being called when the screen is rotated. Without this line, the rotation will stay as you requested but the calls will still be made.

Note: keyboardHidden and orientation are required for < Android 3.2 (API level 13), and all three options are required 3.2 or above, not just orientation.

Solution 2 - Android

I had a similar problem.

When I entered

<activity android:name="MyActivity" android:screenOrientation="landscape"></activity>

In the manifest file this caused that activity to display in landscape. However when I returned to previous activities they displayed in lanscape even though they were set to portrait. However by adding

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

immediately after the OnCreate section of the target activity resolved the problem. So I now use both methods.

Solution 3 - Android

inside the Android manifest file of your project, find the activity declaration of whose you want to fix the orientation and add the following piece of code ,

android:screenOrientation="landscape"

for landscape orientation and for portrait add the following code,

android:screenOrientation="portrait"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser573536View Question on Stackoverflow
Solution 1 - AndroidKevin DionView Answer on Stackoverflow
Solution 2 - AndroidAlan CartwrightView Answer on Stackoverflow
Solution 3 - AndroidHjKView Answer on Stackoverflow