Question:
hello I would like to know how I can get the orientation of the screen in the java class of an activity in android. It would be something like
if(pantalla portrait){
...hago esto...
}else{
...hago esto otro...
}
Answer:
You must take into account that some devices may have different orientations, I consider this to be more appropriate:
public String getRotation(Context context){
final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();
switch (rotation) {
case Surface.ROTATION_0:
return "vertical";
case Surface.ROTATION_90:
return "horizontal";
case Surface.ROTATION_180:
return "vertical inversa";
default:
return "horizontal inversa";
}
}
This to define if the orientation is horizontal or vertical even if this is inverse.
If you only want to know if it is horizontal or vertical then it would be as you say Felix:
public String getRotation(Context context){
final int rotation = ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getOrientation();
switch (rotation) {
case Surface.ROTATION_0:
case Surface.ROTATION_180:
return "vertical";
case Surface.ROTATION_90:
default:
return "horizontal";
}
}
To call the method it would be done in this way:
if(getRotation(getApplicationContext()).equals("vertical")){ //es vertical o portrait.
...hago esto...
}else{ // es horizontal o landscape.
...hago esto otro...
}