Check your Android device Screen Orientation with example


                    Android screen orientation facilitates the device use in all possible orientations. Its very easy to find the screen orientation relative to its natural orientation. The natural orientation of a device is the orientation in which the orientation is 0 on all the three axes.
The natural orientation is either portrait or landscape. Below images will clearly explain you the various device orientations.

Portrait Orientations

Landscape orientations
Now lets see how to get these orientations programatically.

public int getRotation ()
           Returns the rotation of the screen from its natural orientation. The returned value may be :

  • Surface.ROTATION_0 (no rotation)  
  • Surface.ROTATION_90 
  • Surface.ROTATION_180
  • Surface.ROTATION_270
I have switched rotation values in a switch loop and displayed the orientation type on button click using a toast. 

MainActivity.java

import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.view.Surface;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {
 Button button;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  button = (Button) findViewById(R.id.button1);
  button.setOnClickListener(new OnClickListener() {
   public void onClick(View v) {

    int rotation = getWindowManager().getDefaultDisplay()
      .getRotation();
    // DisplayMetrics dm = new DisplayMetrics();
    // getWindowManager().getDefaultDisplay().getMetrics(dm);
    int orientation;
    CharSequence text;

    switch (rotation) {
    case Surface.ROTATION_0:
     text = "SCREEN_ORIENTATION_PORTRAIT";
     break;
    case Surface.ROTATION_90:
     text = "SCREEN_ORIENTATION_LANDSCAPE";
     break;
    case Surface.ROTATION_180:
     text = "SCREEN_ORIENTATION_REVERSE_PORTRAIT";
     break;
    case Surface.ROTATION_270:
     text = "SCREEN_ORIENTATION_REVERSE_LANDSCAPE";
     break;
    default:
     text = "SCREEN_ORIENTATION_PORTRAIT";
     break;
    }

    // CharSequence text = String.valueOf(orientation);
    Toast toast = Toast.makeText(getApplicationContext(), text,
      Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.CENTER | Gravity.CENTER, 10, 0);
    toast.show();

   }
  });
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
 }

}





Source code of this applicaion



Reactions:

1 comment :

  1. I've read your post "Check your Android device Screen Orientation with example". Thanks for sharing worthy information!

    ReplyDelete