Sunday, September 27, 2015

android - How to prevent orientation change

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="#d9dbd4"
    >
    <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_landscape"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set Orientation Landscape"
        android:layout_below="@id/tv"
        />
    <Button
        android:id="@+id/btn_portrait"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Set Orientation Portrait"
        android:layout_below="@id/btn_landscape"
        />
</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 android.widget.Toast;

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_landscape = (Button) findViewById(R.id.btn_landscape);
        final Button btn_portrait = (Button) findViewById(R.id.btn_portrait);
        final TextView tv = (TextView) findViewById(R.id.tv);

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

        /*
            Display a random number to TextView.
            It will help us to verify that activity is not restart when
            user try to change screen orientation.
        */
        tv.setText("Random Number : "+randomNumber);

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

        btn_landscape.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Set screen orientation to landscape
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
        });

        btn_portrait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Set screen orientation to portrait
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
        });
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
        super.onConfigurationChanged(newConfig);

        if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
            /*
                If user request to change screen orientation from portrait
                to landscape, then this code revert it portrait again.
            */
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            Toast.makeText(this, "Landscape requested.",Toast.LENGTH_SHORT).show();
        }

        if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT)
        {
            // Do something
            Toast.makeText(this, "Portrait requested.",Toast.LENGTH_SHORT).show();
        }
    }
}
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="orientation|screenSize"
                This prevent restarting the activity when screen orientation change.
        -->
        <!--
            public void onConfigurationChanged (Configuration newConfig)
                Called by the system when the device configuration changes while your
                activity is running. Note that this will only be called if you have
                selected configurations you would like to handle with the
                configChanges attribute in your manifest.

                So, we need to include orientation in android:configChanges,
                if we want to handle it in activity onConfigurationChanged event.
        -->
        <!--
            android:screenOrientation
                The orientation of the activity's display on the device.

                landscape
                    Landscape orientation (the display is wider than it is tall).

                portrait
                    Portrait orientation (the display is taller than it is wide).

                This setting make the activity a fixed orientation and it is one of the key
                factor to disable orientation change.

                In this example code, we make the activity fixed portrait orientation and
                disable to set it landscape mode.
        -->
        <!--
            Note: When you declare one of the landscape or portrait values, it is considered
            a hard requirement for the orientation in which the activity runs. As such,
            the value you declare enables filtering by services such as Google Play
            so your application is available only to devices that support the orientation
            required by your activities. For example, if you declare either
            "landscape", "reverseLandscape", or "sensorLandscape", then your application
            will be available only to devices that support landscape orientation. However,
            you should also explicitly declare that your application requires either
            portrait or landscape orientation with the <uses-feature> element.
            For example, <uses-feature android:name="android.hardware.screen.portrait"/>.
            This is purely a filtering behavior provided by Google Play (and other services
            that support it) and the platform itself does not control whether your app
            can be installed when a device supports only certain orientations.
        -->
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:configChanges="orientation|screenSize"
            android:screenOrientation="portrait"
            >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
More android examples