[java] Check orientation on Android phone

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

This question is related to java android orientation

The answer is


such this is overlay all phones such as oneplus3

public static boolean isScreenOriatationPortrait(Context context) {
    return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
}

right code as follows:

public static int getRotation(Context context) {
    final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();

    if (rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) {
        return Configuration.ORIENTATION_PORTRAIT;
    }

    if (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) {
        return Configuration.ORIENTATION_LANDSCAPE;
    }

    return -1;
}

I think this code may work after orientation change has take effect

Display getOrient = getWindowManager().getDefaultDisplay();

int orientation = getOrient.getOrientation();

override Activity.onConfigurationChanged(Configuration newConfig) function and use newConfig,orientation if you want to get notified about the new orientation before calling setContentView.


i think using getRotationv() doesn't help because http://developer.android.com/reference/android/view/Display.html#getRotation%28%29 getRotation() Returns the rotation of the screen from its "natural" orientation.

so unless you know the "natural" orientation, rotation is meaningless.

i found an easier way,

  Display display = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
  Point size = new Point();
  display.getSize(size);
  int width = size.x;
  int height = size.y;
  if(width>height)
    // its landscape

please tell me if there is a problem with this someone?


Tested in 2019 on API 28, regardless of the user has set portrait orientation or not, and with minimal code compared to another, outdated answer, the following delivers the correct orientation:

/** @return The {@link Configuration#ORIENTATION_SQUARE}, {@link Configuration#ORIENTATION_PORTRAIT}, {@link Configuration#ORIENTATION_LANDSCAPE} constants based on the current phone screen pixel relations. */
private int getScreenOrientation()
{
    DisplayMetrics dm = context.getResources().getDisplayMetrics(); // Screen rotation effected

    if(dm.widthPixels == dm.heightPixels)
        return Configuration.ORIENTATION_SQUARE;
    else
        return dm.widthPixels < dm.heightPixels ? Configuration.ORIENTATION_PORTRAIT : Configuration.ORIENTATION_LANDSCAPE;
}

It's also worth noting that nowadays, there's less good reason to check for explicit orientation with getResources().getConfiguration().orientation if you're doing so for layout reasons, as Multi-Window Support introduced in Android 7 / API 24+ could mess with your layouts quite a bit in either orientation. Better to consider using <ConstraintLayout>, and alternative layouts dependent on available width or height, along with other tricks for determining which layout is being used, e.g. the presence or not of certain Fragments being attached to your Activity.


Here is code snippet demo how to get screen orientation was recommend by hackbod and Martijn:

? Trigger when change Orientation:

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
        int nCurrentOrientation = _getScreenOrientation();
    _doSomeThingWhenChangeOrientation(nCurrentOrientation);
}

? Get current orientation as hackbod recommend:

private int _getScreenOrientation(){    
    return getResources().getConfiguration().orientation;
}

?There are alternative solution for get current screen orientation ? follow Martijn solution:

private int _getScreenOrientation(){
        Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
        return display.getOrientation();
}

?Note: I was try both implement ? & ?, but on RealDevice (NexusOne SDK 2.3) Orientation it returns the wrong orientation.

?So i recommend to used solution ? to get Screen orientation which have more advantage: clearly, simple and work like a charm.

?Check carefully return of orientation to ensure correct as our expected (May be have limited depend on physical devices specification)

Hope it help,


Check screen orientation in runtime.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();

    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();        
    }
}

Use this way,

    int orientation = getResources().getConfiguration().orientation;
    String Orintaion = "";
    switch (orientation)
    {
        case Configuration.ORIENTATION_UNDEFINED: Orintaion = "Undefined"; break;
        case Configuration.ORIENTATION_LANDSCAPE: Orintaion = "Landscrape"; break;
        case Configuration.ORIENTATION_PORTRAIT:  Orintaion = "Portrait"; break;
        default: Orintaion = "Square";break;
    }

in the String you have the Oriantion


there are many ways to do this , this piece of code works for me

 if (this.getWindow().getWindowManager().getDefaultDisplay()
                .getOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
             // portrait mode
} else if (this.getWindow().getWindowManager().getDefaultDisplay()
                .getOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                      // landscape
        }

A fully way to specify the current orientation of the phone:

public String getRotation(Context context) {
    final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();
    switch (rotation) {
        case Surface.ROTATION_0:
            return "portrait";
        case Surface.ROTATION_90:
            return "landscape";
        case Surface.ROTATION_180:
            return "reverse portrait";
        default:
            return "reverse landscape";
    }
}

Simple and easy :)

  1. Make 2 xml layouts ( i.e Portrait and Landscape )
  2. At java file, write:

    private int intOrientation;
    

    at onCreate method and before setContentView write:

    intOrientation = getResources().getConfiguration().orientation;
    if (intOrientation == Configuration.ORIENTATION_PORTRAIT)
        setContentView(R.layout.activity_main);
    else
        setContentView(R.layout.layout_land);   // I tested it and it works fine.
    

There is one more way of doing it:

public int getOrientation()
{
    if(getResources().getDisplayMetrics().widthPixels>getResources().getDisplayMetrics().heightPixels)
    { 
        Toast t = Toast.makeText(this,"LANDSCAPE",Toast.LENGTH_SHORT);
        t.show();
        return 1;
    }
    else
    {
        Toast t = Toast.makeText(this,"PORTRAIT",Toast.LENGTH_SHORT);
        t.show();
        return 2;
    }       
}

Old post I know. Whatever the orientation may be or is swapped etc. I designed this function that is used to set the device in the right orientation without the need to know how the portrait and landscape features are organised on the device.

   private void initActivityScreenOrientPortrait()
    {
        // Avoid screen rotations (use the manifests android:screenOrientation setting)
        // Set this to nosensor or potrait

        // Set window fullscreen
        this.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        DisplayMetrics metrics = new DisplayMetrics();
        this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

         // Test if it is VISUAL in portrait mode by simply checking it's size
        boolean bIsVisualPortrait = ( metrics.heightPixels >= metrics.widthPixels ); 

        if( !bIsVisualPortrait )
        { 
            // Swap the orientation to match the VISUAL portrait mode
            if( this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT )
             { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
            else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); }
        }
        else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); }

    }

Works like a charm!


The Android SDK can tell you this just fine:

getResources().getConfiguration().orientation

You can use this (based on here) :

public static boolean isPortrait(Activity activity) {
    final int currentOrientation = getCurrentOrientation(activity);
    return currentOrientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT || currentOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
}

public static int getCurrentOrientation(Activity activity) {
    //code based on https://www.captechconsulting.com/blog/eric-miles/programmatically-locking-android-screen-orientation
    final Display display = activity.getWindowManager().getDefaultDisplay();
    final int rotation = display.getRotation();
    final Point size = new Point();
    display.getSize(size);
    int result;
    if (rotation == Surface.ROTATION_0
            || rotation == Surface.ROTATION_180) {
        // if rotation is 0 or 180 and width is greater than height, we have
        // a tablet
        if (size.x > size.y) {
            if (rotation == Surface.ROTATION_0) {
                result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
            }
        } else {
            // we have a phone
            if (rotation == Surface.ROTATION_0) {
                result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
            }
        }
    } else {
        // if rotation is 90 or 270 and width is greater than height, we
        // have a phone
        if (size.x > size.y) {
            if (rotation == Surface.ROTATION_90) {
                result = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
            }
        } else {
            // we have a tablet
            if (rotation == Surface.ROTATION_90) {
                result = ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
            } else {
                result = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            }
        }
    }
    return result;
}

Some time has passed since most of these answers have been posted and some use now deprecated methods and constants.

I've updated Jarek's code to not use these methods and constants anymore:

protected int getScreenOrientation()
{
    Display getOrient = getWindowManager().getDefaultDisplay();
    Point size = new Point();

    getOrient.getSize(size);

    int orientation;
    if (size.x < size.y)
    {
        orientation = Configuration.ORIENTATION_PORTRAIT;
    }
    else
    {
        orientation = Configuration.ORIENTATION_LANDSCAPE;
    }
    return orientation;
}

Note that the mode Configuration.ORIENTATION_SQUARE isn't supported anymore.

I found this to be reliable on all devices I've tested it on in contrast to the method suggesting the usage of getResources().getConfiguration().orientation


Just simple two line code

if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
    // do something in landscape
} else {
    //do in potrait
}

If you use getResources().getConfiguration().orientation on some devices you will get it wrong. We used that approach initially in http://apphance.com. Thanks to remote logging of Apphance we could see it on different devices and we saw that fragmentation plays its role here. I saw weird cases: for example alternating portrait and square(?!) on HTC Desire HD:

CONDITION[17:37:10.345] screen: rotation: 270 orientation: square
CONDITION[17:37:12.774] screen: rotation: 0 orientation: portrait
CONDITION[17:37:15.898] screen: rotation: 90
CONDITION[17:37:21.451] screen: rotation: 0
CONDITION[17:38:42.120] screen: rotation: 270 orientation: square

or not changing orientation at all:

CONDITION[11:34:41.134] screen: rotation: 0
CONDITION[11:35:04.533] screen: rotation: 90
CONDITION[11:35:06.312] screen: rotation: 0
CONDITION[11:35:07.938] screen: rotation: 90
CONDITION[11:35:09.336] screen: rotation: 0

On the other hand, width() and height() is always correct (it is used by window manager, so it should better be). I'd say the best idea is to do the width/height checking ALWAYS. If you think about a moment, this is exactly what you want - to know if width is smaller than height (portrait), the opposite (landscape) or if they are the same (square).

Then it comes down to this simple code:

public int getScreenOrientation()
{
    Display getOrient = getWindowManager().getDefaultDisplay();
    int orientation = Configuration.ORIENTATION_UNDEFINED;
    if(getOrient.getWidth()==getOrient.getHeight()){
        orientation = Configuration.ORIENTATION_SQUARE;
    } else{ 
        if(getOrient.getWidth() < getOrient.getHeight()){
            orientation = Configuration.ORIENTATION_PORTRAIT;
        }else { 
             orientation = Configuration.ORIENTATION_LANDSCAPE;
        }
    }
    return orientation;
}

Use getResources().getConfiguration().orientation it's the right way.

You just have to watch out for different types of landscapes, the landscape that the device normally uses and the other.

Still don't understand how to manage that.


I think this solution easy one

if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
  user_todat_latout = true;
} else {
  user_todat_latout = false;
}

Another way of solving this problem is by not relying on the correct return value from the display but relying on the Android resources resolving.

Create the file layouts.xml in the folders res/values-land and res/values-port with the following content:

res/values-land/layouts.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="is_landscape">true</bool>
</resources>

res/values-port/layouts.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <bool name="is_landscape">false</bool>
</resources>

In your source code you can now access the current orientation as follows:

context.getResources().getBoolean(R.bool.is_landscape)

int ot = getResources().getConfiguration().orientation;
switch(ot)
        {

        case  Configuration.ORIENTATION_LANDSCAPE:

            Log.d("my orient" ,"ORIENTATION_LANDSCAPE");
        break;
        case Configuration.ORIENTATION_PORTRAIT:
            Log.d("my orient" ,"ORIENTATION_PORTRAIT");
            break;

        case Configuration.ORIENTATION_SQUARE:
            Log.d("my orient" ,"ORIENTATION_SQUARE");
            break;
        case Configuration.ORIENTATION_UNDEFINED:
            Log.d("my orient" ,"ORIENTATION_UNDEFINED");
            break;
            default:
            Log.d("my orient", "default val");
            break;
        }

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to orientation

Change Orientation of Bluestack : portrait/landscape mode Detecting iOS orientation change instantly iOS - UIImageView - how to handle UIImage image orientation Force "portrait" orientation mode Android: alternate layout xml for landscape mode Lock screen orientation (Android) How to set Android camera orientation properly? How can I get the current screen orientation? Check orientation on Android phone Set a border around a StackPanel.