Activity in portrait or reverse portrait only

2019-01-11 18:33发布

I want my activity to be available only in both portrait modes - portrait and reversePortrait. How can I achieve this? When I set android:screenOrientation="portrait" it will force activity to be only in normal portrait - vice versa with reversePortrait.

Please, don't tell me it's a bad approach to force/lock orientation. I know about it, but still client is requesting it. Thanks for understanding and for any ideas.

UPDATE: API Level 11 and higher

3条回答
乱世女痞
2楼-- · 2019-01-11 19:19

For posterity's sake, I use this for backward compatibility...

public final class OrientationHelper {

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void setRequestedOrientationSensorPortrait(Activity activity) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
        } else {
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

    @TargetApi(Build.VERSION_CODES.GINGERBREAD)
    public static void setRequestedOrientationSensorLandscape(Activity activity) {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.FROYO) {
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
        } else {
            activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }
}

usage

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    OrientationHelper.setRequestedOrientationSensorPortrait(this);
    super.setContentView(R.layout.my_layout);
}
查看更多
Bombasti
3楼-- · 2019-01-11 19:25

In AndroidManifest.xml:

android:screenOrientation="portrait|reversePortrait"
android:configuration="keyboardHidden|orientation"

In your WhateverActivity.java:

protected void onConfigurationChanged(Configuration newConfig) {
    int currentOrientation = getResources().getConfiguration().orientation;
    if(newConfig.orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ||
        newConfig.orientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
        super.onConfigurationChanged(newConfig);
    }
}

You can try this :)

查看更多
ゆ 、 Hurt°
4楼-- · 2019-01-11 19:29

If you are on API level 9+, use android:screenOrientation="sensorPortrait".

Portrait orientation, but can be either normal or reverse portrait based on the device sensor. Added in API level 9.

Documentation

查看更多
登录 后发表回答