Android将viewImage设置为ListView

时间:2013-11-24 19:25:54

标签: android listview

我需要在ListView中设置ImageView。我从网上下载图像到我的列表。 为此,我尝试扩展BaseAdapter并覆盖方法。 我正在使用UrlImageViewHelper。 所以我发现了一个麻烦。有时我应该展示一个图像,有时候不会。 但我的列表单元格总是显示图像。

class MySimpleAdapter extends BaseAdapter {


    ArrayList<WallMessage> posts;
    HashMap<Long, User> distinctUsers;
    Activity activity;
    WallMessage post;
    User user;
    LayoutInflater inflater=null;

    public MySimpleAdapter(Activity a, ArrayList<WallMessage> posts, HashMap<Long, User> distinctUsers) {
        this.activity = a;
        this.distinctUsers = distinctUsers;
        this.posts = posts;
        for(int i = 0; i < posts.size(); i++) {
            Log.d("myLogs", "attachSize = " + posts.get(i).attachments.size());
        }
        inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return posts.size();
    }

    @Override
    public Object getItem(int position) {
        return posts.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView == null)
            vi = inflater.inflate(R.layout.wall_item, null);

        TextView authorTv = (TextView) vi.findViewById(R.id.author);
        TextView postTv = (TextView) vi.findViewById(R.id.post); 
        TextView dateTv = (TextView) vi.findViewById(R.id.date); 
        TextView likesTv = (TextView) vi.findViewById(R.id.likes); 
        ImageView imagePhoto =(ImageView) vi.findViewById(R.id.imagePhoto);
        ImageView imagePost = (ImageView) vi.findViewById(R.id.imagePost);

        post = posts.get(position);
        user = distinctUsers.get(post.from_id);
        authorTv.setText(user.first_name + " " + user.last_name);
        postTv.setText(post.text);
        dateTv.setText(parseDate(post.date));
        likesTv.setText(Long.toString(post.like_count));
        UrlImageViewHelper.setUrlDrawable(imagePhoto, user.photo);

        if(post.attachments != null && post.attachments.size() != 0) {
            UrlImageViewHelper.setUrlDrawable(imagePost, post.attachments.get(0).photo.src);
        }
        return vi;
    }
}

我知道我有post.attachments.size()== 0的元素。 但我的列表显示从其他单元格加载的所有相同图像。

1 个答案:

答案 0 :(得分:0)

当您使用covertView时,您可以在重用的视图中获取以前存储的值。 试试:

UrlImageViewHelper.setUrlDrawable(imagePhoto, user.photo);

    if (post.attachments != null && post.attachments.size() != 0) {
        UrlImageViewHelper.setUrlDrawable(imagePost, post.attachments.get(0).photo.src);
    } else {
        imagePost.setVisibility(View.INVISIBLE);
        // above can be any default url using UrlImageViewHelper 
        // or just some local resource like 
        // imagePost.setImageResource(R.drawable.some_default_drawable_resource);
    }