Skip to content

Instantly share code, notes, and snippets.

@Pygmalion69
Created April 18, 2018 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Pygmalion69/1febdcde5d487a228a073262a819ffec to your computer and use it in GitHub Desktop.
Save Pygmalion69/1febdcde5d487a228a073262a819ffec to your computer and use it in GitHub Desktop.
/**
* Lock the screen to the current orientation on Android
* https://stackoverflow.com/questions/4553650/how-to-check-device-natural-default-orientation-on-android-i-e-get-landscape
* https://stackoverflow.com/a/14150037/959505
*
*/
private void lockOrientation() {
int orientation = 0;
WindowManager windowService = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
if (windowService != null) {
// Assume phone
int defaultOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
int defaultReverseOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
int otherOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
int otherReverseOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
Configuration config = getResources().getConfiguration();
int rotation = windowService.getDefaultDisplay().getRotation();
if (((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) &&
config.orientation == Configuration.ORIENTATION_LANDSCAPE)
|| ((rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) &&
config.orientation == Configuration.ORIENTATION_PORTRAIT)) {
// We have a landscape device (tablet, TomTom)
defaultOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
defaultReverseOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
otherOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
otherReverseOrientation = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
switch (rotation) {
case Surface.ROTATION_0:
orientation = defaultOrientation;
break;
case Surface.ROTATION_90:
orientation = otherOrientation;
break;
case Surface.ROTATION_180:
orientation = defaultReverseOrientation;
break;
case Surface.ROTATION_270:
orientation = otherReverseOrientation;
break;
}
setRequestedOrientation(orientation);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment