---
title: "Dynamically Locking Activity orientation in Android"  
description: "Hi Everyone, here we learn how to implement dynamic locking of Activity orientations in Android"  
author: "Anonymous User"  
published: 2015-02-18  
updated: 2020-01-28  
canonical: https://www.mindstick.com/articles/1589/dynamically-locking-activity-orientation-in-android  
category: "android"  
tags: ["android"]  
reading_time: 5 minutes  

---

# Dynamically Locking Activity orientation in Android

Previously, we have the locked the orientation for the activity that will not be change dynamically (once it’s fixed, the orientation will not be changed later): Locking Activity Orientation in Android. Now we implement how to change the orientation locking dynamically.\

Sometimes there are many situations in which the user want the orientation to be locked at one moment and to be changed at the next moment.

This scenario can be handled using the requested orientation mechanism in Android, an [application](https://www.mindstick.com/articles/12824/calculator-application-in-android) can adjust the [screen orientation](https://www.mindstick.com/interview/2547/change-screen-orientation-in-android-emulator) used to display the activity, fixing it to a specific orientation or releasing it to the device to decide. This is accomplished through the use of the Activity.setRequestedOrientation() method, which takes an integer constant from the ActivityInfo.screenOrientation [attribute](https://www.mindstick.com/blog/61/ado-dot-net-object-model-and-attributes) grouping.

By default, the requested orientation is set to SCREEN_ORIENTATION_UNSPECIFIED, which allows the device to decide for itself which orientation should be used. This is a decision typically based on the physical orientation of the device. The current requested orientation can be retrieved at any time as well by using Activity.getRequestedOrientation().

##### Pre-Requisites:

1. Ellipse SDK

2. Android SDK

3. ADT plugin

\
Or [Android Studio](https://www.mindstick.com/blog/10942/android-studio-vs-eclipse) and a compatible version of JAVA SDK

Install and configure the above utilities.

Now create a new Android project namely “OrientationLocking”.

##### Implementation objective:

#####

To enable/disable the locking of orientation in the activity according to the users wish i.e. dynamically

##### Code Implementation:

#####

First of all [update your](https://answers.mindstick.com/qa/96426/how-can-you-update-your-profile-without-notifying-contacts) activity_main. xml as follows:

```
<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" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
  <ToggleButton
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/toggleButton"
      android:textOff="Lock"
      android:textOn="LOCKED"
      />
 
</RelativeLayout>
```

Now navigate toMainActivity.java and add this code:

```
package com.example.msclient010.orientationlocking;import android.content.pm.ActivityInfo;import android.content.res.Configuration;import android.os.Bundle;import android.support.v7.app.ActionBarActivity;import android.view.Menu;import android.view.MenuItem;import android.widget.CompoundButton;import android.widget.ToggleButton; 
public class MainActivity extends ActionBarActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //Get handle to the button resources        ToggleButton toggle = (ToggleButton) findViewById(R.id.toggleButton);        //Set default state before adding the listener        if (getRequestedOrientation() != ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED) {            toggle.setChecked(true);        } else {            toggle.setChecked(false);
        }        //Attach the listener to the button        toggle.setOnCheckedChangeListener(listener); 
    }
    CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
        @Override        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            int current = getResources().getConfiguration().orientation;
            if (!isChecked) {                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                return;
            }            switch (current) {                case Configuration.ORIENTATION_LANDSCAPE:                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    break;                case Configuration.ORIENTATION_PORTRAIT:
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    break;
                default:                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
                    break;
            }
        }
    };    @Override    public boolean onCreateOptionsMenu(Menu menu) {        // Inflate the menu; this adds items to the action bar if it is present.        getMenuInflater().inflate(R.menu.menu_main, menu);        return true;
    }    @Override    public boolean onOptionsItemSelected(MenuItem item) {        // Handle action bar item clicks here. The action bar will        // automatically handle clicks on the Home/Up button, so long        // as you specify a parent activity in AndroidManifest.xml.        int id = item.getItemId();        //noinspection SimplifiableIfStatement        if (id == R.id.action_settings) {            return true;
        }        return super.onOptionsItemSelected(item);
    }
} 
```

##### Code Explaination:

· The code in the listener is the key ingredient to this approach. If the user presses the button and it toggles to the ON state, the current orientation is read by storing the orientation [parameter](https://www.mindstick.com/blog/450/parameter-class-in-c-sharp) from [Resources](https://www.mindstick.com/interview/1265/what-are-the-different-types-of-resources-through-which-cold-fusion-can-communicate).getConfiguration().

· The [Configuration](https://www.mindstick.com/articles/13112/setting-up-the-perfect-configuration-for-your-work-computer) object and the requested orientation use different constants to map the states, so we switch on the current orientation and call setRequestedOrientation() with the appropriate constant.

· If the user presses the button and it toggles to the OFF state, we no longer want to lock the orientation, so setRequestedOrientation() is called with the SCREEN_ORIENTATION_UNSPECIFIED constant again to return control back to the device.

· This may also cause an immediate change to occur if the device's physical orientation differs from the activity orientation when the lock is removed.

##### Running the Application:

#####

Hit on Run button, the Emulators screen will be default showed in Portrait orientation:

![Dynamically Locking Activity orientation in Android](https://www.mindstick.com/mindstickarticle/a4177dd5-e50a-4175-a94e-d9eb10fde128/images/0d559a85-2772-4205-927c-0445069ac5b2.png)

Now, change the orientation to landscape, the UI will also change accordingly

![Dynamically Locking Activity orientation in Android](https://www.mindstick.com/mindstickarticle/a4177dd5-e50a-4175-a94e-d9eb10fde128/images/15a6d9c0-62d4-4278-90ec-fbb59d91ea9c.png)

Change back the orientation to portrait and click on Toggle button, the text on button will change to “LOCK” to “Locked”

![Dynamically Locking Activity orientation in Android](https://www.mindstick.com/mindstickarticle/a4177dd5-e50a-4175-a94e-d9eb10fde128/images/05283602-ef19-49af-adea-7bfc4d35f098.png)

Now again change the orientation to landscape mode, this time the UI will be stick to portrait orientation.

![Dynamically Locking Activity orientation in Android](https://www.mindstick.com/mindstickarticle/a4177dd5-e50a-4175-a94e-d9eb10fde128/images/5d22c9d6-063f-42a1-9049-eef35490dd23.png)

Now see how it works for [Landscape mode](https://www.mindstick.com/forum/23288/orientation-issue-how-to-disable-landscape-mode-in-android)

Change the orientation in Landscape and click on toggle button to lock the orientation

**![Dynamically Locking Activity orientation in Android](https://www.mindstick.com/mindstickarticle/a4177dd5-e50a-4175-a94e-d9eb10fde128/images/c65063ce-2e4c-487e-a906-f5588e7abdfc.png)**

Now change the orientation to portrait mode, the UI will be locked for landscape orientation

![Dynamically Locking Activity orientation in Android](https://www.mindstick.com/mindstickarticle/a4177dd5-e50a-4175-a94e-d9eb10fde128/images/3a018ab7-4a8b-4e24-86cb-54c52047dc8e.png)

Thanks for reading this post.

Happy Coding!! J

---

Original Source: https://www.mindstick.com/articles/1589/dynamically-locking-activity-orientation-in-android

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
