【发布时间】:2014-12-12 16:01:36
【问题描述】:
我正在使用AsyncTask 在我的ListView 中延迟加载图像。
这一切正常,但我不明白为什么我必须在onPostExecute 方法中检查我的mHolder.hPosition 和mPosition。如果我不检查这些值,我会在不正确的ListItems 中循环获取旧图像 - 但是为什么mHolder.hPosition 和mPosition 在同一个AsyncTask 中被调用时并不总是相等?
这是我的精简代码:
@Override
public View getItemView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
final Job job = (Job) getStore().get(position);
if (convertView == null) {
// New List Item
holder = new ViewHolder();
convertView = getInflater().inflate(ITEM_LAYOUT, parent, false);
holder.hPosition = position;
holder.hImageView = (ImageView) convertView.findViewById(R.id.app_component_joblistitemview_logo);
convertView.setTag(holder);
} else {
// Recycled List Item
holder = (ViewHolder) convertView.getTag(); // get the ViewHolder that is stored in the Tag
holder.hPosition = position;
}
holder.hImageView.setImageBitmap(null); // set the list item's image to be blank
new DownloadImageTask().execute(position, holder); // async download the image
return convertView;
}
// DownloadImageTask
private class DownloadImageTask extends AsyncTask<Object, Void, Integer> {
Integer mPosition;
ViewHolder mHolder;
@Override
protected Integer doInBackground(Object... params) {
mPosition = (Integer)params[0];
mHolder = (ViewHolder)params[1];
// Download the Image ...
// ...
return 1;
}
protected void onPostExecute(Integer result) {
// >> This is the Spot I am Asking About <<
// Shouldn't mHolder.hPosition ALWAYS be equal to mPosition, since it's still the same AsyncTask?
// Why are mHolder.hPosition and mPosition often not equal?
if (mHolder.hPosition==mPosition) {
// ... update the List View Item
}
}
}
【问题讨论】:
-
因为您的支架可以在图像下载时重复使用
-
所以不是每次启动一个新的 AsyncTask 时都会创建一个新的/本地的 mHolder 实例吗?我是否应该在 AsyncTask 中使用来自持有者的值,因为它们可能会在我滚动列表时发生变化?
标签: android android-listview android-asynctask android-viewholder