How to find element inside a gridview in Android?
Asked Answered
E

1

9

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.
Electrolysis answered 12/5, 2011 at 10:18 Comment(2)
If the object is not on-screen then it's view probably does not exist - in that case you cannot get a reference to it. What you can use is getChildAt in combination with getFirstVisiblePosition and getChildCount to determinate which views are currently visible and what position each one corresponds to.Longsighted
could you explain in more detail what you are suggesting.Electrolysis
L
15

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)

Longsighted answered 12/5, 2011 at 11:7 Comment(3)
i was going for a tag because i did not know the exact location of the view i am trying to find inside the gridview. also when the view is visible, and try to find the view by tag as i have shown in the question i still get a null.Electrolysis
If each unique position in the GridView has a unique tag then if you know what Tag you are looking for you should also be able to work out what position you are looking for.Longsighted
thanks a lot, the code i was reviewing directly accessed childAt(pos).. which resulted in layout null, your code works perfectly...Solita

© 2022 - 2024 — McMap. All rights reserved.