Vérifier l'orientation sur Android phone
Comment puis-je vérifier si le téléphone Android est en paysage ou Portrait?
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 .
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;
}
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)
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
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,
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;
}
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.
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
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();
}
}
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;
}
}
le SDK Android peut vous dire très bien:
getResources().getConfiguration().orientation
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.
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?
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!
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
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
}
Simple et facile:)
- Make 2 xml layouts ( I. e Portrait et paysage)
-
au fichier java, écrire:
private int intOrientation;
à
onCreate
méthode et avantsetContentView
é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.
je pense que cette solution facile
if (context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
user_todat_latout = true;
} else {
user_todat_latout = false;
}
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;
}
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é.
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 ..!