我有一个列表视图与列表项中的图像。我正在使用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 那么我如何摆脱这一点,并正确加载在列表视图中正确的图像? 在此先感谢。
请使用图像加载程序库。链接:https://github.com/nostra13/Android-Universal-Image-Loader –
问题被问到bazillion次......它因为视图重用... 1. getView调用位置1你开始asynctask1 2. getView是再次调用位置2,来自点1的视图被重用,并且您正在开始asynctask2 ... 3. asynctask2完成并且右图像被设置4. asynctask1完成并设置错误的图像... **简单的解决方案(不是对于生产应用程序)将URL存储为imageview中的标记在设置位图之前将其与传递给AsyncTask的URL进行比较...如果它不同,请不要设置** – Selvin