从 Cursor 到 LinearLayout 的动态项目列表,无需使用 ListView
我想在列表中显示游标中的一些(大约 5 个)项目,并且希望使其与游标的内容(游标依次指向数据库)保持同步,但我不这样做不想使用 ListView。相反,我想填充一个普通的旧 LinearLayout。
我似乎明白我需要创建一个自定义 CursorAdapter 并重写 newView() 和 bindView() 方法。我不明白的是谁负责迭代光标的项目(CursorAdapter 是否这样做?我的代码应该这样做吗?),每个项目的视图如何成为 LinearLayout 的父级,以及谁负责创建新项目查看光标中的新项目或删除不再通过光标可用的项目的视图?
不知何故,我有一种预感,CursorAdapter 已经完成了大部分工作,但我无法完全将拼图的所有部分放在一起。我是否只是在 newView() 中膨胀行布局并将其直接添加到 LinearLayout 中?如果游标不再具有关联数据,如何删除行?
感谢您的帮助!
马努
I'd like to display a few (5-ish) items from a Cursor in a list, and I'd like to keep it in sync with the content of the cursor (which in turn points to a database), but I don't want to use ListViews. Instead, I'd like to populate a plain old LinearLayout.
I seem to understand that I need to create a custom CursorAdapter and override the newView() and bindView() methods. What I don't understand is who is responsible for iterating over the cursor's items (does the CursorAdapter do it? Should my code do it?), how do the views for each item get parented to the LinearLayout and who is responsible for creating new views for new items in the cursor or removing views for items that are no longer available through the cursor?
Somehow I have a hunch that the CursorAdapter does already most of the work, but I can't quite put together all the pieces of the puzzle. Do I just inflate a row layout in newView() and add it to the LinearLayout directly? And how does a row gets removed if the cursor no longer has the associated data?
Thanks for your help!
Manu
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
好吧,我会执行以下操作:
** 调用removeAllViews
** 对于每个项目(遍历光标)调用 addView(CursorAdapter.newView(getContext(),cursor,this))
简而言之就是这样。当然,稍后您可能想要优化它,并保留旧视图并使用 CursorAdapter.bindView 代替,这样您就不需要创建新的重型 java 对象。
Well, I would do the following:
** call removeAllViews
** for each item (iterate through the cursor) call addView(CursorAdapter.newView(getContext(), cursor, this))
That's it in short. Of course later on you might want to optimize it, and keep the old views and use CursorAdapter.bindView instead, so you wouldn't need to create new heavy java objects.
CursorAdapter 允许您导航大型列表,而无需将所有项目加载到内存中。如果您只有一小部分项目,那么我只需在您的活动中迭代它们并相应地更新您的视图(添加视图、设置文本值、显示/隐藏等)
The CursorAdapter allows you to navigate a large list without having to have all the items loaded into memory. If you are just going to have a small handful of items then I would just iterate over them in your activity and update your view accordingly (adding views, setting text values, showing/hiding, etc.)
使用CursorLoader。当您的内容发生变化时,它会自动更新。
Use a CursorLoader. When ever there is a change in your content it will update automatically.