How to find element inside a gridview in Android?

前端 未结 1 1753
旧时难觅i
旧时难觅i 2020-12-17 22:33

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,

相关标签:
1条回答
  • 2020-12-17 23:34

    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)

    0 讨论(0)
提交回复
热议问题