Gridview使用asynctask填充问题

时间:2013-03-24 15:12:10

标签: android gridview android-asynctask

我正在尝试用缩略图填充我的Gridview,但是我遇到了在asynctask中解码图像的问题。当我启动应用程序时,图像被逐个加载,图像无法正确显示(一旦我滚动它显示顶部图像并稍后加载原始图像)。这是我的代码:

public class ImageAdapter extends BaseAdapter {
    private Context mContext;
    private List<String> mList;
    private int mheight;
    private int mwidth;
    private InputStream is;

    public ImageAdapter(Context context, List<String> list, int height, int width) {
        mContext = context;
        mList = list;
        mheight = height;
        mwidth = width;
    }


    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position).toString();
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;
        if (convertView == null) {
            imageView = new ImageView(mContext);
        } else {
            imageView = (ImageView) convertView;
        }


        InputStream is;
        try {
            is = mContext.getAssets().open(mList.get(position));
            Loadimage task = new Loadimage(imageView , mheight , mwidth);
            task.execute(is);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return imageView ;

    }

    public class Loadimage extends AsyncTask<InputStream, Void, Bitmap>{
        private final WeakReference<ImageView> imageViewReference;


        private InputStream is = null;
        private int width;


        public Loadimage(ImageView imageView, int mheight, int mwidth) {
             imageViewReference = new WeakReference<ImageView>(imageView);
             this.width=mwidth;

            // TODO Auto-generated constructor stub
        }

        @Override
        protected Bitmap doInBackground(InputStream... params) {
            is = params[0];

            if (is !=null) {

                Bitmap bitmap  = BitmapFactory.decodeStream(is);
                Bitmap nBitmap =Bitmap.createScaledBitmap(bitmap,width/3 , width/3, false);
                return nBitmap;     
            }
            return null; 
          }
         @Override
         protected void onPostExecute(Bitmap bitmap) {
            if (imageViewReference != null && bitmap != null) {
                final ImageView imageView = imageViewReference.get();
                if (imageView != null) {
                    imageView.setImageBitmap(bitmap);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                }


        }
    }
}

1 个答案:

答案 0 :(得分:1)

我强烈推荐Universal Image Loader。它正是您所需要的:可以使用缩略图加载的gridview。它还具有内存和磁盘缓存功能,以及线程池大小的日志记录和功能。试试看;它对我来说非常合适,它应该符合您的需求。