如何找到在Android的一个GridView里面的元素? [英] How to find element inside a gridview in Android?

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

问题描述

我有我填充使用自定义适配器网格视图。 而填充的GridView我给里面的一个独特的标记每个元素。

在这个GridView的填充,我希望能够找到它的标签在GridView内的特定元素。我怎么觉得呢?

目前我在做这样的:

  gridviewobject.findViewById(thetag);
// gridview的对象是我所填充的GridView的对象。
 

解决方案

什么你上面写的都可以工作,但要知道,一个)在搜索视图通过它的标签可能是你可以用它来取景最慢的方法和b)如果你试图请求与标签的视图,该视图当前不可见,那么你会得到

这是因为的GridView 回收自己的看法,所以本质上,它永远只能赚了足够的意见,以适应在屏幕上,然后只需改变这些位置和内容,滚动约。

可能是一个更好的办法可能是做

 最终诠释numVisibleChildren = gridView.getChildCount();
最终诠释firstVisiblePosition = gridView.getFirstVisiblePosition();

的for(int i = 0; I< numVisibleChildren;我++){
    INT positionOfView = firstVisiblePosition + I;

    如果(positionOfView == positionIamLookingFor){
        查看查看= gridView.getChildAt(我);
    }
}
 

实际上 findViewWithTag 做类似的事情,但不是比较整数它比较标签(这是比较慢,因为他们的对象,而不是整数)

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.

解决方案

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)

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

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