我在列表项中有一个带有图像的列表视图。我正在为listview使用自定义适配器。我正在使用AsyncTask下载适配器中每个列表项的图像。我的自定义适配器的代码:
public class AdapterUcomment extends ArrayAdapter<UserModel> {
public AdapterUcomment(Activity context, List<UserModel> list) {
super(context, R.layout.layout_comment_item, list);
this.context = context;
this.list = list;
}
class ViewHolder {
protected TextView text1, text2, text3;
protected ImageView imagev;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.layout_comment_item, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text1 = (TextView) view.findViewById(R.id.txtv_uname);
viewHolder.text2 = (TextView) view.findViewById(R.id.txtv_comment);
viewHolder.text3 = (TextView) view.findViewById(R.id.txtv_cmntTime);
viewHolder.imagev = (ImageView) view.findViewById(R.id.imgv_upic);
view.setTag(viewHolder);
} else {
view = convertView;
}
positionPic = position;
final ViewHolder holder = (ViewHolder) view.getTag();
String uname = list.get(position).getUname();
String ufbid = list.get(position).getUfbid();
String ucomment = list.get(position).getUcomment();
String ucomment_time = list.get(position).getUcomment_time();
holder.text1.setText(Html.fromHtml(uname));
holder.text2.setText(Html.fromHtml(ucomment));
holder.text3.setText(Html.fromHtml(ucomment_time));
// downloading the image using AsyncTask
new UserPic(position, ufbid, holder.imagev).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return view;
}
public class UserPic extends AsyncTask<String, Void, String> {
String ufbid = null;
Bitmap bitmap = null;
ImageView imageView;
int pos = 0;
public UserPic(int pos, String ufbid, ImageView imageView) {
this.ufbid = ufbid;
this.imageView = imageView;
this.pos = pos;
}
@Override
protected String doInBackground(String... strings) {
URL imageURL = null;
try {
imageURL = new URL(".......");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
bitmap = BitmapFactory.decodeStream(imageURL.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String s) {
imageView.setImageBitmap(bitmap);
super.onPostExecute(s);
}
}
乍一看似乎一切都很好: image of listview with properly loaded images 但是当我向下滚动到最后一个项目然后再次向上滚动到第一个项目然后第一个列表项目图像消失时,问题就开始了:image of listview with improperly loaded image 那么我怎样才能摆脱这种情况并在listview中正确加载图像呢? 提前谢谢。
答案 0 :(得分:1)
使用像Picasso或Glide这样的图像加载库将图像加载到列表视图中。另外,您是否考虑过使用Recyclerview?
以下是有关毕加索的更多信息: http://square.github.io/picasso/