简体   繁体   中英

How to load image using glide in advance?

Actually I'm trying to load images into my reycycleview using glide 4.4.0 and it's loading fine . But now the problem is my recyclerview is lagging a bit when I scroll fast due to the image loading . But I saw some of the glide's method called preload and downloadOnly .So,my question is are these methods helpful for loading image in advance if so then how to use them?

You can use this to fine-tune your preloading. It requires quite a bit of work but looks promising.

In short, you need to create a PreLoader class that will get image URLs from your data set:

private class MyPreloadModelProvider implements PreloadModelProvider {
    @Override
    @NonNull
    public List<U> getPreloadItems(int position) {
      String url = myUrls.get(position);
      if (TextUtils.isEmpty(url)) {
        return Collections.emptyList();
      }
      return Collections.singletonList(url);
    }

    @Override
    @Nullable
    public RequestBuilder getPreloadRequestBuilder(String url) {
        return 
            GlideApp.with(fragment)
              .load(url) 
              .override(imageWidthPixels, imageHeightPixels);
    }
}

And then you set it as a scroll listener on your recycler view:

PreloadSizeProvider sizeProvider = 
    new FixedPreloadSizeProvider(imageWidthPixels, imageHeightPixels);
PreloadModelProvider modelProvider = new MyPreloadModelProvider();
RecyclerViewPreloader<Photo> preloader = 
    new RecyclerViewPreloader<>(
        Glide.with(this), modelProvider, sizeProvider, 10 /*maxPreload*/);

RecyclerView myRecyclerView = (RecyclerView) result.findViewById(R.id.recycler_view);
myRecyclerView.addOnScrollListener(preloader);

After this, you'll get your images preloaded before the onBondViewHolder callback in the adapter, and you'll be able to display them from the cache.

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
  ImageView imageView = ((MyViewHolder) viewHolder).imageView;
  String currentUrl = myUrls.get(position);

  GlideApp.with(fragment)
    .load(currentUrl)
    .override(imageWidthPixels, imageHeightPixels)
    .into(imageView);
}

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