I have an Android ListView. I want the visible portion of the list to stay (roughly) the same when the user turns the device. So I save the first visible position on destruction of the activity:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
this.currentPosition = this.listView.getFirstVisiblePosition();
Log.i(TAG, "onSaveInstanceState, productFilter = " + this.productFilter + "; currentPosition = " + this.currentPosition);
outState.putInt("productFilter", this.productFilter);
outState.putInt("currentPosition", this.currentPosition);
}
(Please ignore the productFilter, it's not related to this question.) And I restore it in onCreate like this:
Log.i(TAG, "onCreate");
if (savedInstanceState != null) {
this.productFilter = savedInstanceState.getInt("productFilter");
this.currentPosition = savedInstanceState.getInt("currentPosition");
Log.i(TAG, "productFilter = " + this.productFilter + "; currentPosition = " + this.currentPosition);
}
When rotating the emulator from vertical to horizontal, this works nicely. When rotating it back to vertical, the getFirstVisiblePosition()
in the save method always returns zero, although the actually visible item has been far away. This is the output of the logs:
03-12 19:16:36.140: INFO/WindowManager(51): Config changed: { scale=1.0 imsi=0/0 loc=de_DE touch=3 keys=2/1/2 nav=3 orien=2 layout=34}
03-12 19:16:36.180: INFO/ExperimentalList(777): onSaveInstanceState, productFilter = 0; currentPosition = 53
03-12 19:16:36.190: INFO/ExperimentalList(777): onCreate
03-12 19:16:36.190: INFO/ExperimentalList(777): productFilter = 0; currentPosition = 53
03-12 19:16:36.220: INFO/WindowManager(51): onOrientationChanged, rotation changed to 0
03-12 19:16:36.220: INFO/WindowManager(51): Setting rotation to 0, animFlags=0
03-12 19:16:36.241: INFO/WindowManager(51): Config changed: { scale=1.0 imsi=0/0 loc=de_DE touch=3 keys=2/1/2 nav=3 orien=1 layout=34}
03-12 19:16:36.270: DEBUG/StatusBar(51): updateResources
03-12 19:16:36.340: DEBUG/StatusBar(51): updateResources
03-12 19:16:36.610: INFO/ExperimentalList(777): onSaveInstanceState, productFilter = 0; currentPosition = 0
03-12 19:16:36.620: INFO/ExperimentalList(777): onCreate
03-12 19:16:36.620: INFO/ExperimentalList(777): productFilter = 0; currentPosition = 0
Is there any reason why the first time the position was correctly yielded at 53, but the second time as zero? I can't prove it by the logs here, but I swear I tried this a few times and I never scrolled back to zero!