2016-07-03 48 views
2

我想要添加到ListView的有關部件:如何在listview中使用Picasso?

public class Widget { 
    String w_type; 
    String title; 
    String desc; 
    String img; 
//.... 
} 

我想表明在列表視圖圖像,如果IMG字段不爲空。我應該如何使用Picasso而不用在滾動後重覆在ListView中顯示錯誤圖像的Ang?這是從我的適配器的列表視圖的getView方法的當前代碼:

public View getView(int i, View someView, ViewGroup arg2) { 
    LayoutInflater inflater = LayoutInflater.from(context); 
    if (someView == null) { 
     someView = inflater.inflate(R.layout.widgets_list, arg2, false); 
    } 

    ImageView img = (ImageView) someView.findViewById(R.id.pic); 

    String img_url = data.get(i).img; 
    if (!img_url.equals("")){ 
     Picasso.with(context).load(img_url).into(img); 
    } 
    return someView; 
} 

但現在ListView顯示錯誤和重複的圖像。我該如何解決它?

+0

實施'ViewHolder'在'getView()'方法。對於更詳細地訪問此:http://stackoverflow.com/questions/23120238/using-picasso-library -with-listview – Ironman

回答

1

我會推薦使用ViewHolder模式。 更多信息可以在這裏找到:

https://developer.android.com/training/improving-layouts/smooth-scrolling.html

留意,你必須處理您的img_url確實是空的情況下,你需要設置一個默認的圖像這種情況下,如果沒有,當細胞被回收利用後,圖像將保持不變,然後您將體驗到您所談論的重複。

例如下面的代碼:

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

    ViewHolder holder; 

    if (convertView == null) { 
    convertView = LayoutInflater.from(mContext).inflate(R.layout.widgets_list, null); 
    holder = new ViewHolder(); 
    holder.mImageView = (ImageView) convertView.findViewById(R.id.iconImageView); 
    convertView.setTag(holder); 
    } else { 
    holder = (ViewHolder) convertView.getTag(); 
    } 

    //fetching your data object with the current position 
    Example example = mExamples[position]; 

    String img_url = example.get(i).img; 

    if (!img_url.equals("")){ 
    Picasso.with(context).load(img_url).into(holder.mImageView); 
    } else { 
    //todo - implement a default image in case img_url is indeed empty 
    Picasso.with(context).load(defaultImage).into(holder.mImageView); 
    } 

    return convertView; 
} 

private static class ViewHolder { 
    ImageView mImageView; 
} 
+0

棒極了!我一直在尋找這樣的東西。謝謝! – EpicSyntax

相關問題