Skip to content

Instantly share code, notes, and snippets.

@code-n-roll
Created June 1, 2020 21:52
Show Gist options
  • Save code-n-roll/2f85899c81bd6e9a8f9e63d1ea4eaafc to your computer and use it in GitHub Desktop.
Save code-n-roll/2f85899c81bd6e9a8f9e63d1ea4eaafc to your computer and use it in GitHub Desktop.
class OrientationManager private constructor(context: Context) : OrientationEventListener(context) {
private var previousAngle = 0
var orientation = 0
private val context: Context = context
private var orientationChangeListener: OrientationChangeListener? = null
override fun onOrientationChanged(orientation: Int) {
if (orientation == -1) return
if (this.orientation == 0) {
this.orientation = context.resources.configuration.orientation
if (orientationChangeListener != null) {
orientationChangeListener!!.onOrientationChanged(this.orientation)
}
}
if (this.orientation == Configuration.ORIENTATION_LANDSCAPE &&
(previousAngle > 10 && orientation <= 10 ||
previousAngle < 350 && previousAngle > 270 && orientation >= 350)
) {
if (orientationChangeListener != null) {
orientationChangeListener!!.onOrientationChanged(Configuration.ORIENTATION_PORTRAIT)
}
this.orientation = Configuration.ORIENTATION_PORTRAIT
}
if (this.orientation == Configuration.ORIENTATION_PORTRAIT &&
(previousAngle < 90 && orientation >= 90 && orientation < 270 ||
previousAngle > 280 && orientation <= 280 && orientation > 180)
) {
if (orientationChangeListener != null) {
orientationChangeListener!!.onOrientationChanged(Configuration.ORIENTATION_LANDSCAPE)
}
this.orientation = Configuration.ORIENTATION_LANDSCAPE
}
previousAngle = orientation
}
fun setOrientationChangedListener(l: OrientationChangeListener?) {
orientationChangeListener = l
}
interface OrientationChangeListener {
fun onOrientationChanged(newOrientation: Int)
}
companion object {
private val TAG = OrientationManager::class.java.name
private var instance: OrientationManager? = null
fun getInstance(context: Context): OrientationManager? {
if (instance == null) {
instance = OrientationManager(context)
}
return instance
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment