Friday 3 May 2013

Get Screen Orientation of Screen in Android


 You need to use getResources().getConfiguration().orientation to establish if the device is in portrait or 
landscape mode.Here, is simple code for Get Orientaion of device.

import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;

public class MainActivity extends Activity {

       @Override
       protected void onCreate(Bundle savedInstanceState)
       {

              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
             
              if(getScreenOrientation() == Configuration.ORIENTATION_PORTRAIT)
              {
                     System.out.println("Protrait Screen");
              }
              else
              {
                     System.out.println("Lanscaps Screen");
              }
       }
      
       public int getScreenOrientation()
       {
              return getResources().getConfiguration().orientation;
       }

}

There is anthor way to get orientaion of device.

public void onCreate(Bundle savedInstanceState)
{
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);       

       onConfigurationChanged(getResources().getConfiguration());

}

public void onConfigurationChanged(Configuration orient)
{
       super.onConfigurationChanged(orient);

       // Checks the orientation of the screen
       if (orient.orientation == Configuration.ORIENTATION_LANDSCAPE)
       {
              Toast.makeText(this"LANDSCAPE", Toast.LENGTH_SHORT).show();
       }
       else if (orient.orientation == Configuration.ORIENTATION_PORTRAIT)
       {     

              Toast.makeText(this"PORTRAIT", Toast.LENGTH_SHORT).show();
       }
}

No comments:

Post a Comment