Activity in portrait or reverse portrait only

僤鯓⒐⒋嵵緔 提交于 2019-11-26 16:43:08

问题


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


回答1:


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




回答2:


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);
}



回答3:


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 :)



来源:https://stackoverflow.com/questions/7686512/activity-in-portrait-or-reverse-portrait-only

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!