2012-10-10 21 views
5

tengo un adaptador con este getView:getView es llamado varias veces para la primera posición en GridView

public View getView(int position, View convertView, ViewGroup parent) { 
    Log.d("getView gv", position+""); 

    NewsLine holder = null; 

    if (convertView == null) { 
     LayoutInflater inflater = ((Activity) context).getLayoutInflater(); 
     convertView = inflater.inflate(R.layout.grid_entry, parent, false); 
     holder = new NewsLine(); 

     holder.iv= (ImageView) convertView.findViewById(R.id.photo); 

     convertView.setTag(holder); 
    } else { 
     holder = (NewsLine) convertView.getTag(); 
    } 

    NewsItem item=news.ITEMS.get(position); 
    //--------- 

    if(item.imgurl!=null && item.imgurl.compareToIgnoreCase("null")!=0) 
    { 
     holder.iv.setVisibility(View.VISIBLE);  
     mMemoryCache.loadBitmap(item.imgurl, holder.iv,position); 
    } 
    else 
     holder.iv.setVisibility(View.INVISIBLE); 
    //------------- 




    return convertView; 
} 

Tengo dos problemas:

  1. la getView se llama varias veces por la posición 0 (el mapa de bits se descarga con una AsyncTask si se pierde en un LruCache). Tengo una animación (alfa de 0 a 1) que se reinicia varias veces para esa posición.

  2. porque estoy reciclando la vista, a veces se puede ver el viejo contenido de imageView durante una fracción de segundo.

// ----

Y aquí es la clase de caché (sólo montón):

public class SetImgAT extends LruCache<String, Bitmap> { 
private static SetImgAT instance; 
private Animation FadeInAnimation; 

private SetImgAT(int size, Context context) { 
    super(size); 
    FadeInAnimation = AnimationUtils.loadAnimation(context, R.anim.fadein); 
} 

public static synchronized SetImgAT getInstance(int size, Context context) { 
    if (instance == null) { 
     instance = new SetImgAT(size, context); 
    } 
    return instance; 
} 

@Override 
protected int sizeOf(String key, Bitmap value) { 
    return (value.getRowBytes() * value.getHeight()); 
} 

public void loadBitmap(String url, ImageView imageView,int pos) { 
    Bitmap bitmap = instance.get(url.hashCode() + ""); 
    if (bitmap != null) { 
     Log.d("ImageCache", "hit - "+url.hashCode()+"pos:"+pos); 
     imageView.setImageBitmap(bitmap); 

     imageView.invalidate(); 
    } else { 
     Log.d("ImageCache", "miss"); 
     BitmapWorkerTask task = new BitmapWorkerTask(imageView); 
     task.execute(url); 
    } 
} 

class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> { 
    ImageView mImageView; 

    public BitmapWorkerTask(ImageView imageView) { 
     mImageView = imageView; 
    } 

    @Override 
    protected Bitmap doInBackground(String... url) { 
     Bitmap Picture = null; 


     if (url[0] != null && url[0].compareToIgnoreCase("null") != 0) { 
      Log.d("GetBMP from", url[0]); 

      URL img_value = null; 
      try { 
       img_value = new URL(url[0]); 
      } catch (MalformedURLException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      try { 
       Picture = BitmapFactory.decodeStream(img_value 
         .openConnection().getInputStream()); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      if (Picture == null) { 
       Log.d("deb", "no bitmap"); 
      } else { 
       Log.d("got deb", "got bitmap to "+url[0].hashCode());     
       instance.put(url[0].hashCode()+"", Picture); 
      } 

     } 
     return Picture; 
    } 

    @Override 
    protected void onPostExecute(Bitmap result) { 
     // super.onPostExecute(result); 
     if (result != null) { 
      Log.d("deb", "set bitmap"); 
      mImageView.setImageBitmap(result); 
      //mImageView.startAnimation(FadeInAnimation); 
     } 

    } 
} 

// ------------- ---

}

Gracias! :)

+0

Para la pregunta # 2, intente llamar 'mMemoryCache.loadBitmap()' 'antes setVisibility()' para evitar que el vieja imagen de aparecer. – Sam

+2

"el getView se llama varias veces para la posición 0" - Este es un comportamiento perfectamente normal. No hay reglas sobre cuántas veces se llamará a 'getView() 'para una posición. En general, StackOverflow es para preguntas de programación, y usted no ha hecho una pregunta. – CommonsWare

+0

Sam no funcionó, parece que hay mucho más que ocupar, voy a través de la muestra para el almacenamiento en caché de mapas de bits de http://developer.android.com/training/displaying-bitmaps/cache-bitmap. html. en CommonsWare gracias, no creo que deba reformular esto como una pregunta, tal vez puedas intentarlo. – Misca

Respuesta

0

He visto un comportamiento similar cuando se desplaza hacia adelante y hacia atrás o al azar llamando a notifyDataSetChanged().

Como una mejora de lo que está haciendo ahora, le sugiero que use Picasso, ya que maneja muy bien este caso, además del desvanecimiento en la animación.

Un chiste en su getView():

Picasso.with(context).load(urlToLoad).into(imageView); 

Ver: http://square.github.io/picasso/

Cuestiones relacionadas