看过太多关于横竖屏切换时生命周期变化的文章,今天决定自己实践一下。
- 如何旋转?
- 通过打开手机的自动旋转支持
- 通过代码设置
方案1就不多说了,实际项目当中,我们通过方式2利用代码设置更具通用性
class MyOrientoinListener extends OrientationEventListener {
public MyOrientoinListener(Context context) {
super(context);
}
@Override
public void onOrientationChanged(int orientation) {
Log.d(TAG, "orention" + orientation);
int screenOrientation = getResources().getConfiguration().orientation;
if (((orientation >= 0) && (orientation < 45)) || (orientation > 315)) {//设置竖屏
if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT && orientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
Log.d(TAG, "设置竖屏");
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
} else if (orientation > 225 && orientation < 315) { //设置横屏
Log.d(TAG, "设置横屏");
if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
} else if (orientation > 45 && orientation < 135) {// 设置反向横屏
Log.d(TAG, "反向横屏");
if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
}
} else if (orientation > 135 && orientation < 225) {
Log.d(TAG, "反向竖屏");
if (screenOrientation != ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT);
}
}
}
}
新建一个内部类继承自OrientationEventListener 类,然后在oncreate方法中设置该监听生效
myOrientoinListener = new MyOrientoinListener(this);
myOrientoinListener.enable();
最后不要忘了在onDestory中取消监听
@Override
protected void onDestroy() {
super.onDestroy();
if (myOrientoinListener != null)
myOrientoinListener.disable();
}
- 生命周期到底是怎样的?
- 不配置configChanges时:切换横竖屏时生命周期各自都会走一遍
- 配置configChanges时:必须设置为android:configChanges="orientation|screenSize"时,才不会重走生命周期方法,只会回调onConfigurationChanged方法,注意,不配置configChanges或是配置了但不同时包含这两个值时,都会重走一遍生命周期方法,并且不会回调onConfigurationChanged方法。
- 另外重走生命周期方法时,还会调用onSaveInstanceState() 与onRestoreIntanceState(),资源相关的系统配置发生改变或者资源不足:例如屏幕旋转,当前Activity会销毁,并且在onStop之前回调onSaveInstanceState保存数据,在重新创建Activity的时候在onStart之后回调onRestoreInstanceState。其中Bundle数据会传到onCreate(不一定有数据)和onRestoreInstanceState(一定有数据)。用户或者程序员主动去销毁一个Activity的时候不会回调,其他情况都会调用,来保存界面信息。如代码中finish()或用户按下back,不会回调。