2013-03-24 122 views
2

我想填充我的Gridview縮略圖圖像,但我有問題解碼圖像內的異形。當我啓動應用程序時,圖像被逐個加載,並且圖像顯示不正確(一旦我滾動顯示頂部圖像並在稍後加載原始圖像)。這裏是我的代碼: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); 
       } 


     } 
    } 
} 
+0

爲什麼不使用Universal Image Loader或Lazy list ?.還可以使用視圖來平滑滾動和執行。 – Raghunandan 2013-03-24 15:35:01

回答

1

我強烈推薦Universal Image Loader。它只是你需要的:一個可以用縮略圖加載的gridview。它還具有內存和磁盤緩存功能,以及用於線程池大小的日誌記錄和功能。試一試;它適用於我,完全適合您的需求。

+0

我試圖使用通用圖像加載器,但我在這裏有一個問題我的新帖http://stackoverflow.com/questions/15618989/gridview-with-universal-image-loader-images-are-loading-slowly – Joseph27 2013-03-25 15:44:05