第一种
最常用的方式是处理
@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
}
在 onSaveInstanceState 中保存重要的值,等旋转屏幕后在 onRestoreInstanceState 中恢复值。
Activity 的周期流程是:
onCreate -> onStart -> onResume -> onSaveInstanceState -> onPause -> onStop -> onDestory ->onCreate -> onStart -> onRestoreInstanceState - >onResume
从这里看出,在旋转屏幕后重新走了onCreate的方法,所以我们可能需要根据重要数据重新绘制View
第二种
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
重写该方法,但是需要在 AndroidManifest 文件中做一些配置。
如下:
<uses-permission android:name="android.permission.CHANGE_CONFIGURATION"/>
<activity android:name=".ui.mine.MyActivity"
android:screenOrientation="sensor"
android:configChanges="orientation|screenSize">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
<category android:name="android.intent.category.MULTIWINDOW_LAUNCHER" />
</intent-filter>
</activity>
首先一定要设置权限。
其次 screenOrientation 设置成 sensor 表示跟随系统设置
configChanges属性在 4.0 版本后一定要添加 screenSize
Activity 周期是:
onCreate -> onStart -> onConfigurationChanged …
这也可以看出旋转后没有重新走onCreate的方法,我们也不需要保存所谓的重要数据了。