Skip to content

Instantly share code, notes, and snippets.

@Bradleycorn
Last active January 20, 2019 22:16
Show Gist options
  • Save Bradleycorn/c4d2bfd7fda83d5d61329a4d33f6a9cb to your computer and use it in GitHub Desktop.
Save Bradleycorn/c4d2bfd7fda83d5d61329a4d33f6a9cb to your computer and use it in GitHub Desktop.
class MainActivityViewModel: ViewModel() {
private val orientationHandler = Handler()
private var orientationLock: Int = Configuration.ORIENTATION_UNDEFINED
fun onDeviceOrientationChange(deviceOrientation: Int, activityOrientation: Int?) {
currentOrientation = when (deviceOrientation) {
in 0..20, in 160..200, in 340..359 -> Configuration.ORIENTATION_PORTRAIT
in 70..110, in 250..290 -> Configuration.ORIENTATION_LANDSCAPE
else -> currentOrientation // In between, keep the current orientation
}
if (currentOrientation == orientationLock) {
orientationLock = Configuration.ORIENTATION_UNDEFINED
}
if (orientationLock == Configuration.ORIENTATION_UNDEFINED
&& activityOrientation != currentOrientation) {
//Post a message to set the orientation
orientationHandler.removeCallbacksAndMessages(null)
orientationHandler.postDelayed({ setOrientation() }, 50)
}
}
fun onOrientationForced(orientation: Int) {
orientationLock = orientation
setOrientation(orientation)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment