如何在Android的gridview中查找元素? [英] How to find element inside a gridview in Android?

查看:20
本文介绍了如何在Android的gridview中查找元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用自定义适配器填充的网格视图.在填充 gridview 时,我为每个元素提供了一个唯一的标签.

I have a grid view which I populate using a custom adapter. While populating the gridview I give each element inside a unique tag.

一旦这个 gridview 被填充,我希望在 gridview 中找到一个特定的元素及其标签.我如何找到这个?

Once this gridview is populated, I wish to find a specific element inside the gridview with its tag. How do I find this?

目前我正在这样做:

gridviewobject.findViewById(thetag);
// gridview object is the object of the gridview that i have populated.

推荐答案

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

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.

这是因为 GridView 回收它的视图,所以本质上它只会制作足够的视图以适应屏幕,然后在滚动时更改这些视图的位置和内容.

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.

可能是更好的方法

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 做了类似的事情,但不是比较整数,而是比较标签(由于它们是对象而不是整数,所以速度较慢)

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

这篇关于如何在Android的gridview中查找元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆