在Android中将图像下载到ListView中

时间:2013-04-18 13:41:28

标签: android listview android-asynctask lazy-loading adapter

我想将图片列表加载到来自互联网的列表视图中。每个列表项包含文本视图(即图像的url)和imageview。这是我的适配器类代码,用于下载图像并绑定到listview。但是图片与网址不匹配。几行具有相同的图像(但不同的URL)。有些行在一段时间后会改变它的图像。请帮帮我。

public class CustomAdapter extends BaseAdapter{

private Activity act;
private String imageUrlsArray[];
private LayoutInflater inflater;

public CustomAdapter(Activity activity, String imageUrls[]) {
    this.act = activity;
    this.imageUrlsArray = imageUrls;
    inflater = (LayoutInflater)this.act.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return imageUrlsArray.length;
}

@Override
public Object getItem(int arg0) {
    return null;
}

@Override
public long getItemId(int arg0) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    View rowView = convertView;

    if (rowView == null) { 

        rowView = inflater.inflate(R.layout.list_row, parent, false);

        holder = new ViewHolder();
        holder.imageView = (ImageView)rowView.findViewById(R.id.imageViewInListRow);
        holder.urlTextView = (TextView)rowView.findViewById(R.id.textViewInListRow);


        rowView.setTag(holder);

    }else{
        holder = (ViewHolder) rowView.getTag();

    } 
    loadImage(holder.imageView, imageUrlsArray[position]);
    holder.urlTextView.setText(imageUrlsArray[position]);

    return rowView;
}

private void loadImage(ImageView iv, String url) {
    DownloadTask asyncTask = new DownloadTask();
    asyncTask.execute(iv, url);
}

class DownloadTask extends AsyncTask<Object,Object, Object>{
    private ImageView iv;
    private InputStream is = null;
    private Drawable imageDrawable = null;
    @Override
    protected Object doInBackground(Object... params) {
        iv = (ImageView) params[0];

        try {
            is  = new DefaultHttpClient().execute(new HttpPost(params[1].toString())).getEntity().getContent();
            imageDrawable = Drawable.createFromStream((InputStream)is , "src name");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imageDrawable;
    }
    @Override
    protected void onPostExecute(Object response) {
        super.onPostExecute(response);
        if(response != null){
            iv.setImageDrawable((Drawable)response);
        } 


    }

}
static class ViewHolder{
    public TextView urlTextView;
    public ImageView imageView;
}

}

1 个答案:

答案 0 :(得分:2)

使用hashMap与textview进行正确映射。首先将url转换为适配器中的图像位图。