Murali Murali - 3 months ago 32
Android Question

How to load all the images in the background of a RecyclerView in Android

Hi I am working on a Recycler view with 1000 records, where i need to display remote images. Iam loading 20 records at a time. 6 records can be shown at a time on the screen (based on the screen size of the android device). The recycler view is making a req to the backend for the image when the row is shown on the screen, which is resulting in taking some time to display it on the screen (I am using picasso library for lazy loading). Can you please suggest me how to cache all 20 images in the back ground at a time, this way i can show the image immediately to the user when he scrolls down. (this is what our requirement)

Answer

I think this link has what you need to do but not exactly 20 records

first you need to implement this LinearLayoutManager :

public class PreCachingLayoutManager extends LinearLayoutManager {
private static final int DEFAULT_EXTRA_LAYOUT_SPACE = 600;
private int extraLayoutSpace = -1;
private Context context;

public PreCachingLayoutManager(Context context) {
    super(context);
    this.context = context;
}

public PreCachingLayoutManager(Context context, int extraLayoutSpace) {
    super(context);
    this.context = context;
    this.extraLayoutSpace = extraLayoutSpace;
}

public PreCachingLayoutManager(Context context, int orientation, boolean reverseLayout) {
    super(context, orientation, reverseLayout);
    this.context = context;
}

public void setExtraLayoutSpace(int extraLayoutSpace) {
    this.extraLayoutSpace = extraLayoutSpace;
}

@Override
protected int getExtraLayoutSpace(RecyclerView.State state) {
    if (extraLayoutSpace > 0) {
        return extraLayoutSpace;
    }
    return DEFAULT_EXTRA_LAYOUT_SPACE;
}
}

and then set it as layout manager for you recycle view.

PreCachingLayoutManager layoutManager = new  
PreCachingLayoutManager(getActivity());
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
layoutManager.setExtraLayoutSpace(DeviceUtils.getScreenHeight(getActivity()));
recyclerView.setLayoutManager(layoutManager);