0

我想从互联网将图像列表加载到列表视图中。每个列表项都包含一个 textview(即图像的 url)和一个 imageview。这是我的适配器类代码,用于下载图像并绑定到列表视图。但是图片与网址不匹配。几行具有相同的图像(但不同的 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;
}

}

4

1 回答 1

2

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

于 2013-04-18T13:46:28.710 回答