Friday, August 5, 2011

Universal way to detect landscape mode in Android

Hello everybody,

Today I have faced a real challenge how to determinate the screen mode :)

Issue was to detect orientation (Landscape or portrait) for ANY Android device.
Xoom has 0,3 - landscape 1,2 - portrait, Galaxy 1,2 - landscape 0,3 - portrait,
so it is difficult to handle all necessary events for different devices due to theirs default orientation. I didn't find the way to get default orientation, so I have implement a super easy way to detect if we are in Landscape mode:

String private mOrientation = "";
private boolean isDeviceInTheLandscapeMode(Activity acitivity)
{
int width =
acitivity.getWindowManager().getDefaultDisplay().getWidth();
int height =
acitivity.getWindowManager().getDefaultDisplay().getHeight();

boolean isLandscape = width > height;

if(isLandscape)
mOrientation = "(>.>)";
else
mOrientation = "(^.^)";

return isLandscape; // landscape is true
}


Notes:
To retrieve current orientation id, you are able to use:

activity.getWindowManager().getDefaultDisplay().getOrientation()


This function returns 0,1,2 or 3 integers, which are corresponds to the appropriate constants in Surface class:

Surface.ROTATION_90
Surface.ROTATION_0
Surface.ROTATION_180
Surface.ROTATION_270

Happy orientation detection ^__^

Best regards,
Yahor

0 comments:

Post a Comment