1、屏幕方向属性:screenOrientation
Android应用程序中,android:screenOrientation用于控制activity启动时方向。
1.1、屏幕方向属性
屏幕方向android:screenOrientation取值可以为以下几种:
- unspecified 默认值,由系统决定,不同手机可能不一致
- landscape 强制横屏显示
- portrait 强制竖屏显
- behind 与前一个activity方向相同
- sensor 根据物理传感器方向转动,90度、180度、270度旋转手机,activity更着变化
- sensorLandscape 横屏旋转,一般横屏游戏会这样设置
- sensorPortrait 竖屏旋转
- nosensor 旋转设备时候,界面不会跟着旋转。初始化界面方向由系统控制
- user 用户当前设置的方向
1.2、在AndroidManifest中设置
在AndroidManifest.xml的Activity节点下指定屏幕方向:
<activity android:name=".JumpActivity"
android:screenOrientation="portrait"/>
1.3、代码中设置
代码中设置:在Activity中调用public void setRequestedOrientation(int requestedOrientation)方法:
public void setRequestedOrientation(int requestedOrientation);
1.4、AndroidStudio warning
新版的AndroidStudio,固定屏幕方向竟然警告。可能不建议将应用的屏幕方向锁死。

加入tools:ignore="LockedOrientationActivity"忽略这个提示:
<activity android:name=".JumpActivity"
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity" />
2、锁定屏幕
多数情况下需要将界面锁定成竖屏,不随着系统的很竖屏发生变化,就要锁定竖屏或者横屏。关于屏幕旋转等设置发生变化导致Activity重启参考《onConfigurationChanged()及屏幕横竖屏锁定》
2.1、在AndroidManifest中设置横竖屏(推荐)
在AndroidManifest中添加Activity的属性android:screenOrientation,有两个值竖屏portrait和横屏landscape
//当前Activity锁定竖屏
android:screenOrientation="portrait"
2.2、代码中设置横竖屏(不推荐)
在Activity中调用setRequestedOrientation()方法设置布局横竖屏
// 横屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
//竖屏
setRequestedOrientation(ActivityInfo .SCREEN_ORIENTATION_PORTRAIT);
2.3、两种锁定横竖屏对Activity生命周期的影响
第一种在AndroidManifest中设置,
android:screenOrientation="landscape"
来看看初始化时,执行了一次onCreate(),生命周期正常。
D/TAG_ForbiddenCapture: onCreate
再来看看第二种在onCreate中设置锁定横屏landscape属性
第一次debug启动打印出下面这样的log,有点意外,竟然调用了onConfigurationChanged,但是并没有在activity节点下配置相关属性android:configChanges
D/TAG_ForbiddenCapture: onCreate
D/TAG_ForbiddenCapture: onConfigurationChanged:横屏
D/TAG_ForbiddenCapture: onCreate
之后每次重新打开应用都会执行两次onCreate()
D/TAG_ForbiddenCapture: onCreate
D/TAG_ForbiddenCapture: onCreate