Android GridView
is quite interesting, it reuses the child views. The ones scrolled up comes back from bottom. So there is no method from GridView
You can't reach the views directly because of the recycling. The view at position 0 may be re-used for the position 10, so you can't be sure of the data present in a specific view.
The way to go is to use the underlying data. If you need to modify data at position 10, then do it in the List or array under your adapter and call notifyDataSetChanged()
on the adapter.
if you need to have different views for different data subtypes, you can override the two following method in your adapter: getItemViewType()
and getViewTypeCount()
Then, in getView()
you can 1) decide which layout to inflate 2) know the type of view recycled using getItemViewType()
You can find an example here: https://stackoverflow.com/a/5301093/990616
After reading source of getPositionForView
, I have wrote this method in own GridView, works perfect by API 18
public View GetViewByPosition(int position) {
int firstPosition = this.getFirstVisiblePosition();
int lastPosition = this.getLastVisiblePosition();
if ((position < firstPosition) || (position > lastPosition))
return null;
return this.getChildAt(position - firstPosition);
}
There was an issue reported for this. Here is the link. This issue has been closed as WorkingAsIntended. Wish means we can expect the GridView to call getView() on pos 0 multiple times.
My work around is as follow:
public class GridAdapter extends BaseAdapter {
...
int previouslyDisplayedPosition = -1;
...
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(previouslyDisplayedPosition != position) {
....
previouslyDisplayedPosition = position;
}
return convertedView;
}
What I am trying to do here is returning the same 'convertView
' if same pos is called again and again. There by preventing any logic within getView()
(eg setting image view etc)to be executed again and again.