简体   繁体   中英

Android ListView: load items only on scroll

I have a custom adapter for a list view. It has 3 fields: a thumbnail and two text fields.

Once the layout is inflated, the thumbnails are downloaded from an external server.

How do i change the functionality so that the images are downloaded only when the user scrolls down.

@Override
public View getView(int position, View convertView, ViewGroup parent) {

    // Inflate the layout
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View rowView = inflater.inflate(R.layout.list_single, parent, false);

    ImageView image = (ImageView) rowView.findViewById(R.id.picture);
    TextView firstline = (TextView) rowView.findViewById(R.id.firstline);
    TextView secondline = (TextView) rowView.findViewById(R.id.secondline);         

    // Get information about the report
    AnimalLocationLog current = objects.get(position);

    // Get all the important information
    String species = current.getSpecies();
    String sanitizedSpecies = MiscHelpers.sanitizeString(species);
    int reportId = objects.get(position).getTrackerId();

    // Construct the URL to the image
    String imageLocation = websiteUrl + sanitizedSpecies + separator + reportId + extension;

    // Display user report          
    downloader.download(imageLocation, image);          
    firstline.setText(species);
    secondline.setText("Spotted " + current.getDateTime().toString("yyyy-MM-dd H:m"));

    return rowView;
}

Add an OnScrollListener to your ListView with ListView.setOnScrollListener() and do the download in the ScrollListener.onScroll() method. You can use the ListView.getLastVisiblePosition() to figure out what list items are visible and which aren't.

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