Skip to content Skip to sidebar Skip to footer

Capture Orientation Change Event Before It Happens

It's simple to lock the orientation to portrait or landscape. or to capture when the sc

Solution 1:

Use this piece of code in onPause() method. When rotatio changes, activty re-coustructs it self which means on-Create is called again and previous activity is finish();

int currentOrientation = getResources().getConfiguration().orientation;
    if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE){
        if (display.getRotation() == Surface.ROTATION_0)
        // play with different angles e.g ROTATION_90, ROTATION_180
    }

So when rotation changes the previous activites's onPause() will be called and at that stage you can decide what you want with new orientation.

Solution 2:

  1. Force the activity to stay in one mode (e.g. landscape) via setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); in onCreate(..)

  2. Attach your own orientation listener,

    orientationEventListener = new OrientationEventListener(this, SensorManager.SENSOR_DELAY_UI) {

    @OverridepublicvoidonOrientationChanged(int orientation) {
                if (Math.abs(orientation - 90) < 30){
                       // your device orientation has changed, you can update UI                        accordingly, (layout won't rotate).
            }
        };
        orientationEventListener.enable();
    

Keep in mind that if you do this you will receive x & y axis of touch events 'inversed' when you discard the configuration change. Also, if you have a navigation bar, it will remain where it is and won't rotate as well!

Post a Comment for "Capture Orientation Change Event Before It Happens"