是什么导致 ListView 在方向更改后保持其滚动位置?
我有一个包含 ListView 的活动。我使用 SimpleCursorAdapter 填充列表视图。当我运行应用程序时,我可以在 ListView 中手动向下滚动(例如,滚动到第 10 项)。然后,当我旋转手机时,这会破坏并重新创建我的 Activity,并且 ListView 会按预期重新创建。
但是,在我的手机上旋转后,重新创建的 Activity 显示我的 ListView 仍处于手动滚动位置(在本例中为第 10 行)。我很确定我的代码没有调用 ListView.setSelection(int) 那么是什么导致了 ListView 的重新定位?
这可能看起来很方便,但这不是我想要的。它是 ListViews 行为的一部分吗?如果是这样,如何停止/覆盖这种重新定位?
I have an Activity containing a ListView. I populate the list view using a SimpleCursorAdapter. When I run the app, I can manually scroll down in the ListView (e.g. to the 10th item). Then when I rotate my phone - this destroys and re-creates my Activity and the ListView is made afresh as expected.
But, on my phone after rotating, the re-created Activity shows my ListView still at my manual scroll position (in this example, the 10th row). I'm pretty sure my code is not calling ListView.setSelection(int) so what is causing this re-positioning of the ListView ?
This might seem pretty handy, but its not what I want. Is it part of ListViews behaviour ? If so, how can stop/override this re-positioning ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
围绕该主题阅读更多内容......
视图状态会自动存储(包括我的 ListView)。这是由 onSaveInstanceState() / onRestoreInstanceState() 的默认实现处理的。使用调试器,我可以看到 savingInstanceState 包含来自 ListView 的条目 - 这就是自动重新定位它的原因。要在我的 Activity 中停止此操作,我只需重写 onSaveInstanceState() 即可。
Reading around the topic some more....
View states are stored automatically (including my ListView). This is handled by the default implementation of onSaveInstanceState() / onRestoreInstanceState(). Using the debugger I can see that savedInstanceState includes an entry from my ListView - so that is what is automatically repositioning it. To stop that in my Activity I can just override onSaveInstanceState().
您是否使用 ListActivity 作为您的活动的基类?如果是,那么它可能是该功能,因为它会覆盖 onRestoreInstanceState。我会尝试从简单的 Activity 继承。
Did you use ListActivity as a base class for your activity? If yes then it's likely the feature as it overrides onRestoreInstanceState. I would try to inherit from simple Activity.
ListView
在屏幕旋转后恢复其状态(包括滚动位置),其方式和原因与EditText
保留您在其中键入的文本相同。 Android 框架就是这样设计的。您可以通过在 xml 布局文件中设置ListView
的android:saveEnabled="false"
属性来停止此保存/恢复行为。或者,您可以出于相同目的调用ListView
上的setSaveEnabled(false)
方法。ListView
restores its state (including scroll position) after screen rotation the same way and for the same reason as for exampleEditText
preserves the text you typed in it. It is how the Android framework is designed. You can stop this save/restore behavior by settingandroid:saveEnabled="false"
attribute for theListView
in the xml layout file. Or you can callsetSaveEnabled(false)
method on theListView
for the same purpose.