Android set orientation

Viewed 352

I have an oddball android device which has no gravity sensors, and on that device, my "set orientaion" function does nothing. On all other devices, including some without sensors, the following works fine.

        Activity act = AndroidNativeUtil.getActivity();
    int newo = portrait 
        ?   (reverse
                ? ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT
                : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
        :   (reverse
                ? ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE
                : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    act.setRequestedOrientation(
            newo

is there some additional API that can lock the screen orientation? Some other apps successfully change the screen orientation.

2 Answers

Check orientation

@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);

// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
    Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
    Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}

How to lock orientation?

public class OrientationUtils {
private OrientationUtils() {}

/** Locks the device window in landscape mode. */
public static void lockOrientationLandscape(Activity activity) {
    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}

/** Locks the device window in portrait mode. */
public static void lockOrientationPortrait(Activity activity) {
    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

/** Allows user to freely use portrait or landscape mode. */
public static void unlockOrientation(Activity activity) {
    activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}

}

How about android:screenOrientation="locked". This will lock the orientation to its current rotation (From API 18)

Related