在Android开发中,屏幕方向控制是通过Activity的screenOrientation
属性或setRequestedOrientation()
方法实现的。系统默认支持四种基本方向:portrait
(竖屏)、landscape
(横屏)、reversePortrait
(反向竖屏)和reverseLandscape
(反向横屏)。
要实现禁用90°旋转(即横屏)但允许180°旋转(即反向竖屏),需要理解Android的屏幕方向控制机制。标准的portrait
和reversePortrait
都是竖屏方向,只是上下颠倒。
<activity
android:name=".YourActivity"
android:screenOrientation="portrait"
android:configChanges="orientation|screenSize"/>
这种方法会完全锁定为竖屏,不允许任何旋转,包括180°。
在Activity中重写onConfigurationChanged
方法,动态控制方向:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
int orientation = newConfig.orientation;
if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
// 检测到横屏,强制转回竖屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
// 允许竖屏和反向竖屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
}
}
// 在onCreate中设置初始方向
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
// 然后监听方向变化
private OrientationEventListener orientationEventListener;
@Override
protected void onResume() {
super.onResume();
orientationEventListener = new OrientationEventListener(this) {
@Override
public void onOrientationChanged(int orientation) {
if (orientation >= 45 && orientation < 135) {
// 左横屏,禁用
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else if (orientation >= 135 && orientation < 225) {
// 反向竖屏,允许
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
} else if (orientation >= 225 && orientation < 315) {
// 右横屏,禁用
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else {
// 正常竖屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
};
if (orientationEventListener.canDetectOrientation()) {
orientationEventListener.enable();
}
}
@Override
protected void onPause() {
super.onPause();
if (orientationEventListener != null) {
orientationEventListener.disable();
}
}
SCREEN_ORIENTATION_SENSOR_PORTRAIT
从API Level 18(Android 4.3)开始支持这种控制方式适用于:
通过以上方法,你可以实现禁用90°旋转但允许180°旋转的效果。