Control display orientation of an android device.

In some cases you want to fix the display orientation for your app in landscape or portrait. In this post i will explain how to restrict the orientation of your app only in landscape or portrait mode.
You can set the display orientation by using the following method

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

If you want to restrict the display orientation in portrait mode, then you can use the following.
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Also you have to made some changes in the androidmanifest.xml file as follows.
  <activity
            android:name="com.orientationdemo.MainActivity"
            android:label="@string/app_name" 
            android:screenOrientation="landscape" >

MainActivity.java

  1. package com.orientationdemo;
  2. import android.os.Bundle;
  3. import android.app.Activity;
  4. import android.content.pm.ActivityInfo;
  5. import android.view.Display;
  6. import android.view.Menu;
  7. import android.view.WindowManager;
  8. import android.widget.Toast;
  9. public class MainActivity extends Activity {
  10. @Override
  11. protected void onCreate(Bundle savedInstanceState) {
  12. super.onCreate(savedInstanceState);
  13. setContentView(R.layout.activity_main);
  14. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
  15. }
  16. @Override
  17. public boolean onCreateOptionsMenu(Menu menu) {
  18. // Inflate the menu; this adds items to the action bar if it is present.
  19. getMenuInflater().inflate(R.menu.main, menu);
  20. return true;
  21. }
  22. }
AndroidManifest.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3. package="com.orientationdemo"
  4. android:versionCode="1"
  5. android:versionName="1.0" >
  6. <uses-sdk
  7. android:minSdkVersion="8"
  8. android:targetSdkVersion="17" />
  9. <application
  10. android:allowBackup="true"
  11. android:icon="@drawable/ic_launcher"
  12. android:label="@string/app_name"
  13. android:theme="@style/AppTheme" >
  14. <activity
  15. android:name="com.orientationdemo.MainActivity"
  16. android:label="@string/app_name"
  17. android:screenOrientation="landscape"
  18. >
  19. <intent-filter>
  20. <action android:name="android.intent.action.MAIN" />
  21. <category android:name="android.intent.category.LAUNCHER" />
  22. </intent-filter>
  23. </activity>
  24. </application>
  25. </manifest>