System如何自动保留ListView的滚动位置?
您可能已经注意到,即使您没有处理 onSaveInstanceState 方法,某些数据在轮换期间也不会受到影响。例如
- EditText 中的滚动位置文本
- EditText 等中的文本
屏幕旋转时会发生什么?
当屏幕旋转时,系统会终止 Activity 的实例并重新创建一个新实例。系统这样做是为了为不同配置的活动提供最合适的资源。当一个完整的活动进入多窗格屏幕时,也会发生同样的事情。
系统如何重新创建一个新的Instance?
系统使用 Activity 实例的旧状态创建一个新实例,称为“instance state”。 Instance State 是存储在BundleObject 中的键值对的集合。
例如,默认情况下系统将视图对象保存在 Bundle 中。
例如滚动位置EditText等。
因此,如果您想保存应该在方向更改后保留的其他数据,您应该覆盖onSaveInstanceState(Bundle saveInstanceState) 方法。
重写 onSaveInstance 方法时要小心!!!
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
始终调用super.onSaveInstanceState(savedInstanceState) ekse,默认行为将不起作用。即 EditText 值在定向期间不会持续存在。不相信我吗? Go and check this code.
恢复数据时使用哪种方法?
onCreate(Bundle savedInstanceState)
或
onRestoreInstanceState(Bundle savedInstanceState)
这两种方法都获得相同的 Bundle 对象,因此在哪里编写恢复逻辑并不重要。唯一的区别是,在onCreate(Bundle savedInstanceState) 方法中,您必须进行空检查,而在后一种情况下不需要。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mTextView = (TextView) findViewById(R.id.main);
if (savedInstanceState != null) {
CharSequence savedText = savedInstanceState.getCharSequence(KEY_TEXT_VALUE);
mTextView.setText(savedText);
}
}
或
@Override
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);
}
总是打电话给super.onRestoreInstanceState(savedInstanceState),这样
系统默认恢复视图层次结构。