Friday, June 10, 2011

Handling Orientation Change in Android

If you want perform some operation in the orientation the following snippet useful. If you change the orientation then one default method will call i.e onConfigurationChanged()

@Override
 public void onConfigurationChanged(Configuration newConfig)
{
         super.onConfigurationChanged(newConfig);
         if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
         {           
                  // indicates orientation changed to landscape
         }             
         else if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
         {           
                  // indicates orientation changed to portrait
         }            
}

Note :
We will change the declaration of the Activity in manifast.xml to the following :
<activity android:name=".YourActivity" android:label="@string/app_name" android:configChanges="orientation|keyboardHidden" />

If you want know more information about this plz follow the link :
http://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange   

getting current screen orientation in android

The following snippet gives the current screen orientation.

public int getScreenOrientation()
{
        return getResources().getConfiguration().orientation;
}

The above method return integer. We will compare as follows.

 if(getScreenOrientation() == Configuration.ORIENTATION_PORTRAIT)
 {
            //App is in Portrait mode
 }
 else
{
           //App is in LandScape mode
}