为什么我必须在AsyncTask onPostExecute中检查mPosition?

时间:2014-12-12 16:01:37

标签: android android-listview android-asynctask android-viewholder

我在AsyncTask

中使用ListView延迟加载图片

这一切都正常,但我不明白为什么我必须在mHolder.hPosition方法中检查我的mPositiononPostExecute。如果我不检查这些值,我会让旧图像循环显示错误的ListItems - 但如果调用它们,为什么mHolder.hPositionmPosition并不总是相等在同一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

            }
        }

    }

1 个答案:

答案 0 :(得分:2)

下载图像时,可以继续滚动列表视图。

ViewHolder可以回收利用,此时可以有其他数据。

要检查ViewHolder是否处于正确位置,您应该检查持有者的实际位置是否与在onPostExecute上生成下载事件的位置相同。