错误的图像显示在我的ListView行中

时间:2010-10-08 10:09:12

标签: android listview

我在getView中使用此代码:

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View v = convertView;
    if (v == null) {

        LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.listrow, null);
    }
    Order o = items.get(position);

    if (o != null) {
        TextView tt = (TextView) v.findViewById(R.id.toptext);
        ImageView thumb = (ImageView) v.findViewById(R.id.icon);

        if (o.getOrderDrawable() != null) {
            thumb.setImageDrawable(o.getOrderDrawable());
        } else {
            tt.setText(o.getOrderTitle());
        }

    }
    return v;
}

问题出在滚动时;有时会显示正确的图像,但有时向后/向前滚动时,图像会随机显示,并且与行无关。

图像从网上下载。

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:25)

Android的ListView会在不再需要时重复使用列表项。因此,您需要确保所有应更改的视图实际上都会更改。

您的问题是,如果您没有找到当前列表项的drawable,则不会清空也不隐藏ImageView。在这种情况下,您应该thumb.setImageDrawable(null),或thumb.setVisibility(View.GONE)

答案 1 :(得分:-1)

如果您停止使用convertView(您绝对应该这样做),并生成一个全新的View以便每次返回,它是否正常工作?我认为问题在于您重用视图的方式。

答案 2 :(得分:-1)

我尝试使用此处标记的解决方案是正确的,但它无法解决滚动期间错误图像的问题。 我尝试了第二个(ZsomborErdődy-Nagy),现在它真的很好。谢谢Zsombor: - )

这是我的片段:

    @Override
public View getView(int position, View convertView, ViewGroup parent) {
    /*
    View v = convertView;
    if (v == null) {
        LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = vi.inflate(R.layout.tweet_list, null);
    }
    */
    LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = vi.inflate(R.layout.tweet_list, null);
    final Status status = getItem(position);
    if (status != null) {
        TextView statusName = (TextView) v.findViewById(R.id.statusName);
        TextView statusText = (TextView) v.findViewById(R.id.statusText);
        TextView statusWhen = (TextView) v.findViewById(R.id.statusWhen);
        TextView statusScreenName = (TextView) v.findViewById(R.id.statusScreenName);
        final ImageView statusUserImage = (ImageView) v.findViewById(R.id.statusUserImage);
        statusName.setText(status.getUser().getName());
        statusScreenName.setText("@" + status.getUser().getScreenName());
        statusText.setText(status.getText());
        statusWhen.setText(dateTimeFormatter.format(status.getCreatedAt()));
        URL url = status.getUser().getProfileImageURL();
        String imageCacheKey = url.getPath();
        Drawable cachedImage = imageCache.get(imageCacheKey);
        if (null != cachedImage) {
            statusUserImage.setImageDrawable(cachedImage);
        } else {
            new DownloadImageTask(statusUserImage, imageCacheKey).execute(url);
        }

    }
    return v;
}