Библиотека Пикассо: ImageView в ListView Shows загружает изображение несколько раз при быстрой прокрутке

Я загружаю удаленное изображение в строку listView, используя обратный вызов picaso. Но изображение меняется несколько раз, когда listView прокручивается очень быстро. Я предполагаю, что это связано с повторным использованием строк. Как я могу исправить это и показать правильное изображение без перезагрузки разных изображений в imageView.

Я также устанавливаю нулевое растровое изображение в ImageView. Так что он не использует предыдущее изображение при повторном использовании изображения

Вот мой код:

      @Override
public View getView(int position, View convertView, ViewGroup arg2)
{
    ViewHolder holder = null;

    if (convertView == null)
    {
        LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = vi.inflate(R.layout.row_health, arg2, false);
        holder = new ViewHolder();

        convertView.setTag(holder);

    }

    else
    {
        holder = (ViewHolder) convertView.getTag();

        holder.imageOfDoctor_select.setImageBitmap(null);

    }
  loadImage("imageViewURL", relLyt_txtPicInitials, imgVw);
}


 private void loadImage(String imgURL, RoundedImage imgVw, RelativeLayout relLyt_txtPicInitials){

 Target target = new Target() {
        @Override
        public void onBitmapFailed(Drawable arg0)
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void onPrepareLoad(Drawable arg0)
        {
            // TODO Auto-generated method stub

        }

        @Override
        public void onBitmapLoaded(Bitmap bitmap, LoadedFrom arg1)
        {
            if(bitmap != null){
                imgVw.setVisibility(View.VISIBLE);
                imgVw.setImageBitmap(bitmap);
                relLyt_txtPicInitials.setVisibility(View.GONE);
            }


        }
    };
    if (!TextUtils.isEmpty(imgURL) && !imgURL.equalsIgnoreCase("null") && URLUtil.isValidUrl(imgURL))
    {
        Picasso.with(context).load(imgURL).into(target);
    }

  }

RoundedImage.java

  public class RoundedImage extends ImageView
 {

private float cornerRadius;
private float bitmapCornerRadius;

public RoundedImage(Context context, AttributeSet attrs, int defStyle)
{
    super(context, attrs, defStyle);
    getXMLAttribute(context, attrs);

    // TODO Auto-generated constructor stub
   }




            public RoundedImage(Context context, AttributeSet attrs)
      {
    super(context, attrs);
    getXMLAttribute(context, attrs);

    // TODO Auto-generated constructor stub
}

public RoundedImage(Context context)
{
    super(context);
    // TODO Auto-generated constructor stub
}

@Override
public void setImageBitmap(Bitmap bm)
{
    if (bm != null)
    {
        bm = Utils.getRoundedCornerBitmap(bm, 50);
    }
    super.setImageBitmap(bm);
}

private void getXMLAttribute(Context context, AttributeSet attrs)
{
    // Get proportion.
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RoundedCornerImageView);
    cornerRadius = a.getDimension(R.styleable.RoundedCornerImageView_cornerRadius, 0);
    a.recycle();
}

public void setCornerRadius(int radius)
{
    this.cornerRadius = radius;
}

@Override
protected void onDraw(Canvas canvas)
{
    boolean applyCornerToBitmap = false;

    Drawable drawable = getDrawable();
    if (drawable != null)
    {
        Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
        if (bitmap != null)
        {
            int viewWidth = getWidth();
            if (viewWidth != 0f)
            { // Only round the corner if view width is not zero.
                // Calculate the corner radius on the real bitmap, based on
                // the
                // corner radius of the view.
                int bitmapWidth = bitmap.getWidth();
                float newBitmapCornerRadius = cornerRadius * bitmapWidth / viewWidth;

                // If newBitmapCornerRadius equals to bitmapCornerRadius,
                // then it is not needed to set the round the corner bitmap
                // to the drawable again.
                if (bitmapCornerRadius != newBitmapCornerRadius)
                {
                    applyCornerToBitmap = true;
                    // Create bitmap with rounded corner.
                    int bitmapHeight = bitmap.getHeight();
                    bitmapCornerRadius = newBitmapCornerRadius;
                    bitmap = Utils.getRoundedCornerBitmap(bitmap, 50);
                    // Set rounded corner bitmap to the view's drawable.
                    setImageBitmap(bitmap); // This will call onDraw()
                                            // again.
                }
            }
        }
    }
    // Call super onDraw() if the drawable has already been rounded.
    if (!applyCornerToBitmap)
    {
        super.onDraw(canvas);
    }
}

}


person user1288005    schedule 25.02.2015    source источник


Ответы (1)


Измените так, вы правильно догадались, проблема связана с повторным использованием представлений, и в каждом методе getView все изображения должны очищаться, например, установить заполнитель или установить ноль, я точно не знаю imgVw илиholder.imageOfDoctor_select должен сбросить, попробуйте их оба

Как я могу исправить это и показать правильное изображение без перезагрузки разных изображений в imageView.

Вы не можете, потому что ImageView все еще содержит предыдущее изображение

@Override
public View getView(int position, View convertView, ViewGroup arg2) {
    ViewHolder holder = null;

    if (convertView == null) {
        LayoutInflater vi = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = vi.inflate(R.layout.row_health, arg2, false);
        holder = new ViewHolder();
        convertView.setTag(holder);

    }
    else {
        holder = (ViewHolder) convertView.getTag();
    }
    holder.imageOfDoctor_select.setImageBitmap(null); //Or put placeholder here, until image loaded
    loadImage("imageViewURL", relLyt_txtPicInitials, imgVw);
}

Я могу предложить другое решение, без цели, просто используйте public void into(android.widget.ImageView target, com.squareup.picasso.Callback callback) эту перегрузку, аналогичную этой

Picasso.with(getContext())
            .load(imgVw)
            .into(imgVw, new Callback() {
                @Override
                public void onSuccess() {
                    imgVw.setVisibility(View.VISIBLE);
                    relLyt_txtPicInitials.setVisibility(View.GONE);
                }

                @Override
                public void onError() {

                }
            });
person mes    schedule 25.02.2015
comment
onSuccess не дает BitMap, который можно установить в imageView. - person user1288005; 25.02.2015
comment
извините, я удаляю эту строку, Picasso устанавливает растровое изображение автоматически, вам не нужно получать растровое изображение и устанавливать его вручную - person mes; 25.02.2015