[SOLVED] Set Screen Orientation Programmatically

There are times where you need to ensure that your application is displayed only in a certain orientation. For example, suppose you are writing a game that should only be viewed in landscape mode. In this case, you can programmatically force a change in orientation using the setRequestOrientation() method of the Activity class:
package net.learn2develop.OrientationAware;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;

public class Orientation extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //---change to landscape mode---
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }
}

To change to portrait mode, use the ActivityInfo.SCREEN_ORIENTATION_PORTRAIT constant:


        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Developing Orientation-Aware Android Applications.

About these ads

5 Responses to [SOLVED] Set Screen Orientation Programmatically

  1. Pingback: [SOLVED] Set Screen Orientation Programmatically « RussenReaktor’s Weblog « Gregory Reese Research

  2. Tom Tasche says:

    Is this possible from outside of an activity? So I can force an app, that’s not controlled by me, to change orientation?

    Thanks
    Tom

    • Just put attach a command to the Intent before it’s sent, and retrieve it when the class gets instantiated.

      In the intent
      intent.putExtra(“orientation”, “portrait”);

      In the class
      String orientation = getIntent().getExtras().getString(“orientation”);
      if(orientation == “portrait”){
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
      } else {
      // defaults to landscape
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
      }

  3. coder says:

    nice

  4. Pingback: Set Screen Orientation Programmatically | JavaZzzzz….

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: