Vérifier l'orientation sur Android phone

Comment puis-je vérifier si le téléphone Android est en paysage ou Portrait?

349
demandé sur Mohit Deshpande 2010-05-09 02:10:24

21 réponses

la configuration actuelle, telle qu'elle est utilisée pour déterminer quelles ressources extraire, est disponible à partir des ressources' Configuration objet:

getResources().getConfiguration().orientation

Vous pouvez vérifier l'orientation en regardant sa valeur:

int orientation = getResources().getConfiguration().orientation
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
    // In landscape
} else {
    // In portrait
}

plus d'informations peuvent être trouvées dans le Android Developer docs .

571
répondu hackbod 2018-08-25 06:58:32

si vous utilisez getResources().getConfiguration ().orientation sur certains appareils, vous vous trompez. Nous avons utilisé cette approche au départ dans http://apphance.com . Grâce à l'enregistrement à distance des apparences, nous avons pu le voir sur différents appareils et nous avons vu que la fragmentation joue son rôle ici. J'ai vu des cas bizarres: par exemple l'alternance de portrait et de carré(?!) sur 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

ou ne changeant pas du tout d'orientation:

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

d'un autre côté, width() et height() est toujours correct (il est utilisé par window manager, donc il vaut mieux qu'il le soit). Je dirais que la meilleure idée est de toujours vérifier la largeur/hauteur. Si vous pensez à un moment, c'est exactement ce que vous voulez - savoir si la largeur est plus petite que la hauteur (portrait), l'opposé (paysage) ou si elles sont identiques (carré).

alors il s'agit de ce code simple:

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;
}
167
répondu Jarek Potiuk 2011-06-30 13:10:46

une autre façon de résoudre ce problème est de ne pas compter sur la valeur de retour correcte de l'affichage, mais en se basant sur les ressources Android résoudre.

créer le fichier layouts.xml dans les dossiers res/values-land et res/values-port avec le contenu suivant:

res/values-terre/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>

Dans votre code source, vous pouvez maintenant accéder à l'orientation actuelle comme suit:

context.getResources().getBoolean(R.bool.is_landscape)
50
répondu Paul 2013-02-18 04:12:33

entièrement manière de spécifier l'orientation actuelle du télé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";
            }
        }

Chear Binh Nguyen

46
répondu Nguyen Minh Binh 2012-10-18 02:22:47

voici code snippet demo comment obtenir l'orientation de l'écran a été recommandé par hackbod et Martijn :

risque de déclenchement en cas de changement d'Orientation:

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

acheter orientation actuelle comme hackbod recommander:

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

il y a une solution alternative pour obtenir l'orientation de l'écran actuelle "follow Martijn solution:

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

փ Note : J'ai été essayer à la fois mettre en œuvre փ & փ, mais sur Realdevice (NexusOne SDK 2.3) Orientation il renvoie la mauvaise orientation.

escape So I recommander à la solution utilisée Escape pour obtenir l'orientation de L'écran qui ont plus d'avantage: clair, simple et travailler comme un charme.

vérifier soigneusement le retour de l'orientation pour s'assurer qu'elle est correcte comme prévu (peut-être limitée dépendent de physique des dispositifs de spécification)

Espère que ça aide,

26
répondu NguyenDat 2017-05-23 12:03:08
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;
        }
16
répondu anshul 2011-07-22 15:23:24

Utiliser getResources().getConfiguration().orientation c'est de la bonne manière.

il suffit de faire attention aux différents types de paysages, le paysage que l'appareil utilise normalement et l'autre.

ne comprend toujours pas comment gérer cela.

13
répondu neteinstein 2016-11-25 02:46:00

un certain temps s'est écoulé depuis que la plupart de ces réponses ont été affichées et que certaines utilisent maintenant des méthodes et des constantes dépréciées.

j'ai mis à jour le code de Jarek de ne plus utiliser ces méthodes et constantes:

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

notez que le mode Configuration.ORIENTATION_SQUARE n'est plus supporté.

j'ai trouvé cela fiable sur tous les appareils que je l'ai testé sur en contraste avec la méthode suggérant l'utilisation de getResources().getConfiguration().orientation

11
répondu Baz 2017-05-23 12:34:41

vérifier l'orientation de l'écran à l'exécution.

@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();        
    }
}
6
répondu Kumar 2016-07-26 06:27:31

il y a une autre façon de le faire:

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;
    }       
}
5
répondu maximus 2011-11-18 06:08:23

le SDK Android peut vous dire très bien:

getResources().getConfiguration().orientation
4
répondu Single 'n Looking 2012-05-31 16:56:20

je pense que ce code peut fonctionner après le changement d'orientation a prendre effet

Display getOrient = getWindowManager().getDefaultDisplay();

int orientation = getOrient.getOrientation();

remplacer Activité.onConfigurationChanged (Configuration newConfig) et utilisez newConfig,orientation si vous voulez être informé de la nouvelle orientation avant d'appeler setContentView.

2
répondu Daniel 2011-11-26 17:54:48

je pense que l'utilisation de getRotationv () n'aide pas parce que http://developer.android.com/reference/android/view/Display.html#getRotation%28%29 getRotation () renvoie la rotation de l'écran de son orientation "naturelle".

donc à moins de connaître l'orientation" naturelle", la rotation n'a pas de sens.

j'ai trouvé un moyen plus facile,

  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

s'il vous plaît dites-moi s'il y a un problème avec ceci quelqu'un?

2
répondu steveh 2013-01-17 09:51:41

Vieux post, je sais. Quelle que soit l'orientation choisie ou changée, etc. J'ai conçu cette fonction est utilisée pour régler l'appareil dans le bon sens sans le besoin de savoir comment le portrait et les caractéristiques du paysage sont organisées sur l'appareil.

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

    }

Fonctionne comme un charme!

1
répondu Codebeat 2014-03-13 10:24:23

utiliser cette voie,

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

dans la chaîne vous avez L'origine

1
répondu 2015-06-22 18:51:44

il y a plusieurs façons de faire cela , ce morceau de code fonctionne pour moi

 if (this.getWindow().getWindowManager().getDefaultDisplay()
                .getOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
             // portrait mode
} else if (this.getWindow().getWindowManager().getDefaultDisplay()
                .getOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                      // landscape
        }
1
répondu Mehroz Munir 2016-04-18 10:51:42

Simple et facile:)

  1. Make 2 xml layouts ( I. e Portrait et paysage)
  2. au fichier java, écrire:

    private int intOrientation;
    

    à onCreate méthode et avant setContentView écrire:

    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.
    
1
répondu Kerelos 2017-11-22 15:57:11

je pense que cette solution facile

if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
  user_todat_latout = true;
} else {
  user_todat_latout = false;
}
1
répondu Issac Nabil 2017-12-16 04:17:28

tel c'est overlay tous les téléphones tels que oneplus3

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

code de droite comme suit:

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;
    }
1
répondu yueyue_projects 2018-06-01 06:10:08

il est également intéressant de noter que de nos jours, Il ya moins bonne raison de vérifier l'orientation explicite avec getResources().getConfiguration().orientation si vous le faites pour des raisons de mise en page, comme Multi-Window Support introduit dans Android 7 / API 24+ pourrait jouer avec vos layouts un peu dans l'une ou l'autre orientation. Mieux vaut envisager d'utiliser <ConstraintLayout> , et autres dispositions en fonction de la largeur ou de la hauteur disponible , avec d'autres trucs pour déterminer ce qui la disposition est utilisée, par exemple la présence ou non de certains Fragments attachés à votre activité.

0
répondu qix 2018-07-21 14:13:18

dans le fichier D'activité:

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

    private void checkOrientation(Configuration newConfig){
        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Log.d(TAG, "Current Orientation : Landscape");
            // Your magic here for landscape mode          
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            Log.d(TAG, "Current Orientation : Portrait");
            // Your magic here for portrait mode         
        }
    }

et dans le fichier manifeste:

<activity android:name=".ActivityName"
            android:configChanges="orientation|screenSize">

j'espère que ça vous aidera ..!

0
répondu Viral Patel 2018-09-21 06:02:38