Android Change Orientation Without Restarting Activity Example

This example will show you how to change the android device screen orientation ( horizontal to vertical vice versa ) and how to avoid activity restart during the screen orientation change.

1. Android Change Screen Orientation Example.

  1. There are two radio buttons in the example. When you click the related button, the screen orientation will be changed between portrait and landscape.
  2. There will also popup a toast message at the bottom of the screen during the screen orientation change. This toast message is displayed when the activity is created in the onCreate method. Which means each time the screen orientation change, the activity is restarted.
  3. You can see the example demo video at the youtube link https://youtu.be/lvcx5lEBCjA.
  4. Below is the source code. The core file is MainActivity.java, activity_main.xml, AndroidManifest.xml.
    android-change-screen-orientation-example-source-code

1.1 Main Activity.

  1. MainActivity.java
    package com.dev2qa.screenorientation;
    
    import android.content.pm.ActivityInfo;
    import android.content.res.Configuration;
    import android.graphics.drawable.GradientDrawable;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.support.v7.widget.LinearLayoutCompat;
    import android.widget.RadioButton;
    import android.widget.RadioGroup;
    import android.widget.Toast;
    
    public class MainActivity extends AppCompatActivity {
    
        // The default value is -1 which means unspecified.
        private int currentScreenOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            setTitle("dev2qa.com - Android Change Screen Orientation Example.");
    
            /* This method will be invoked when this activity is created or restart.
            *  If this message do not shown then it means the activity is not restarted.
            * */
            showCurrentOrientation();
    
            // Get radio group object.
            RadioGroup radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
    
            // Get each radio button.
            RadioButton portraitRadioButton = (RadioButton)findViewById(R.id.portraitRadioButton);
            RadioButton landscapeRadioButton = (RadioButton)findViewById(R.id.landscapeRadioButton);
    
            // Check or uncheck related radio button by current screen orientation.
            if(currentScreenOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
            {
                portraitRadioButton.setChecked(true);
                landscapeRadioButton.setChecked(false);
            }else if(currentScreenOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
            {
                portraitRadioButton.setChecked(false);
                landscapeRadioButton.setChecked(true);
            }
    
            /* When the radio group button value changed. */
            radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
    
                    if(checkedId == R.id.landscapeRadioButton)
                    {
                        // If user click landscape radio button.
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                    }else if(checkedId == R.id.portraitRadioButton)
                    {
                        // If user click portrait radio button.
                        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                    }
    
                }
            });
        }
    
        /* Display related information about current screen orientation. */
        private void showCurrentOrientation()
        {
            // Get current orientation.
            currentScreenOrientation = getRequestedOrientation();
    
            // If above method can not get current screen orientation.
            if(currentScreenOrientation == ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
            {
                // Get screen orientation from activity configuration.
                currentScreenOrientation = this.getResources().getConfiguration().orientation;
            }
    
            // Show different text messages by different screen orientation.
            StringBuffer msgBuf = new StringBuffer();
    
            if(currentScreenOrientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
            {
                msgBuf.append("Current screen orientation is landscape ( horizontal )");
            }else if(currentScreenOrientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
            {
                msgBuf.append("Current screen orientation is portrait ( vertical )");
            }else if(currentScreenOrientation == -1)
            {
                msgBuf.append("Current screen orientation is unknown.");
            }
    
            // Display toast message.
            Toast.makeText(this, msgBuf.toString(), Toast.LENGTH_LONG).show();
        }
    }

1.2 Main Activity Layout Xml File.

  1. app/res/layout/activity_main.xml
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    
        <RadioGroup
            android:id="@+id/radioGroup"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">
    
            <RadioButton
                android:id="@+id/portraitRadioButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Portrait ( Vertical Screen)"
                android:textAllCaps="false"
                android:textSize="20dp"/>
    
            <RadioButton
                android:id="@+id/landscapeRadioButton"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="LandSacpe ( Horizontal Screen)"
                android:textAllCaps="false"
                android:textSize="20dp"/>
    
        </RadioGroup>
    </LinearLayout>

2. Android Change Screen Orientation Without Restart Activity.

  1. If you want the activity to not restart during screen orientation change, you can use the below AndroidManifest.xml.
  2. Please note the activity android:configChanges=”orientation|screenSize” attribute. This attribute makes the activity not restart when change screen orientation.
  3. So when you run the example again, the toast message will not be shown which means the onCreate method is not invoked when changing screen orientation.
  4. You can see the example demo video on the youtube URL https://youtu.be/kWDFR9eLwGo.
  5. AndroidManifest.xml.
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.dev2qa.screenorientation">
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity"
            android:configChanges="orientation|screenSize">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.