您的位置:首页 > 移动开发 > Android开发

Android 手动设置屏幕方向后不能自动转屏问题

2016-06-12 00:00 197 查看
如题,Android在手动设置屏幕方向后不能使用自动转屏了,这是因为手动设置屏幕方向

如:

[code=language-java]setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

相当于在Manifest文件中Activity节点下配置了:

[code=plain]android:screenOrientation="landscape"

这会导致该Activity方向锁定,不能自动转屏。But,手动转屏是可以的,所以我们只需要加上方向改变监听,然后手动转屏,也就达到了自动转屏的目的:

[code=language-java]class OrientationEventListenerImpl extends OrientationEventListener {
public OrientationEventListenerImpl(Context context) {
super(context);
}
@Override
public void onOrientationChanged(int rotation) {
Log.i("旋转角度:","rotation = "+rotation);
// 设置为竖屏
if (((rotation >= 0) && (rotation <= 45)) || (rotation >= 315)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
// 设置为横屏
if(((rotation >= 225) && (rotation <= 315))) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
//设置为横屏(逆向)
if(((rotation >= 45) && (rotation <= 135))) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
}
}
}

然后再注册该监听器,比如在Activity的onCreate()方法中注册:

[code=plain]OrientationEventListenerImpl orientationEventListenerImpl = new OrientationEventListenerImpl(this);
orientationEventListenerImpl.enable();

这样就可以实现自动转屏了。上面代码只实现了在3个方向上转屏,没有写逆向的竖直方向(一般都不会用到这个方向吧),如有需要可以自己加上,角度请自己计算,其方向常量为:

[code=language-java]ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT

通过以上的代码,还可以再配合

[code=plain]@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}

就可达到自由控制屏幕显示方向的目的。

文章原地址:http://my.oschina.net/u/2500514/blog/690088
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: