编辑: bingyan8 | 2018-11-21 |
// Always call the superclass first // Check whether we're recreating a previously destroyed instance if (savedInstanceState != null) { // Restore value of members from saved state mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else { // Probably initialize members with default values for a new instance } ... } 也可以选择实现 onRestoreInstanceState()方法 (在onCreate()后被调用) 恢复数据, 而不是在 onCreate()方法中恢复.系统仅在有保存的数据需要恢复的时候才会调用 onRestoreInstanceState()方法,所以不需要在该方法中检查 Bundle 是否为空: public void onRestoreInstanceState(Bundle savedInstanceState) { // Always call the superclass so it can restore the view hierarchy super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} 警告: 实现该方法时,一定记住调用父类的 onRestoreInstanceState(),这样默认的实 现可恢复 view 的状态. 参考 Handling Runtime Changes. 上一节 下一节 下一课: 支持不同的设备