¿Cómo puedo obtener la orientación actual de la pantalla?


Solo quiero establecer algunas banderas cuando mi orientación está en horizontal para que cuando la actividad se recrea en onCreate() pueda alternar entre lo que cargar en vertical vs.horizontal. Ya tengo un xml de layout-land que está manejando mi layout.

public void onConfigurationChanged(Configuration _newConfig) {

        if (_newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            this.loadURLData = false;
        }

        if (_newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            this.loadURLData = true;
        }

        super.onConfigurationChanged(_newConfig);
    }

Sobrepasar onConfigurationChanged evitará que mi xml de layout-land se cargue en orientación horizontal.

Solo quiero obtener la orientación actual de mi dispositivo en onCreate(). Cómo puedo conseguir esto?

Author: Sheehan Alam, 2010-09-08

8 answers

Activity.getResources().getConfiguration().orientation
 404
Author: EboMike,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-03 18:00:17
int orientation = this.getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
    // code for portrait mode
} else {
    // code for landscape mode
}

Cuando la superclase de this es Context

 47
Author: Daniel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-08 17:55:11

En algunos dispositivos void onConfigurationChanged() puede bloquearse. El usuario utilizará este código para obtener la orientación actual de la pantalla.

public int getScreenOrientation()
{
    Display getOrient = getActivity().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;
}

Y use

if (orientation==1)        // 1 for Configuration.ORIENTATION_PORTRAIT
{                          // 2 for Configuration.ORIENTATION_LANDSCAPE
   //your code             // 0 for Configuration.ORIENTATION_SQUARE
}
 27
Author: Sakthimuthiah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-30 08:54:54
int rotation =  getWindowManager().getDefaultDisplay().getRotation();

Esto dará toda la orientación como normal y inversa

Y manejarlo como

int angle = 0;
switch (rotation) {
    case Surface.ROTATION_90:
        angle = -90;
        break;
    case Surface.ROTATION_180:
        angle = 180;
        break;
    case Surface.ROTATION_270:
        angle = 90;
        break;
    default:
        angle = 0;
        break;
}
 18
Author: AndroidBeginner,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-13 07:17:53
getActivity().getResources().getConfiguration().orientation

Este comando devuelve el valor int 1 para Vertical y 2 para Horizontal

 12
Author: Rudolf Coutinho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-06-05 06:35:28

En caso de que alguien quiera obtener una descripción de orientación significativa (como la que se pasa a onConfigurationChanged(..) con los reverseLandscape, sensorLandscape y así sucesivamente), simplemente use getRequestedOrientation()

 5
Author: a.ch.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-02-20 13:30:40

En tu clase de actividad usa el siguiente método:

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

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {

            setlogo();// Your Method
            Log.d("Daiya", "ORIENTATION_LANDSCAPE");

        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {

            setlogoForLandScape();// Your Method
            Log.d("Daiya", "ORIENTATION_PORTRAIT");
        }
    }

Luego, para declarar que su actividad maneja un cambio de configuración, edite el elemento apropiado en su archivo de manifiesto para incluir el atributo android:configChanges con un valor que represente la configuración que desea manejar. Los valores posibles se enumeran en la documentación para el atributo android:configChanges (los valores más utilizados son "orientation" para evitar reinicios cuando cambia la orientación de la pantalla y "keyboardHidden" para evitar se reinicia cuando cambia la disponibilidad del teclado). Puede declarar varios valores de configuración en el atributo separándolos con una tubería / carácter.

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

Eso es todo!!

 1
Author: DalveerSinghDaiya,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-16 07:13:03

Si desea sobrescribir ese método onConfigurationChanged y aún así desea que haga las cosas básicas, considere usar super.onConfigyrationChanged () como la primera instrucción en el método override.

 0
Author: Samarth S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-14 11:52:24