2013-12-21 4 views
1

Я работаю над полноэкранным галерея, и я разрабатываю свой пользовательский адаптер. Я хочу показать изображение держателя места для всех моих представлений при первом запуске приложения и с прокруткой представлений (изображений) загрузки растровых изображений из пути к файлу.установка место держатель для пользовательского полноэкранного адаптера

Я использую Loading bitmaps efficiantly учебник для загрузки растровых изображений.

Моя проблема заключается в том, что это placeHolder изображение просто показано в приложении, и оно не загружает другие изображения.

Я попытался установить растровое изображение mPlaceHolder в разных местах, таких как doInBackground и onPostExecute, в моем классе AsyncTask, но это не помогает мне.

Мне что-то не хватает?

вот мой адаптер код:

public View getView(int position, View convertView, ViewGroup parent) { 
    ImageView imageView; 

    if (convertView == null) { 
     imageView = new ImageView(mContext); 
     imageView.setAdjustViewBounds(true); 
     imageView.setPadding(20, 0, 20, 0); 
     imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
    } else { 
     imageView = (ImageView) convertView; 
    } 

    try { 
     loadBitmap(imagePaths.get(position), imageView); 
    } catch (Exception e) { 
     // TODO: handle exception 
    } 

    //Bitmap bitmap =decodeFiles(imagePaths.get(position),width,height); 
    /* 
    try{ 
     image = decodeFile(new File(imagePaths.get(position)),screenMaxSize); 
    } 
    catch (Exception e) { 
     // TODO: handle exception 
     Log.i("erroe", imagePaths.get(position)); 
    } 
    */ 


    //imageView.setImageBitmap(bitmap); 

    //imageView.setLayoutParams(new GridView.LayoutParams(90, 70)); 

    return imageView; 


} 

public void loadBitmap(String filePath, ImageView imageView) { 
    if (cancelPotentialWork(filePath, imageView)) { 
     final BitmapWorkerTask task = new BitmapWorkerTask(imageView); 
     final Bitmap *mPlaceHolderBitmap* = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.gallery_icon); 

     final AsyncDrawable asyncDrawable = 
       new AsyncDrawable(mContext.getResources(), mPlaceHolderBitmap, task); 
     imageView.setImageDrawable(asyncDrawable); 
     task.execute(filePath); 
    } 
} 


public Bitmap decodeFiles(String pathName, int reqWidth,int reqHeight){ 

    // First decode with inJustDecodeBounds=true to check dimensions 
    final BitmapFactory.Options options = new BitmapFactory.Options(); 
    options.inJustDecodeBounds = true; 
    BitmapFactory.decodeFile(pathName, options); 

    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); 
    /* 
    int scale = 1; 
    if (o.outHeight > screenMaxSize || o.outWidth > screenMaxSize) { 
     scale = (int)Math.pow(2, (int) Math.round(Math.log(screenMaxSize/(double) Math.max(o.outHeight, o.outWidth))/Math.log(0.5))); 
    } 
    */ 

    //Decode with inSampleSize 
    options.inJustDecodeBounds = false; 

    return BitmapFactory.decodeFile(pathName, options); 
} 

private int calculateInSampleSize(Options options, int reqWidth, int reqHeight) { 
    // TODO Auto-generated method stub 
    // Raw height and width of image 
    final int height = options.outHeight; 
    final int width = options.outWidth; 
    int inSampleSize = 1; 

    if (height > reqHeight || width > reqWidth) { 

     final int halfHeight = height/2; 
     final int halfWidth = width/2; 

     // Calculate the largest inSampleSize value that is a power of 2 and keeps both 
     // height and width larger than the requested height and width. 
     while ((halfHeight/inSampleSize) > reqHeight 
       && (halfWidth/inSampleSize) > reqWidth) { 
      inSampleSize *= 2; 
     } 
    } 

    return inSampleSize; 
} 


public static boolean cancelPotentialWork(String filePath, ImageView imageView) { 
    final BitmapWorkerTask bitmapWorkerTask = getBitmapWorkerTask(imageView); 

    if (bitmapWorkerTask != null) { 
     final String bitmapData = bitmapWorkerTask.data; 
     if (bitmapData != filePath) { 
      // Cancel previous task 
      bitmapWorkerTask.cancel(true); 
     } else { 
      // The same work is already in progress 
      return false; 
     } 
    } 
    // No task associated with the ImageView, or an existing task was cancelled 
    return true; 
} 

private static BitmapWorkerTask getBitmapWorkerTask(ImageView imageView) { 
     if (imageView != null) { 
      final Drawable drawable = imageView.getDrawable(); 
      if (drawable instanceof AsyncDrawable) { 
       final AsyncDrawable asyncDrawable = (AsyncDrawable) drawable; 
       return asyncDrawable.getBitmapWorkerTask(); 
      } 
     } 
     return null; 
} 

class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> { 
    private final WeakReference<ImageView> imageViewReference; 
    private String data = ""; 

    public BitmapWorkerTask(ImageView imageView) { 
     // Use a WeakReference to ensure the ImageView can be garbage collected 
     imageViewReference = new WeakReference<ImageView>(imageView); 
    } 

    // Decode image in background. 
    @Override 
    protected Bitmap doInBackground(String... params) { 
     data = params[0]; 
     return decodeFiles(data, width, height); 
    } 

    // Once complete, see if ImageView is still around and set bitmap. 
    @Override 
    protected void onPostExecute(Bitmap bitmap) { 
     if (isCancelled()) { 
      bitmap = null; 
     } 

     if (imageViewReference != null && bitmap != null) { 
      final ImageView imageView = imageViewReference.get(); 
      final BitmapWorkerTask bitmapWorkerTask = 
        getBitmapWorkerTask(imageView); 
      if (this == bitmapWorkerTask && imageView != null) { 
       imageView.setImageBitmap(bitmap); 
      } 
     } 

    } 
} 

static class AsyncDrawable extends BitmapDrawable { 
    private final WeakReference<BitmapWorkerTask> bitmapWorkerTaskReference; 

    public AsyncDrawable(Resources res, Bitmap bitmap, BitmapWorkerTask bitmapWorkerTask) { 
     super(res, bitmap); 
     bitmapWorkerTaskReference = 
      new WeakReference<BitmapWorkerTask>(bitmapWorkerTask); 
    } 

    public BitmapWorkerTask getBitmapWorkerTask() { 
     return bitmapWorkerTaskReference.get(); 
    } 
} 

ответ

0

Это, вероятно, потому, что вы не уведомляя адаптер в сообщении Execute:

protected void onPostExecute(Bitmap bitmap) { 
    if (isCancelled()) { 
     bitmap = null; 
    } 

    if (imageViewReference != null && bitmap != null) { 
     final ImageView imageView = imageViewReference.get(); 
     final BitmapWorkerTask bitmapWorkerTask = 
       getBitmapWorkerTask(imageView); 
     if (this == bitmapWorkerTask && imageView != null) { 
      imageView.setImageBitmap(bitmap); 
     } 
    } 
    <YoutAdapterName>.this.notifyDataSetChanged()//<<---do it here 

} 
+0

Tnx для ответа, но я просто вижу первый инициализированный растровый рисунок для всех моих изображений :-( –

-1

Сделать mPlaceHolderBitmap переменную уровню адаптера и установить его перед вызовом loadBitmap() ,

+0

Неужели я серьезно зашел, потому что кому-то не понравился синтаксис моего (правильного) ответа? Это был первый ответ, который я беспокоил чтобы дать, и с таким видом приема, вероятно, будет моим последним. Отличный способ приветствовать новых пользователей! – atariguy

Смежные вопросы