如何在 Android 中查找 gridview 中的元素?

发布于 2024-11-07 02:39:43 字数 276 浏览 0 评论 0原文

我有一个使用自定义适配器填充的网格视图。 在填充 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

女皇必胜 2024-11-14 02:39:43

您上面所写的内容将起作用,但要注意:a)通过标签搜索视图可能是查找视图时最慢的方法;b)如果您尝试请求带有标签的视图,但该视图不是当前可见,那么您将得到null

这是因为 GridView 回收其视图,因此本质上它只会生成足够的视图以适合屏幕,然后在您滚动时更改这些视图的位置和内容。

可能更好的方法可能是

final int numVisibleChildren = gridView.getChildCount();
final int firstVisiblePosition = gridView.getFirstVisiblePosition();

for ( int i = 0; i < numVisibleChildren; i++ ) {
    int positionOfView = firstVisiblePosition + i;

    if (positionOfView == positionIamLookingFor) {
        View view = gridView.getChildAt(i);
    }
}

本质上 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

final int numVisibleChildren = gridView.getChildCount();
final int firstVisiblePosition = gridView.getFirstVisiblePosition();

for ( int i = 0; i < numVisibleChildren; i++ ) {
    int positionOfView = firstVisiblePosition + i;

    if (positionOfView == positionIamLookingFor) {
        View view = gridView.getChildAt(i);
    }
}

Essentially findViewWithTag does something similar, but rather than comparing integers it compares the tags (which is slower since they're objects and not ints)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文