Sunday, September 27, 2015

android - How to change orientation without restarting activity

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#e4e8ff"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="Sans-Serif-Condensed"
        android:textSize="18dp"
        android:textStyle="italic"
        android:textColor="#000000"
        android:padding="15dp"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Screen Orientation"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.ActionBar;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.content.res.Configuration;
import android.widget.TextView;
import java.util.Random;


public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        final Button btn = (Button) findViewById(R.id.btn);
        final TextView tv = (TextView) findViewById(R.id.tv);

        Random rand = new Random();
        final int randomNumber = rand.nextInt(100);

        ActionBar ab = getActionBar();
        ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#6da5eb")));

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Get the activity
                Activity activity = MainActivity.this;

                if(getScreenOrientation(activity) == "Landscape")
                {
                    /*
                        public void setRequestedOrientation (int requestedOrientation)
                            Change the desired orientation of this activity. If the activity
                            is currently in the foreground or otherwise impacting the screen
                            orientation, the screen will immediately be changed
                            (possibly causing the activity to be restarted).
                            Otherwise, this will be used the next time the activity is visible.

                        Parameters
                            requestedOrientation
                             An orientation constant as used in ActivityInfo.screenOrientation.
                    */

                    /*
                        ActivityInfo
                            Information you can retrieve about a particular application activity
                            or receiver. This corresponds to information collected from the
                            AndroidManifest.xml's <activity> and <receiver> tags.
                    */
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

                    /*
                        If the activity restarted after changing the screen orientation,
                        then this random number will change.

                        If the screen orientation changed without restarting the activity,
                        then this random number will not change when we change the screen
                        orientation.

                        Even we can't see the new text on TextView, if the activity restarted
                        after screen orientation change.
                    */
                    tv.setText("Random Number : " + randomNumber);
                    tv.setText(tv.getText() + "\nScreen orientation changed.");
                    tv.setTextColor(Color.RED);
                }
                else if (getScreenOrientation(activity) == "Portrait")
                {
                    tv.setText("Random Number : " + randomNumber);
                    tv.setText(tv.getText() + "\nScreen orientation changed.");
                    tv.setTextColor(Color.BLUE);
                    // Change the screen orientation to landscape
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                }
            }
        });
    }

    // Custom method to get screen current orientation
    public static String getScreenOrientation(Activity activity) {
        String orientation = "";
        int currentOrientation = activity.getResources().getConfiguration().orientation;

        if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) {
            orientation = "Landscape";
        }

        if (currentOrientation == Configuration.ORIENTATION_PORTRAIT) {
            orientation = "Portrait";
        }

        return orientation;
    }
}
AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.cfsuman.me.androidcodesnippets" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <!--
            android:configChanges
                Lists configuration changes that the activity will handle itself.
                When a configuration change occurs at runtime, the activity is shut
                down and restarted by default, but declaring a configuration with
                this attribute will prevent the activity from being restarted.
                Instead, the activity remains running and its
                onConfigurationChanged() method is called.

                Multiple values are separated by '|' — for example,
                "locale|navigation|orientation".

                orientation
                    The screen orientation has changed — the user has rotated the device.

                    Note: If your application targets API level 13 or higher (as declared by
                    the minSdkVersion and targetSdkVersion attributes), then you should
                    also declare the "screenSize" configuration, because it also changes
                    when a device switches between portrait and landscape orientations.

                screenSize
                    The current available screen size has changed. This represents a change
                    in the currently available size, relative to the current aspect ratio,
                    so will change when the user switches between landscape and portrait.
                    However, if your application targets API level 12 or lower, then your
                    activity always handles this configuration change itself (this
                    configuration change does not restart your activity, even when
                    running on an Android 3.2 or higher device).
        -->
        <!--
            android:configChanges="orientation|screenSize"
                This prevent restarting the activity when screen orientation change.
        -->
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            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>

More android examples