自定义ArrayAdapter在滚动后显示重复的图像

时间:2014-10-31 15:50:37

标签: android android-listview android-arrayadapter

我是Android的新手,通过使用ArrayAdapter,我试图创建一个带有标题和图像的listView。我从sqlite databae获取图像。(我知道,不推荐),但到目前为止,我能够创建所需的listView。

listView中有一些项目,没有图像,有些有图像,我遇到的问题是当我向上和向下滚动然后我的图像重复。那些没有图像的图像从列表中获取随机图像。

我搜索了网页并找到了相关主题,但这并没有解决我的问题。

我的ArrayAdapter代码:

public class CustomListViewAdapter extends ArrayAdapter<DataItems> 
{
  Context context;
  LayoutInflater mInflater;

  public CustomListViewAdapter(Context context, int resourceId, List<DataItems> items) 
  {
    super(context, resourceId, items);
    this.context = context;
    mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
  }

  /* private view holder class */
  private class ViewHolder 
  {
     ImageView thumdnail;           
     TextView txtTitle;
  } 

  public View getView(int position, View convertView, ViewGroup parent)
  {
    ViewHolder holder = null;
    DataItems rowItem = getItem(position);

    if (convertView == null) 
    {
      holder = new ViewHolder();

      convertView = mInflater.inflate(R.layout.list_item2, null, false);

      holder.thumdnail = (ImageView) convertView.findViewById(R.id.thumbnail2); 
      holder.txtTitle = (TextView) convertView.findViewById(R.id.mytitle2);

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


    holder.txtTitle.setText(rowItem.getTitle());

    if(rowItem.getThumbnailImageId() != null)
    {
      // here getImage() is converting byte array to bitmap

      Bitmap b2 = getImage(rowItem.getThumbnailImageId());
      Drawable drawable2 = new BitmapDrawable(b2);
      holder.thumdnail.setBackground(drawable2);
    }

    return convertView;

}

请你告诉我,我在这里做错了什么?

2 个答案:

答案 0 :(得分:4)

感谢 njzk2 ,似乎您的问题是我们忘记在if语句中再次将visibility设置为VISIBLE

如果没有图片,您需要指定geView将执行的操作:

if(rowItem.getThumbnailImageId() != null)
        {
            // here getImage() is converting byte array to bitmap

            Bitmap b2 = getImage(rowItem.getThumbnailImageId());
            Drawable drawable2 = new BitmapDrawable(b2);
            holder.thumdnail.setBackground(drawable2);

            holder.thumdnail.setVisibility(View.VISIBLE);
        }
    else
    {
      //hide the image, or do anything you like when theres no image
      holder.thumdnail.setVisibility(View.GONE);
    }

这一点在 else 代码中,因此listview知道在有图像时你要做什么(你的if语句)以及是否有(else语句)。< / p>

并尝试让你的持有人类静态:

private static class ViewHolder

答案 1 :(得分:1)

如果您没有thumbnailID,则应隐藏ImageView:

if(rowItem.getThumbnailImageId() != null)
    {
        holder.thumdnail.setVisibility(View.VISIBLE);

        Bitmap b2 = getImage(rowItem.getThumbnailImageId());
        Drawable drawable2 = new BitmapDrawable(b2);
        holder.thumdnail.setBackground(drawable2);
    }
else
{
     holder.thumdnail.setVisibility(View.GONE);
}