How can I rotate display only in landscape mode in android?

rubdottocom picture rubdottocom · Mar 21, 2011 · Viewed 21k times · Source

I want that my View rotates only in landscape mode, clockwise and counterclockwise.

I read about the only counterclockwise for android < 2.2 and that's not a problem, my App will be +2.2 for now.

I modify my manifest to catch Configuration Changes

android:configChanges="keyboardHidden|orientation"

I override my activity to catch Configuration Changes

@Override
public void onConfigurationChanged(Configuration newConfig) {

and I know how to catch orientation

Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int rot = display.getRotation();

but... I don't know how to trigger the appropiate landscape orientation, I am doing this:

if (rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270){
  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}

but always rotate to counterclocwise :-(

How can I set left and right landscape orientation?

EDIT

If I set orientation in manifest:

android:screenOrientation="landscape"

The activity's layout remains always in "left landscape", and I want change between left and right landscape :S

Answer

croc picture croc · Jan 13, 2012

If you're building your app for Android 2.3 and newer you should set the manifest attribute as

android:screenOrientation="sensorLandscape"

and your app will rotate to either (left or right) landscape position.

If you're building your app for Android 2.2 and older but want to run it on Android 2.3 and newer as a "sensorLandscape" configuration, you could try something like this

public static final int ANDROID_BUILD_GINGERBREAD = 9;
public static final int SCREEN_ORIENTATION_SENSOR_LANDSCAPE = 6;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (Build.VERSION.SDK_INT >= ANDROID_BUILD_GINGERBREAD) {
        setRequestedOrientation(SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
    }
...

This was the best way to handle the landscape orientation changes in my case. I was not able to find any better way to rotate the screen to left or right landscape orientations for Android 2.2 and older. I tried reading sensor orientations and setting the landscape position based on that, but it seems to me that as soon as you call "setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);" sensor turns off (for your app/activity) and you cannot read orientation through sensor.

BTW you don't really need to override the "onConfigurationChanged(Configuration newConfig)" for any of this to work properly.