带有 ArrayAdapter 和后台服务的 Android ListView 不能保持项目的正确顺序
当我在服务获取新数据后渲染/更新列表视图时,列表项的顺序每次都会发生变化。
ArrayAdapter 有一个 ArrayList 成员,所有项目在显示在屏幕上之前都按正确顺序排列。我还有两种 ItemViewType,一种用于项目标题,另一种用于项目。这是用 ViewHolder“模式”渲染的。
我想我错过了一些愚蠢的事情。
什么会导致这种行为?
When I render / update the list view after the service get's new data the order of the list items is changing every time.
The ArrayAdapter has an ArrayList member and all the items are in correct order until shown on the screen. I also have two ItemViewTypes, one for the header of the items and one for the items of course. This is rendered with the ViewHolder "pattern".
I guess I'm missing something silly.
What could cause such behavior?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我的猜测是
ArrayAdapter
拥有您在实例化时提供的 List 自己的浅拷贝 ArrayAdapter
。如果此假设成立,则结果是 ListView 显示列表项的修改,而不会反映列表项顺序的修改。如果您的列表项具有可比性,以便可以恢复所需的顺序,则可以随后调用 ArrayAdapter.sort(Comparator comp) 方法和 ArrayAdapter.notifyDataSetChanged() 方法。就我而言,甚至滚动位置也完美保留。
但是,您也可以尝试使用
ArrayAdapter
的add
和remove
方法来更新适配器本身。My guess is that
ArrayAdapter
holds it's own shallow copy of the List you provide on instantiation of theArrayAdapter
. If this assumption holds true, the consequence is that modifications of list items are shown by the ListView while modifications of the list item order will not be reflected.If your list items are comparable so that the required order can be recovered, you could call the
ArrayAdapter.sort(Comparator comp)
method and the ArrayAdapter.notifyDataSetChanged() method afterwards. In my case even the scroll position was preserved perfectly.However, you could also try to use the
add
andremove
methods ofArrayAdapter
to update the adapter itself.