Android Screen Orientation Change (Screen Rotation) Example
22
May
2013

Android Screen Orientation Change (Screen Rotation) Example with Code Description

Know everything about Android Screen Orientation Change (Screen Rotation Change) Example with Code Description. We will discuss all possible Android Screen Orientation Change in details with help of a simple Android Activity Example. Also you can learn how to do android screen orientation lock here. Also you can change your screen orientation any time you want in an Android application.

android-screen-orientation-change-landscapeandroid-screen-orientation-change-portrait

Below are the possible screen orientation states for any android application.

ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED

ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE

ActivityInfo.SCREEN_ORIENTATION_PORTRAIT

ActivityInfo.SCREEN_ORIENTATION_USER

ActivityInfo.SCREEN_ORIENTATION_BEHIND

ActivityInfo.SCREEN_ORIENTATION_SENSOR

ActivityInfo.SCREEN_ORIENTATION_NOSENSOR

ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE

ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT

ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE

ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT

ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR

Note: These states are already present in the default Android Class called ‘ActivityInfo’. So don’t worry, we will just call the above parameters when we want to set the screen orientation of  any activity at anytime. We will discuss it latter in this chapter.

How to check screen orientation (screen rotation) on Emulator

If you don’t have Android device and you want to check landscape and portrait mode for your application,  then you can do it. Below is the shortcut key combination for changing landscape to portrait mode in emulator.

Key Combination: Press Ctrl+F12.

Here we will discuss regarding below possible points on Android Android Screen Orientation Change (Screen Rotation) with help of an example. Below are the points.

1.  Lock screen orientation change in Android

If you want to lock the screen orientation change of any screen (activity) of your android application then add below line in your projects AndroidManifest.xmlAdd the below line along with your activity entry in the AndroidManifest file.

  • Lock for landscape mode

Your screen will always display in Landscape mode, when you rotate your device, no changes will apply for the current activity.


android:screenOrientation="landscape"

Complete code for the activity entry in the attached example. Note You can search your activity entry in the Manifest file and add the above line like below

<activity
android:name="com.techblogon.screenorientationexample.MainActivity"
android:screenOrientation="landscape"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

 

  •  Lock for portrait mode

Your screen will always display in portrait mode, when you rotate your device, no changes will apply for the current activity.

android:screenOrientation="portrait"

Complete code for the activity entry in the attached example. Note You can search your activity entry in the Manifest file and add the above line like below

<activity
android:name="com.techblogon.screenorientationexample.MainActivity"
android:screenOrientation="portrait"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

2. Lock screen orientation (screen rotation) programmatically in Android

This option is little tricky. What we need to do is, we will get the screen orientation change (rotation change) event, then both for landscape and portrait mode event, we will set ether landscape or portrait mode as per our requirement. Below is the code snippet. We will set portrait mode always, so the screen will always stay in portrait mode.

// Check screen orientation or screen rotate event here

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Checks the orientation of the screen for landscape and portrait and set portrait mode always
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

 

3. Change screen orientation programmatically at anytime in Android

If you want to change your activity’s orientation mode at any time as per your requirement, then below is the java code for doing the same. As we discuss all the Android screen orientation modes above, we can set any of the mode at any time from the java code. Below is the example for both landscape and portrait mode. But you can set all available modes as the same way. put the below lines of code anywhere in your activity java file, where you want to change the screen orientation of your activity. For example if want to set a particular orientation before showing the screen, then you can add the code in onCreate() function of your activity.

  •  For Landscape mode

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

  •  For Landscape mode

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Note: While adding this code, don’t forget to import the package import android.content.pm.ActivityInfo; in to your code.

4. How to get screen orientation at runtime

Sometime, you want to get the screen orientation of the current screen programmatically at runtime . To get the same you can try the below java code in your activity.java file.

//Get current screen orientation
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int orientation = display.getOrientation();
switch(orientation) {
case Configuration.ORIENTATION_PORTRAIT:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case Configuration.ORIENTATION_LANDSCAPE:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
}

Note: Don’t forget to import below packages for the above code.

import android.view.Display;
import android.content.res.Configuration;
import android.view.WindowManager;

5. Find screen orientation change event in Android

If you want to get automatic events when any screen orientation changes occurred in the device. That means when your device moved from landscape to portrait and vice-versa, then you will get an automatic event in your java code, so that you can take action accordingly. Below is the code snippet for the same.

Step 1:

Add below line in your AndroidManifest file along with your activity entry.

android:configChanges="orientation|screenSize|keyboardHidden"

Note:  Caution: Beginning with Android 3.2 (API level 13) or above, the above code will only work, if you are working with below Android 3.2 API level 13), then you might use android:configChanges=”orientation|keyboardHidden” instead of android:configChanges=”orientation|screenSize|keyboardHidden”. Note: the attribute screenSize is omitted here.

Complete code for the activity entry in the attached example. Note You can search your activity entry in the Manifest file and add the above line like below

<activity
android:name="com.techblogon.screenorientationexample.MainActivity"
android:configChanges="orientation|screenSize|keyboardHidden"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

Step 2:

Override default android method onConfigurationChanged() for android screen orientation changes. Add below code snippet in your Activity Class. Note: We are showing toast messages while getting android screen orientation events from system.

// Check screen orientation or screen rotate event here
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);

// Checks the orientation of the screen for landscape and portrait
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, “landscape”, Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, “portrait”, Toast.LENGTH_SHORT).show();
}
}

Note: Now, when one of these configurations change, Your Activity does not restart. Instead, Your Activity receives a call to onConfigurationChanged().

6. Android screen orientation Lifecycle

We might have some confusion on the android screen orientation change lifecycle of an Android activity.  Sometimes you might observe  that your activity getting restarted, while the you rotate the device. Sometimes nothing happens. Below is the simple rule for android screen orientation change lifecycle.

1. If you already @Override the onConfigurationChanged() function in your java code( in your Android activity class) for handle Android Screen Orientation Change. Then your activity will never restart for any screen orientation changes. As i explained it in point-4 above.

2. If you do not @Override onConfigurationChanged() function as above, then your running activity will get restart every time for any screen orientation change happens in your device. That means your activity will destroy first by calling onDestroy() API and then onCreate() method will call again for your running activity to restart it.

3. To properly handle your activity’s restart state, you need to restores its previous state through the normal Activity lifecycle, in which Android OS calls onSaveInstanceState() method before it destroys your activity. So that you can save your data(variable values)and your application state. You can then restore the previous state during onCreate() or onRestoreInstanceState() method call of your activity.

Project Creation: ScreenOrientationExample

Create a new project in eclipse. Use below details while creating the test project, so that you can sync with the description here. Note:  In the attached example, i have only included the screen orientation change event as active code, how ever commented all other code, if you want it you can un-comment and use as per your requirement. Also the simplest way to test all possible Android screen orientation change modes is adding above code snippet in your code as described above.

1. Create a new project with project name: ScreenOrientationExample

2. Fill Application Name: ScreenOrientationExample

3. Fill the Package Name as: com.techblogon.screenorientationexample

4. Fill the activity name (if asking while creating this project) as: MainActivity

5. Fill the xml layout name (if asking while creating this project)  as: activity_main.xml

6. I have used SDK version Android 4.0.3 and Eclipse Version Indigo. But you can use any version.

7. Add below  java file (MainActivity.Java) in you project’s /src folder. Note: You can copy and paste below code to your MainActivity.Java file

  • MainActivity.Java


import android.os.Bundle;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.view.Menu;
import android.view.Display;
import android.content.res.Configuration;
import android.view.WindowManager;
import android.widget.Toast;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// programmitically set screen orientation of activity (landscape)
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

// programmitically set screen orientation of activity (portrait)
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

/*
//Get current screen orientation
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int orientation = display.getOrientation();
switch(orientation) {
case Configuration.ORIENTATION_PORTRAIT:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
case Configuration.ORIENTATION_LANDSCAPE:
setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
}
*/
}
// Check screen orientation or screen rotate event here
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);

// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, “landscape”, Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, “portrait”, Toast.LENGTH_SHORT).show();
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}

}

8. Add below xml layout file (activity_main.xml) in your project’s res/layout folder. Note: You can copy and paste the below code snippet in your activity_main.xml file.

  •  activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<TextView
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_centerHorizontal=”true”
android:layout_centerVertical=”true”
android:text=”@string/hello_world” />

</RelativeLayout>

9. Add the below Manifest file (AndroidManifest.xml) in your project’s root folder. Note: You can copy and paste the below code snippet in your AndroidManifest file.

  • AndroidManifest.xml


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.techblogon.screenorientationexample"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion=”8″
android:targetSdkVersion=”16″ />

<application
android:allowBackup=”true”
android:icon=”@drawable/ic_launcher”
android:label=”@string/app_name”
android:theme=”@style/AppTheme” >
<activity
android:name=”com.techblogon.screenorientationexample.MainActivity”
android:configChanges=”orientation|screenSize|keyboardHidden”
android:label=”@string/app_name” >
<intent-filter>
<action android:name=”android.intent.action.MAIN” />

<category android:name=”android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
</application>

</manifest>

10. Build and Run the application. You can see a toast message for each landscape and portrait mode change,when you rotate your device.

downloadDownload complete code for Android Screen Orientation Change (Screen Rotation) Example from Here

I hope this small tutorial on Android Screen Orientation Change will help you at it’s best.

| Tags: ,
  • 3985 View
  • Pin It