GridView get view by position, first child view different

前端 未结 3 679
失恋的感觉
失恋的感觉 2020-12-19 05:51

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

相关标签:
3条回答
  • 2020-12-19 06:35

    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

    0 讨论(0)
  • 2020-12-19 06:36

    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);
    }
    
    0 讨论(0)
  • 2020-12-19 06:49

    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.

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