Using AsyncTask to load images into a custom adapter

前端 未结 2 1438
心在旅途
心在旅途 2020-12-30 13:20

Although there are many tutorials out there, I\'ve found it really difficult to implement an AsyncTask to load images from URI\'s (obtained from a content provider) into a c

相关标签:
2条回答
  • 2020-12-30 13:48

    You need to pass your AsyncTask the view so that it can update it when it completes:

    //Run ImageLoader AsyncTask here, and let it set the ImageView when it is done.
    new ImageLoader().execute(view, uri);
    

    And modify AsyncTask so that it can handle mixed parameter types:

    public class ImageLoader extends AsyncTask<Object, String, Bitmap> {
    
        private View view;
        private Bitmap bitmap = null;
    
        @Override
        protected Bitmap doInBackground(Object... parameters) {
    
            // Get the passed arguments here
            view = (View) parameters[0];
            String uri = (String)parameters[1];
    
            // Create bitmap from passed in Uri here
            // ...
            return bitmap;
        }
    
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null && view != null) {
                ImageView albumArt = (ImageView) view.getTag(R.id.albumArt);
                albumArt.setImageBitmap(bitmap);
            }
        }
    }
    

    I haven't tested this code but it should give you an idea.

    0 讨论(0)
  • 2020-12-30 14:02

    Why are you doing setImage in AsyncTask? You can do it in a thread. I don't think in this condition AsyncTask would be good. Better you do it in different thread.

    0 讨论(0)
提交回复
热议问题