Android Screen Orientation Example

By | April 2, 2013
The Actvity (Screen) of the application changes it’s orientation either in portrait and landscape  when the device changes it’s direction

 In android we can have control over the acivity orientation through an attribute
 “android:screenOrientation” of activity tag inside manifest.xml file


 Lets See An Example of Screen Orientation .

1. XML Layout

     file:- activity_main.xml

<RelativeLayout 
android:layout_height="match_parent"
android:layout_width="match_parent"
android:paddingbottom="@dimen/activity_vertical_margin"
android:paddingleft="@dimen/activity_horizontal_margin"
android:paddingright="@dimen/activity_horizontal_margin"
android:paddingtop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">

<TextView
android:layout_centerinparent="true"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="@string/label"
android:textsize="30dp" />

</RelativeLayout>

2. Activity

Create Activity Class
  1) MainActivity
       file:- MainActivity.java

package com.pavan.screendemo;

import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);
}
}

3 Manifest

 3.1 Both In Portrait and Landscape Mode

< if your don’t specify the android:screenOriention attribute for acitivity tag inside manifest.xml file , by defalut it sets the value “unspecified” for it and hence the activity(screen) shifts to portrait mode when device is held in portrait diection and shifts to landscape mode when device is held in landscape direction
     
  android:screenOrientation=”unspecified



<uses-sdk android:minsdkversion="8" android:targetsdkversion="17"/>












3.2  In Portrait Mode Only

If you want to make the activity (screen) to be in portrait mode only then set the value of “android:screenOrientation” for activity tag inside manifest.xml with “Portrait” , even if you move the device in landscape the activity will be portrait

  android:screenOrientation=”portrait



<uses-sdk android:minsdkversion="8" android:targetsdkversion="17"/>










3.3  In Landscape Mode Only


If you want to make the activity (screen) to be in Landscape mode only then set the value of “android:screenOrientation” for activity tag inside manifest.xml with “Landscape” ,even if you move the device in portrait the activity will be landscape

  android:screenOrientation=”landscape