Created
April 18, 2018 15:01
-
-
Save Pygmalion69/1febdcde5d487a228a073262a819ffec to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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