如何在 Android 中查找 gridview 中的元素?
我有一个使用自定义适配器填充的网格视图。 在填充 gridview 时,我给每个元素赋予一个唯一的标签。
一旦填充了这个 gridview,我希望在 gridview 中找到一个特定的元素及其标签。我如何找到这个?
目前我正在这样做:
gridviewobject.findViewById(thetag);
// gridview object is the object of the gridview that i have populated.
I have a grid view which I populate using a custom adapter.
While populating the gridview I give each element inside a unique tag.
Once this gridview is populated, I wish to find a specific element inside the gridview with its tag. How do I find this?
Currently I'm doing this:
gridviewobject.findViewById(thetag);
// gridview object is the object of the gridview that i have populated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您上面所写的内容将起作用,但要注意:a)通过标签搜索视图可能是查找视图时最慢的方法;b)如果您尝试请求带有标签的视图,但该视图不是当前可见,那么您将得到
null
。这是因为 GridView 回收其视图,因此本质上它只会生成足够的视图以适合屏幕,然后在您滚动时更改这些视图的位置和内容。
可能更好的方法可能是
本质上
findViewWithTag
做类似的事情,但不是比较整数,而是比较标签(这比较慢,因为它们是对象而不是整数)What you have written above will work, except be aware that a) searching for a view by its tag is probably the slowest method you could use to find a view and b) if you try requesting a view with a tag and that view is not currently visible, then you will get
null
.This is because
GridView
recycles its views, so essentially it only ever makes enough views to fit on screen, and then just changes the positions and content of these as you scroll about.Possibly a better way might be to do
Essentially
findViewWithTag
does something similar, but rather than comparing integers it compares the tags (which is slower since they're objects and not ints)