Home > Mobile >  How to detect screen rotation without rotating/recreating the activity?
How to detect screen rotation without rotating/recreating the activity?

Time:12-18

I want to be able to detect whether the phone is in landscape or portrait mode, but I don't want my activity and all my buttons to rotate along.

This code detects the rotation, but it also rotates the screen:

Display display = getWindowManager().getDefaultDisplay();
int rotation = display.getRotation();

rotVal.setText("Rotation: "   rotation);

I tried to lock the activity in portrait mode with this in the MainActivity, but then rotation value doesn't change. (Makes sense I guess)

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

I also tried android:screenOrientation="portrait" in the manifest file but the rotVal stays zero.

This answer have a rotating animation, and I don't want that. I want the screen to stay as it is even in landscape mode, no rotating, no animation, etc.

This answer doesn't work. When I rotate the phone, the rotVal stays zero.

Is there a way to detect the orientation without rotating/recreating the layout?

CodePudding user response:

The second Stack Overflow answer you link to will work, but you can't inquire for the orientation like you do.

First, lock the app in portrait mode. The following code should work and does not include all the animation code.

private lateinit var orientationListener: OrientationListener

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // Code here to do Activity-related stuff.

    // Set up a listener to detect orientation changes.
    orientationListener = OrientationListener(this)
}

override fun onStart() {
    orientationListener.enable()
    super.onStart()
}

override fun onStop() {
    orientationListener.disable()
    super.onStop()
}

private class OrientationListener(context: Context?) : OrientationEventListener(context) {
    val ROTATION_O = 1 // portrait
    val ROTATION_90 = 2 // landscape counter-clockwise
    val ROTATION_180 = 3 // portrait inverted
    val ROTATION_270 = 4 // landscape clockwise

    private var rotation = 0
    override fun onOrientationChanged(orientation: Int) {
        if ((orientation < 35 || orientation > 325) && rotation != ROTATION_O) { // PORTRAIT
            rotation = ROTATION_O
        } else if (orientation > 145 && orientation < 215 && rotation != ROTATION_180) { // REVERSE PORTRAIT
            rotation = ROTATION_180
        } else if (orientation > 55 && orientation < 125 && rotation != ROTATION_270) { // REVERSE LANDSCAPE
            rotation = ROTATION_270
        } else if (orientation > 235 && orientation < 305 && rotation != ROTATION_90) { //LANDSCAPE
            rotation = ROTATION_90
        }

        // We'll just display the value, but it should be stashed for further use or acted upon immediately.
        Log.d("Applog", "rotation = $rotation")
    }
}
  • Related