Search code examples
androidfresco

How to Precache 2-3 Images using Fresco in Recycler View


I am loading images in Recycler View using Fresco using the following code. Currently the image loading is started as soon as the user scrolls to any item, and the Fresco load the image and caches it for later, and next time the image is loaded from cache. Is there any way to precache images so that the images can be loaded fast even first time.

public class ProductFeedsRecyclerAdapterV2 extends RecyclerView.Adapter<ProductFeedsRecyclerAdapterV2.ViewHolder> {

    private static final String TAG = ProductFeedsRecyclerAdapterV2.class.getSimpleName();
    private List<ProductFeed> mItems;
    private float ratio;

    Context context;
    String user_id;

    public ProductFeedsRecyclerAdapterV2(Context context, List<ProductFeed> items) {
        mItems = items;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item_brand_feed, viewGroup, false);

        return new ViewHolder(v);
    }


    @Override
    public void onBindViewHolder(final ViewHolder viewHolder, final int i) {

        final ProductFeed feed = mItems.get(i);

        CircleProgressBarDrawable drawable = new CircleProgressBarDrawable();
        drawable.setBackgroundColor(context.getResources().getColor(R.color.gray));
        drawable.setColor(context.getResources().getColor(R.color.colorAccent));

        GenericDraweeHierarchyBuilder builder =
                new GenericDraweeHierarchyBuilder(context.getResources());
        GenericDraweeHierarchy hierarchy = builder
                .setFadeDuration(100)
                .setProgressBarImage(drawable)
                .build();

        hierarchy.setActualImageScaleType(ScalingUtils.ScaleType.FOCUS_CROP);
        hierarchy.setActualImageFocusPoint(new PointF(0.5f,0f));

        Uri uri = Uri.parse(feed.image);
        viewHolder.ivBrandImage.setImageURI(uri);
        viewHolder.ivBrandImage.setHierarchy(hierarchy);
        viewHolder.ivBrandImage.setAspectRatio(1.15f);

    }

    @Override
    public int getItemCount() {
        return mItems.size();
    }


    class ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.ivBrandImage) SimpleDraweeView ivBrandImage;
        ViewHolder(View v) {
            super(v);
            ButterKnife.bind(this, v);
        }
    }

}

Solution

  • Fresco supports prefetching, see http://frescolib.org/docs/using-image-pipeline.html

    You can simply call

    imagePipeline.prefetchToDiskCache(imageRequest, callerContext);
    

    or

    imagePipeline.prefetchToBitmapCache(imageRequest, callerContext);
    

    to prefetch to disk or bitmap cache.