2014-09-03 208 views
0

我有一個圖像url的數組,我想用Picasso下載圖像並在網格視圖中顯示它們。我當前的實現工作,但它將最後一張圖像放入網格視圖的每個圖像視圖中。從數組填充GridView

public class GridViewAdapter extends ArrayAdapter { 

     Context context; 

     public GridViewAdapter(Context context) { 
      super(context, 0); 
      this.context = context; 
     } 

     public int getCount() { 
      return thumbnailURLS.size(); 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 

      View row = convertView; 

      if(row == null) { 
       LayoutInflater inflater = ((Activity)context).getLayoutInflater(); 
       row = inflater.inflate(R.layout.grid_row, parent, false); 

       ImageView gridImageView = (ImageView)row.findViewById(R.id.gridImageView); 

       for(String s : thumbnailURLS) { 
        Picasso.with(context) 
          .load(s) 
          .placeholder(R.drawable.placeholder) 
          .error(R.drawable.placeholder) 
          .into(gridImageView); 
       } 
      } 

      return row; 
     } 
    } 

回答

1

爲每個項目調用一次getView(即調用次數等於'getCount')。最簡單的做法是放棄for循環並使用position參數查找thumbnailUrl。

@Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

     View row = convertView; 

     if(row == null) { 
      LayoutInflater inflater = ((Activity)context).getLayoutInflater(); 
      row = inflater.inflate(R.layout.grid_row, parent, false); 
     } 

     ImageView gridImageView = (ImageView) row.findViewById(R.id.gridImageView); 

     Picasso.with(context) 
       .load(thumbnailURLs.get(position)) 
       .placeholder(R.drawable.placeholder) 
       .error(R.drawable.placeholder) 
       .into(gridImageView); 

     return row; 
    } 
1

你getView是每一個圖像實際上加載到列表項,因此只有最後一個變成可見的一個!

正確的解決辦法如下:

@Override 
    public View getView(int position, View convertView, ViewGroup parent) { 

    View row = convertView; 
    if (row == null) { 
     LayoutInflater inflater = ((Activity) context).getLayoutInflater(); 
     row = inflater.inflate(R.layout.grid_row, parent, false); 
    } 

    ImageView gridImageView = (ImageView) row.findViewById(R.id.gridImageView); 
    Picasso.with(context).load(thumbnailURLS.get(position)).placeholder(R.drawable.placeholder) 
     .error(R.drawable.placeholder).into(gridImageView); 
    return row; 
    } 

你也應該考慮使用ViewHolder模式(http://developer.android.com/training/improving-layouts/smooth-scrolling.html#ViewHolder),使得你沒有做一個findViewById每個getView被稱爲時間!

0

試試這個

// Get the image URL for the current position. 
String url = getItem(position); 

// Trigger the download of the URL asynchronously into the image view. 
Picasso.with(context) // 
    .load(url) // 
    .placeholder(R.drawable.placeholder) // 
    .error(R.drawable.error) // 
    .fit() // 
    .into(view);