Android How to - Control the Orientation of the Activity








To ensure that your application is displayed in only a certain orientation, you can programmatically force a change in orientation using the setRequestOrientation() method of the Activity class.

import android.content.pm.ActivityInfo;
//from   w  w w  .  j a  v a 2s . co  m
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //---change to landscape mode---
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}

You can also use the android:screenOrientation attribute on the <activity> element in AndroidManifest.xml as follows to constrain the activity to a certain orientation:

<?xml version="1.0" encoding="utf-8"?>
<manifest 
    ...

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".OrientationsActivity"
            android:screenOrientation="landscape" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


The activity will not be destroyed and the onCreate() method will not be fired again when the orientation of the device changes.

Following are two other values that you can specify in the android:screenOrientation attribute:

  • portrait - Portrait mode
  • sensor - Based on the accelerometer (default)