1

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

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

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

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,但第二次为 0?我无法通过这里的日志证明这一点,但我发誓我尝试了几次,但我从未回滚到零!

4

1 回答 1

0

尝试使用 setSelection。后

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

添加

this.listView.setSelection(this.currentPosition);

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

于 2013-03-12T22:43:54.170 回答