Is there a way to programmatically lock an app in portrait mode for certain operations, and then resume (and have the app rotate to landscape if the user is holding the device that way) after the operation is complete?
Asked
Active
Viewed 2.9k times
3 Answers
99
Try this:
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//Do your operation
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

OceanBlue
- 9,142
- 21
- 62
- 84
-
1I had to use `SCREEN_ORIENTATION_SENSOR_PORTRAIT` instead of `SCREEN_ORIENTATION_SENSOR`. – Julien Kronegg Nov 08 '13 at 15:00
-
2If the user is holding a tablet in REVERSE_PORTRAIT, this will change the orientation to portrait and then again to the sensor. So I I could get the orientation value using `getResources().getConfiguration().orientation` but it returns 1 for both portrait as well as reverse_portrait.... How can I get the correct orientation? Thanks – AL̲̳I Nov 05 '14 at 12:22
-
2I am now using `orientation = getRequestedOrientation();` which returns the correct orientation value... it might help someone :) – AL̲̳I Nov 05 '14 at 13:25
-
You "unset" an app's orientation preference with `ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED`. `ActivityInfo.SCREEN_ORIENTATION_SENSOR` will override user configuration to prefer the hardware orientation. – Abandoned Cart Feb 28 '20 at 14:09
4
I'm reading into your question a bit, but if the problem you are facing is that the reload of the activity causes problems, you can add in the manifest a line to handle the orientation changes yourself. You'll probably need to do this anyway if you want to do something special for the orientation changes, but perhaps just adding the lines will take care of your problems for you:
<activity android:name=".MyActivity"
android:configChanges="keyboard|keyboardHidden|orientation" />

Micah Hainline
- 14,367
- 9
- 52
- 85
0
Just use this in OnCreate Method of Activity if you want to set Screen only in Portrait
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
If you want only LANDSCAPE so use this line
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
This one Line is Enough
Like this below
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

Rehan Khan
- 1,031
- 13
- 10