Android: Detect Orientation Changed

ffleandro picture ffleandro · Nov 23, 2011 · Viewed 38.4k times · Source

I need to detect an orientation change in my application, but I don't want my layout to be changed from portrait to landscape. Currently I'm using the OrientationEventListener however detecting the orientation angle is not enough. I want to detect that the user changed from portrait to landscape or viceversa, and that is not just detecting if the orientation angle is 90 or 270.

I want to do the same detection that the Android does to change the activity's orientantion. I tried overriding onConfigurationChanged and check if orientantion is landscape/portrait, however this still changes my activity layout to landscape.

Is there a way to use onConfigurationChanged but force the layout to stay in portrait?
Is there another way to detect orientantion change without using OrientationEventListener. Ultimately I can implement my own orientation changed algorithm, any ideas on this? It has to be something more complex than if(90-THRESHOLD <= orientation <= 90+THRESHOLD), I want to detect if the user made the complete movement Portrait->Landscape or Landscape->Portrait.

Thanks for the help,
Filipe

Answer

ffleandro picture ffleandro · Nov 24, 2011

Ok, after trying to use the Android API and not being able to do what I need, I implemented my own algorithm and actually it wasn't that complicated: I used a OrientationEventListener, and calculated if the orientation is in the 4 orientation points (in my code I only detect LANDSCAPE_RIGHT and PORTRAIT_UP:

orientationListener = new OrientationEventListener(context, SensorManager.SENSOR_DELAY_UI) {
        public void onOrientationChanged(int orientation) {
            if(canShow(orientation)){
                show();
            } else if(canDismiss(orientation)){
                dismiss();
            }
        }
    };

@Override
public void onResume(){
    super.onResume();
    orientationListener.enable();
}

@Override
public void onPause(){
    super.onPause();
    orientationListener.disable();
}

private boolean isLandscape(int orientation){
        return orientation >= (90 - THRESHOLD) && orientation <= (90 + THRESHOLD);
    }

private boolean isPortrait(int orientation){
    return (orientation >= (360 - THRESHOLD) && orientation <= 360) || (orientation >= 0 && orientation <= THRESHOLD);
}

public boolean canShow(int orientation){
    return !visible && isLandscape(orientation);
}

public boolean canDismiss(int orientation){
    return visible && !dismissing && isPortrait(orientation);
}