简体   繁体   中英

How to get ArrayList<String> image URLs into ImageView of ListView getView method

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView == null){
        convertView = inflater.inflate(resource, null);
    }

    ImageView imageView;
    imageView = (ImageView) convertView.findViewById(R.id.ivGallery);
    for(HospitalModel.Images images: hospitalModelList.get(position).getImagesList()) {
        Glide.with(getContext()).load(images).into(imageView);
    }
    return convertView;
}

// image URLs are stored in string ArrayList . I defined getter and setter for array list but still I don't know how to use get method for showing ArrayList images dynamically in ListView

Extend the class from BaseAdapter

Override getCount() method and return here the total amount of images you need to show.

In the getView load with Glide only ONE url (remove the for loop), the getView method will be called N times to show in the list the "total" amount of images you returned in the getCount method, the position parameter in the getView method will run from 0 to (total - 1).

You should map 1 position to 1 url, maybe you will need to change the way you access the objects that contain the urls.

Okay so first: stop using ListView, use RecyclerView.

Next, you need to override getItemCount(). You can either choose to do this using a for loop:

int count = 0;

for(HospitalModel.Images images: hospitalModelList.get(position).getImagesList()) {
    count += images.size();
}

Or, what is likely preferable, flatten your model object into just what this adapter actually cares about (which is the image URL strings). Something like this:

ArrayList<String> imageUrls = new ArrayList<String>();

for(HospitalModel model : hospitalModelList) {
    imageUrls.addAll(model.getImagesList().getImageUrls());
}

Then pass in the imageUrls ArrayList to the Adapter instead. You should only need to flatten this when the model is updated (whether that's initialization or changed). When that occurs, use the notify... methods on the adapter.

After that, it's just a simple Glide.with(getContext()).load(imageUrls.get(position)).into(imageView); inside getView (or onBindViewHolder if you're using a RecyclerView, which I HIGHLY recommend).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM