articles

Dynamically Locking Activity orientation in Android

Anonymous User 7943 18-Feb-2015

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 can adjust the screen orientation 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 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 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 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 from Resources.getConfiguration().

·   The Configuration 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

 

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

 

Dynamically Locking Activity orientation in Android

 

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

 

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

 

Dynamically Locking Activity orientation in Android

 

Now see how it works for Landscape mode

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

 

Dynamically Locking Activity orientation in Android

 

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

Dynamically Locking Activity orientation in Android

 

Thanks for reading this post.

Happy Coding!! J

 


Updated 28-Jan-2020
I am a content writter !

Leave Comment

Comments

Liked By