由于某些原因,我的自定义适配器只允许我随时在列表视图中显示1个图像,我不知道为什么会发生这种情况。每个列表项中应该有一个图像,但只有最后一个列表项有图像集,所以我假设我重新使用了一个我不应该使用的值。其余的列表项目设置正确。
public class CustomAdapter extends ArrayAdapter<Item> {
private ArrayList<Item> itemList;
private ViewHolder holder;
private Context context;
public CustomAdapter(Context context, int textViewResourceId, ArrayList<Item> list) {
super(context, textViewResourceId, list);
this.itemList = new ArrayList<Item>();
this.itemList.addAll(list);
this.context = context;
}
private class ViewHolder {
ImageView img;
TextView name;
CheckBox access;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_grid, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.name);
holder.access = (CheckBox) convertView.findViewById(R.id.checkBox1);
holder.img = (ImageView) convertView.findViewById(R.id.imageView1);
convertView.setTag(holder);
}
else { holder = (ViewHolder) convertView.getTag(); }
Item it = itemList.get(position);
new UrlLookup().execute(it.getUrl());
holder.name.setText(it.getName());
holder.access.setChecked(it.isSelected());
return convertView;
}
//Create an image from the url passed in from the server and display it on the image view
private class UrlLookup extends AsyncTask<String, Integer, String>{
Bitmap bmp;
@Override
protected String doInBackground(String... params){
try {
URL u = new URL(params[0]);
bmp = BitmapFactory.decodeStream(u.openConnection().getInputStream());
} catch (Exception e) { e.printStackTrace(); }
return "Done!";
}
@Override
protected void onPostExecute(String result){
super.onPostExecute(result);
holder.img.setImageBitmap(bmp);
}
}
}
答案 0 :(得分:0)
您忘记了每次视图可见时您的持有人都会更改的事实。所以通常只有最后一个项目有图像。
AsyncTask的完成时间比getView
方法要长很多。
您应该将ImageView传递给AsyncTask:
new UrlLookup().execute(it.getUrl(), holder.img);
调用AsyncTask
private class UrlLookup extends AsyncTask<Object, Integer, String>{
Bitmap bmp;
ImageView view;
@Override
protected String doInBackground(Object... params){
view = (ImageView) params[1];
try {
URL u = new URL((String)params[0]);
bmp = BitmapFactory.decodeStream(u.openConnection().getInputStream());
} catch (Exception e) { e.printStackTrace(); }
return "Done!";
}
@Override
protected void onPostExecute(String result){
super.onPostExecute(result);
view.setImageBitmap(bmp);
}
}
现在,您将在每个AsyncTask中获得每行ImageView的引用。
我想向你们指出,Koush有一个出色的项目来做你想要的事情: UrlImageViewHelper