如何按位置从列表视图中获取每个菜单项?
假设一个列表有 4 个项目,如何按位置从列表的每个菜单项中获取视图?
Let's say a list has 4 items, how can I get a view from each menu item of a list by position?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是,ListView 中的项目通常只是可见的。您应该改为迭代 ListAdapter。
例如,在我的一些代码中,我有这样的:
编辑:
为了回应 jeffamaphone 的评论,这里还有一些其他内容...如果您尝试使用每个 UI 元素,那么 getChildAt 肯定更合适,因为它返回子项的视图,但一般来说您仍然只能与当时可见的那些一起工作。如果这就是您所关心的,那么很好 - 只需确保在调用返回时检查
null
即可。如果您正在尝试实现像我一样的功能 - 对于可能超出屏幕的列表的“全选/全选/反转选择”类型的功能,那么您最好在适配器中进行更改,或者有一个外部数组(如果像我的情况一样,适配器中没有地方可以进行更改),然后在列表适配器上调用
notifyDataSetChanged()
。例如,我的“Invert”功能具有如下代码:请注意,在我的例子中,我还使用自定义 ListView 子项,使用
adapter.setViewBinder(this);
和自定义>setViewValue(...)
函数。此外如果我没记错的话,我认为列表中的“位置”不一定与适配器中的“位置”相同......它又更多地基于中的位置名单。因此,即使您想要列表中的“第 50 个”项目,如果它是第一个可见的项目,
getChildAt(50)
也不会返回您所期望的内容。我认为你可以使用ListView.getFirstVisiblePosition()
来核算和调整。Unfortunately the items that are in the ListView are generally only those that are visible. You should iterate on the ListAdapter instead.
For example, in some of my code, I have this:
EDIT:
In response to jeffamaphone's comments, here's something else... if you are trying to work with each UI element then
getChildAt
is certainly more appropriate as it returns the View for the sub-item, but in general you can still only work with those that are visible at the time. If that's all you care about, then fine - just make sure you check fornull
when the call returns.If you are trying to implement something like I was - a "Select All / Select None / Invert Selection" type of feature for a list that might exceed the screen, then you are much better off to make the changes in the Adapter, or have an external array (if as in my case, there was nowhere in the adapter to make the chagne), and then call
notifyDataSetChanged()
on the List Adapter. For example, my "Invert" feature has code like this:Note that in my case, I am also using a custom ListView sub-item, using
adapter.setViewBinder(this);
and a customsetViewValue(...)
function.Furthermore if I recall correctly, I don't think that the "position" in the list is necessarily the same as the "position" in the adapter... it is again based more on the position in the list. Thus, even though you are wanting the "50th" item on the list, if it is the first visible,
getChildAt(50)
won't return what you are expecting. I think you can useListView.getFirstVisiblePosition()
to account and adjust.看到这里,这个问题回答了您在这里提到的类似问题
在 android ListView 中,如何迭代/操作所有子视图,而不仅仅是可见的子视图?
See here, this question answers the similar problem you mentioned here
In an android ListView, how can I iterate/manipulte all the child views, not just the visible ones?