Change screen orientation in android programmatically on Button click

How to dynamically change android mobile phone device screen orientation Landscape,Portrait on button click.

In this tutorial we are changing the current screen orientation mode on button clicks using setRequestedOrientation method. This method will help us to change the screen orientation after start activity using MainActivity.java file. So here is the complete step by step tutorial for Change screen orientation in android programmatically.

android-project-download-code-button

How to Change screen orientation in android programmatically.

Code for MainActivity.java file.

 package com.changescreenorientation_android_examples.com;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;


public class MainActivity extends Activity {

 Button Landscape, Portrait;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 
 Landscape = (Button)findViewById(R.id.button1);
 Portrait = (Button)findViewById(R.id.button2);
 
 Landscape.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 
 
 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
 
 
 }
 });
 
 Portrait.setOnClickListener(new View.OnClickListener() {
 
 @Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 
 
 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.changescreenorientation_android_examples.com.MainActivity" >

 <Button
 android:id="@+id/button2"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_below="@+id/button1"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="14dp"
 android:text="Portrait Mode" />

 <Button
 android:id="@+id/button1"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentTop="true"
 android:layout_centerHorizontal="true"
 android:layout_marginTop="156dp"
 android:text="Landscape Mode" />

</RelativeLayout>

Screenshot:

Change screen orientation in android programmatically

 

screen-2

Click here to download Change screen orientation in android programmatically project with source code.

Leave a Reply

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