views:

870

answers:

3

How can I check if the Android phone is in Landscape or Portrait?

A: 

You can ask the user ;-)

Martijn Courteaux
That's awful. Almost warrants a downvote :\
Mark
In some comical way, he's right
Mohit Deshpande
+2  A: 

Google is your friend:

/* First, get the Display from the WindowManager */
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();

/* Now we can retrieve all display-related infos */
int width = display.getWidth();
int height = display.getHeight();
int orientation = display.getOrientation();

Or

public int getScreenOrientation()
{
    Display getOrient = getWindowManager().getDefaultDisplay();

    int orientation = getOrient.getOrientation();

    // Sometimes you may get undefined orientation Value is 0
    // simple logic solves the problem compare the screen
    // X,Y Co-ordinates and determine the Orientation in such cases
    if(orientation==Configuration.ORIENTATION_UNDEFINED){

        Configuration config = getResources().getConfiguration();
        orientation = config.orientation;

        if(orientation==Configuration.ORIENTATION_UNDEFINED){
            //if height and widht of screen are equal then
            // it is square orientation
            if(getOrient.getWidth()==getOrient.getHeight()){
                orientation = Configuration.ORIENTATION_SQUARE;
            }else{ //if widht is less than height than it is portrait
                if(getOrient.getWidth() < getOrient.getHeight()){
                    orientation = Configuration.ORIENTATION_PORTRAIT;
                }else{ // if it is not any of the above it will defineitly be landscape
                    orientation = Configuration.ORIENTATION_LANDSCAPE;
                }
            }
        }
    }
    return orientation; // return value 1 is portrait and 2 is Landscape Mode
}
Martijn Courteaux
You could combine the first suggestion into: int orientation = ((WindowManager)getSystemService(WINDOW_SERVICE)).getDefaultDisplay().getOrientation(); It's a little sloppy, but works as well.
Mohit Deshpande
NOOOOOOOOOOOOOOOOO!!!!!!!!!!!!!!!Good ghod NOOOOOOOOOOOO!getResources().getConfiguration().orientationThat is the correct thing to do.The other recommendations here are not at all what you should do.
hackbod
+7  A: 

The current configuration, as used to determine which resources to retrieve etc, as available from the Resources' Configuration object as:

getResources().getConfiguration().orientation

http://developer.android.com/reference/android/content/res/Configuration.html#orientation

hackbod