ffleandro ffleandro - 1 year ago 62
Android Question

Android: Detect Orientation Changed

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

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
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
. 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,


Answer Source

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) {
            } else if(canDismiss(orientation)){

public void onResume(){

public void onPause(){

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);