Thursday, May 24, 2012

Android: Handle Screen Orientation

Android:Handle Screen Orientation in Your Application:

1. Lock the Orientation in Current Activity:-
   In the onCreate(Bundle) method of the current activity use the setRequestedOrientation(int) method to set the screen orientation.
The activity will stay in this orientation regardless of if the device is tilted or not.
Java code:
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    this.setRequestedOrientation(
    ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}


2.  Detect the Current Screen Orientation:-
   Orientation property of the Configuration class returns four possible values corresponding to LANDSCAPE, PORTRAIT, SQUARE and UNDEFINED.
Java Code:
switch(this.getResources().getConfiguration().orientation)
{
case Configuration.ORIENTATION_PORTRAIT:
  // Do something here
  break;
case Configuration.ORIENTATION_LANDSCAPE:
  // Do something here
  break;
case Configuration.ORIENTATION_SQUARE:
  // Do something here
  break;
case Configuration.ORIENTATION_UNDEFINED:
  // Do something here
  break;
default:
  throw new Exception("Unexpected orientation enumeration returned");
  break;
}


3. Re-enable screen rotation for Appliction:-
   To enable the orientation to be automatically changed on device tilt simply pass the setRequestedOrientation(int) method the enumeration value for an unspecified orientation.
// Allow screen rotations again
this.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);


Download Source Code: ScreenorientationApp








0 comments:

Post a Comment

 
Powered by Blogger