Disable landscape mode in android app programmatically

Stop activity rotating to landscape mode dynamically so app is always starts runs on portrait mode.

There are two mode available on ever android device first one is Portrait and second one is Landscape mode. Portrait mode is where mobile phone in normal condition without rotating screen but landscape mode is where android mobile phone user rotate the mobile phone screen. Sometimes app developer needs to disable activity rotation to landscape mode so android app can only runs on portrait mode using setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) function . So here is the complete step by step tutorial for Disable landscape mode in android app programmatically.

android-project-download-code-button

How to Disable landscape mode in android app programmatically.

Code for MainActivity.java file.

 package com.disablelandscapemode_android_examples.com;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 //Add below line after setContentView to disable rotation.
 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
 
 }
}

Code for activity_main.xml layout file.

 <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:paddingBottom="@dimen/activity_vertical_margin"
 android:paddingLeft="@dimen/activity_horizontal_margin"
 android:paddingRight="@dimen/activity_horizontal_margin"
 android:paddingTop="@dimen/activity_vertical_margin"
 tools:context="com.disablelandscapemode_android_examples.com.MainActivity" >

 <TextView
 android:id="@+id/textView1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_centerHorizontal="true"
 android:layout_centerVertical="true"
 android:text="Disable landscape mode in android app programmatically"
 android:textAppearance="?android:attr/textAppearanceLarge"
 android:gravity="center" />
 
</RelativeLayout>

Screenshot in portrait mode .

portrait mode

Screenshot in landscape mode :

Disable landscape mode in android app programmatically

Click here to download Disable landscape mode in android app programmatically project.

Leave a Reply

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