在基本适配器中使用异步任务加载文件缩略图的列表视图

Using async task in a baseadapter to load listview of file thumbnails

我正在尝试将图片文件列表从我的设备存储加载到用户可以与之交互的列表视图中。我目前正在使用视图持有者模式来清理滚动,但似乎这还不够,因为列表中的图片越多,滚动就越不稳定。我研究过使用异步任务,但我不熟悉使用它来填充涉及基本适配器的缩略图列表视图。

这些是我列表视图中的对象类型。每个项目都是在另一个 class.

中定义的 "Selfie" 对象

这是我从 BaseAdapter 获取的视图:

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    Log.v(TAG, "in getView for position " + position +
            ", convertView is " +
            ((convertView == null)?"null":"being recycled"));

    View newView = convertView;
    ViewHolder holder;

    if (null == convertView) {

        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        newView = inflater.inflate(R.layout.single_item, null);

        holder = new ViewHolder();
        holder.description = (TextView) newView.findViewById(R.id.textView1);
        holder.picture = (ImageView) newView.findViewById(R.id.imageView1);
        newView.setTag(holder);

    } else {
        holder = (ViewHolder) newView.getTag();
    }

    holder.picture.setScaleType(ImageView.ScaleType.CENTER_CROP);

    SelfieObject selfie = (SelfieObject) getItem(position);
    setPic(holder.picture, new Point(WIDTH, HEIGHT), selfie.getPath());

    TextView textView = (TextView) holder.description;
    textView.setText(selfie.getName());


    return newView;
}

static class ViewHolder {

    ImageView picture;
    TextView description;   

这是我希望从 Developers 站点使用的异步代码:

new AsyncTask<ViewHolder, Void, Bitmap>() {
private ViewHolder v;

@Override
protected Bitmap doInBackground(ViewHolder... params) {
    v = params[0];
    return mFakeImageLoader.getImage();
}

@Override
protected void onPostExecute(Bitmap result) {
    super.onPostExecute(result);
    if (v.position == position) {
        // If this item hasn't been recycled already, hide the
        // progress and set and show the image
        v.progress.setVisibility(View.GONE);
        v.icon.setVisibility(View.VISIBLE);
        v.icon.setImageBitmap(result);
    }
  }
}.execute(holder);

任何人都可以指出我如何在 BaseAdapter 中实现它的正确方向吗? Android 开发代码对于我正在做的事情来说似乎太通用了。

您应该扩展 AsyncTask class,例如:

public void onClick(View v) {
    new DownloadImageTask().execute("http://example.com/image.png");
    }

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
    /** The system calls this to perform work in a worker thread and
      * delivers it the parameters given to AsyncTask.execute() */
    protected Bitmap doInBackground(String... urls) {
        return loadImageFromNetwork(urls[0]);
    }

    /** The system calls this to perform work in the UI thread and delivers
      * the result from doInBackground() */
    protected void onPostExecute(Bitmap result) {
        mImageView.setImageBitmap(result);
    }
}