22

Here's a pseudo code to detect screen rotate event, and decide to retain or changes the screen orientation.

public boolean onOrientationChanges(orientation) {
  if(orientation == landscape)
    if(settings.get("lock_orientation"))
      return false;   // Retain portrait mode
    else
      return true; // change to landscape mode

  return true; 
}

How do I make similar things in Android?

EDIT: I'm actually looking answer on Where to handle orientation changes. I do not want to fix the orientation by adding screenOrientation="portrait".

I need something, similar to onConfigurationChanges(), where I can handle the orientation, but do no need me to manually redraw the view.

Raidri
  • 17,258
  • 9
  • 62
  • 65
Bananakilo
  • 1,323
  • 3
  • 14
  • 20
  • You do not need to intercept the request and then permit or deny it. You can lock or free the orientation in advance. There are also more options with this method, such as whether to allow a 180 degree rotation when locked. Please read my answer below, rather than the selected one. – Steve Waring Aug 03 '14 at 17:33

6 Answers6

52

You need a Display instance firstly:

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();

Then orientation may be called like this:

int orientation = display.getOrientation();

Check orientation as your way and use this to change orientation:

setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

I hope it helps.

Update:

Okay, let's say you've an oAllow var which is Boolean and default value is False.

public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
    int orientation = display.getOrientation(); 
    switch(orientation) {
        case Configuration.ORIENTATION_PORTRAIT:
            if(!oAllow) {
                    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
            }
            break;
        case Configuration.ORIENTATION_LANDSCAPE:
            if(!oAllow) {
                    setRequestedOrientation (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            break;
    }
}

You can add more choices.

I didn't try this sample, but at least tells you some clues about how to solve. Tell me if you got any error.

UPDATE

getOrientation() is already deprecated see here. Instead Use getRotation(). To check if the device is in landscape mode you can do something like this:

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE))
        .getDefaultDisplay();

int orientation = display.getRotation();

if (orientation == Surface.ROTATION_90
        || orientation == Surface.ROTATION_270) {
    // TODO: add logic for landscape mode here            
}
msam
  • 4,259
  • 3
  • 19
  • 32
Ogulcan Orhan
  • 5,170
  • 6
  • 33
  • 49
  • thanks but where do I put the code? I mean which event/function is fired when the orientation is changed? – Bananakilo Mar 01 '12 at 00:05
  • @kenyi Simply what do you want do? Give more detail. Do you just need to handle orientation or what? I'll upgrade my answer. – Ogulcan Orhan Mar 01 '12 at 00:10
  • Before device change the orientation, I need to determine if landscape mode is allowed, in runtime. Let's say if user had landscape mode turned off, then app will remain in portrait mode. – Bananakilo Mar 01 '12 at 00:30
  • Updated my questions. I need to know where to handle the orientation during runtime – Bananakilo Mar 01 '12 at 00:36
  • Updated my answer, check out and tell me about result please. – Ogulcan Orhan Mar 01 '12 at 01:05
  • sorry onOrientationChanges is my pseudo code, there is not such event in android. I'm looking for that piece of code that could replace onOrientationChanges – Bananakilo Mar 01 '12 at 01:37
  • Yep, sorry for my negligence. I think overrided method has to be `onConfigurationChanged` according to these answers: http://stackoverflow.com/a/1512263/1033899 and http://stackoverflow.com/a/5200226/1033899 – Ogulcan Orhan Mar 01 '12 at 01:47
  • Updated for the last time I hope. – Ogulcan Orhan Mar 01 '12 at 17:10
  • Hi.. if you are doing some action based on the layout.. during orientation. This approach wont be much helpful – Gnanam R Mar 07 '13 at 08:52
  • 5
    display.getOrientation(); is depricated. Try to use getResources().getConfiguration().orientation – 0xPixelfrost Mar 26 '13 at 12:28
  • You do not need to intercept the request and then permit or deny it. You can lock or free the orientation in advance. There are also more options with this method, such as whether to allow a 180 degree rotation when locked. Please read my answer below. – Steve Waring Aug 03 '14 at 17:34
  • 1
    Also Surface.ROTATION_90 is relative to the natural rotation of the screen, so it could be portrait or landscape depending upon the device. – Steve Waring Aug 03 '14 at 18:17
21

Try running

getResources().getConfiguration().orientation

From your context object to figure out what is the screen orientation at runtime, the possible values are documented here

In order to catch the orientation change event you can find the answer in the Android Dev Guide: Handling the Configuration Change Yourself

From the guide :

For example, the following manifest code declares an activity that handles both the screen orientation change and keyboard availability change:

<activity android:name=".MyActivity"
android:configChanges="orientation|keyboardHidden"
android:label="@string/app_name">

Now, when one of these configurations change, MyActivity does not restart. Instead, the MyActivity receives a call to onConfigurationChanged(). This method is passed a Configuration object that specifies the new device configuration. By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface. At the time this method is called, your activity's Resources object is updated to return resources based on the new configuration, so you can easily reset elements of your UI without the system restarting your activity.

...

Talihawk
  • 1,299
  • 9
  • 18
  • Hi, I updated my question. I know how to retrieve the screen orientation, I need to know WHERE to handle it. – Bananakilo Mar 01 '12 at 00:36
  • Hi, check out the last link in my answer... [Handling the configuration change yourself](http://developer.android.com/guide/topics/resources/runtime-changes.html#HandlingTheChange). I edited my answer with some more info – Talihawk Mar 01 '12 at 01:30
4
if (this.getWindow().getWindowManager().getDefaultDisplay()
    .getOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
  // portrait mode
} else if (this.getWindow().getWindowManager().getDefaultDisplay()
           .getOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
  // landscape
}
Linh
  • 57,942
  • 23
  • 262
  • 279
Ashish Dwivedi
  • 8,048
  • 5
  • 58
  • 78
2

Another solution to determine screen orientation:

public boolean isLandscape() {
    return Resources.getSystem().getDisplayMetrics().widthPixels - Resources.getSystem().getDisplayMetrics().heightPixels > 0;
}
IQ.feature
  • 600
  • 6
  • 16
1

You don't need to intercept the event and then override it. Just use:

// Allow rotation
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
// Lock rotation (to Landscape)
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_LANDSCAPE);

Points to note here are, if on Jellybean and above this will allow a 180 degree rotation when locked. Also when unlocked this only allows rotation if the user's master settings is to allow rotation. You can forbid 180 degree rotations and override the master settings and allow rotation, and much much more, so check out the options in ActivityInfo

In addition, if you have pre-set that there is to be no rotation, then your activity will not be destroyed and then restarted, just for you to set the orientation back which will again cause the activity to be restarted; Thus setting what you want in advance can be much more efficient.

Pre Jellybean use ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE -- no 180 degree rotation with this.

Steve Waring
  • 2,882
  • 2
  • 32
  • 37
1

Check your android screen orientation at Runtime:

ListView listView = (ListView) findViewById(R.id.listView1);
if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
    //do work for landscape screen mode.
    listView.setPadding(0, 5, 0, 1);
} else if (getResources().getConfiguration().orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
    //Do work for portrait screen mode.
    listView.setPadding(1, 10, 1, 10);
}
Linh
  • 57,942
  • 23
  • 262
  • 279
Rahul Raina
  • 3,322
  • 25
  • 30