旋转到水平时为什么getFirstVisiblePosition正确,但旋转回来时错误?

时间:2013-03-12 19:27:32

标签: android listview lifecycle

我有一个Android ListView。当用户转动设备时,我希望列表的可见部分保持(大致)相同。所以我在破坏活动时保存了第一个可见位置:

    @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);
}

(请忽略productFilter,它与此问题无关。)我在onCreate中将其恢复如下:

    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);
    }

将仿真器从垂直旋转到水平时,这很有效。将其旋转回垂直时,save方法中的getFirstVisiblePosition()始终返回零,尽管实际可见的项目已经很远。这是日志的输出:

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

有没有任何理由为什么第一次在53处正确地产生了位置,但第二次是零?我无法通过这里的日志来证明这一点,但我发誓我尝试了几次,而且我从未滚动回零!

1 个答案:

答案 0 :(得分:0)

尝试使用setSelection。之后

this.currentPosition = savedInstanceState.getInt("currentPosition");

添加

this.listView.setSelection(this.currentPosition);

*警告:这将更改您选择的项目。