membersound membersound - 3 years ago 60
Android Question

How to access all child elements of a GridView?

I have a

GridView
showing items of "icon with text overlay".
On a specific event I want to iterate all of those items and change the text. But how can I get a reference to those items outside of a
OnItemClickListener
?

Can I somehow execute something like:
view.findAllViewById(R.id.itemtext);
? I know the findAll() does not exist.

item_view.xml:

<RelativeLayout>
<ImageView />
<TextView android:id="@+id/itemtext" />
</RelativeLayout>


main.xml:

<LinearLayout>
<GridView android:id="@+id/simpleGridView" />
</LinearLayout>


Code.

GridView grid = (GridView) findViewById(R.id.simpleGridView);
grid.setAdapter(..); //inside adapter: inflates the items by R.layout.item_view

grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView item = ((TextView) view.findViewById(R.id.itemtext));
item.setText("some click text");
}
});


Question: how can I access all available
R.id.itemtext
elements, and iterate through them? Because I have no reference to them.

Answer Source

1. Child views

If your really want to access the R.id.itemtext views you could probably use the GridView as a ViewGroup (it extends it), iterate over its children and findViewById(R.id.itemtext) for each of them:

for (int i = 0; i < grid.getChildCount(); i++) {
    View child = getChildAt(i);
    View itemText = child.findViewById(R.id.itemtext);
    ...
}

2. Adapter items

But GridView is also an AdapterView and it has some handy methods like getFirstVisiblePosition, getLastVisiblePosition and getItemAtPosition and I would consider using them to get the data in the (currently visible) text views like this:

int first = grid.getFirstVisiblePosition();
int last = grid.getLastVisiblePosition();
for(int i=first; i<=last; ++i){
    Object item = grid.getItemAtPosition(); // You should probably cast to your adapter's item type
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download