How to lock orientation during runtime
Is there a way to lock orientation during runtime? For example I'd like to allow the user to lock the screen to landscape if the user currently in landscape and toggle the menu option.
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
Called on an activity, will lock it to landscape. Look for the other flags in the ActivityInfo class. You can lock it back to portrait or make it sensor/slider driven.
More info here: http://www.devx.com/wireless/Article/40792
Be careful of the difference between what getConfiguration returns and what setRequestedOrientation wants - they are both int, but they are coming from different constant definitions.
Here's how to lock the current orientation, while allowing 180 degree flips
int currentOrientation = getResources().getConfiguration().orientation;
if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
}
else {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
This works on devices with reverse portrait and reverse landscape.
Lock orientation:
int orientation = getActivity().getRequestedOrientation(); int rotation = ((WindowManager) getActivity().getSystemService( Context.WINDOW_SERVICE)).getDefaultDisplay().getRotation(); switch (rotation) { case Surface.ROTATION_0: orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; break; case Surface.ROTATION_90: orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; break; case Surface.ROTATION_180: orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT; break; default: orientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE; break; } getActivity().setRequestedOrientation(orientation);
Unlock orientation:
getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);