Check orientation on Android phone
Rapidly figure out the orientation of an Android phone by querying Configuration.orientation
:
Here, we use the good old switch
statement for readability and directly pull the orientation from the Configuration
class, making sure you can act on orientation-specific behavior in a jiffy.
Supporting dynamic orientation changes
Android allows our apps to become proper yogis, adapting as the things turn around, literally. For dynamically handling orientation changes in your Activity
, we plug an onConfigurationChanged
event listener like so:
Never forget your AndroidManifest.xml
, it needs some love too (and this declaration):
Embracing all orientations with WindowManager
Our trusty friend, WindowManager
, with its handy getRotation
method gives us a precise approach, courteous enough to recognize reverse orientations:
Don't go easy with handling the cases. Remember users are fond of auto-rotation and can do all sorts of acrobatics.
Playing Detective with device physical dimensions
In certain cases, playing Sherlock with your device's screen physical size could help solve the crime of sussing out the orientation:
Though this method gets a bit roundabout, it's a gem when your case involves square or other oddly-shaped displays.
Design considerations for responsiveness
It's the age of "fit to screen". Your screen layouts should not just look pretty but also handle whatever curve orientation changes throw at them.
Using resource qualifiers
Create separate layout files for different orientations. Android will automatically pick the correct one. It's kind of like having two outfits, one for work and one for the gym:
res/layout/main_activity.xml # For portrait: The work outfit
res/layout-land/main_activity.xml # For landscape: The gym attire
Reacting to width and height
In situations where the screen is almost square (like a stubborn sandwich), it's better to go by the dimensions. You can create resource files for specific width and height:
res/layout/main_activity.xml # default
res/layout-w600dp/main_activity.xml # for screens that are wider than 600dp
Considering square screens
Those square screens always want to be special. Here is how to detect them:
Was this article helpful?