Activity in portrait or reverse portrait only
I want my activity to be av开发者_运维知识库ailable 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
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
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);
}
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 :)
精彩评论